I am creating a web application with various JS libraries (AngularJS, OpenLayers, ...) and need the ability to intercept all AJAX responses in order to be able, in case the expired user session (the response is returned with 401 Unauthorized status) so that redirect it to the login page.
I know that AngularJS offers interceptors to manage such scenarios, but could not find a way to achieve such an injection into OpenLayers queries. So I chose the Vanilla JS approach.
Here I found this piece of code ...
(function(open) { XMLHttpRequest.prototype.open = function(method, url, async, user, pass) { this.addEventListener("readystatechange", function() { console.log(this.readyState);
... which I adapted and looks like it behaves as expected (only tested it on the latest Google Chrome).
As soon as it modifies the XMLHTTPRequest prototype, I wonder how dangerous this can be, or it can cause serious performance problems. And, by the way, will there be some valid alternative?
Update: How to intercept requests before sending them
The previous trick is working fine. But what if in the same scenario you want to enter some headers before sending a request? Follow these steps:
(function(send) { XMLHttpRequest.prototype.send = function(data) {
javascript ajax interceptor
mettjus Aug 15 '14 at 23:44 2014-08-15 23:44
source share