I've made an ajax call interceptor to listen for XMLHttpRequests.
I would like to modify the request headers of the XHR. For some reason I can only change them in XMLHttpRequest.send()
. Is it to early to modify them in XMLHttpRequest.open()
? It throws the exception that I pasted in the code below.
So, why do I get an error?
(function (open) {
XMLHttpRequest.prototype.open = function () {
this.setRequestHeader('foo', 'bar');
// InvalidStateError: An attempt was made to
// use an object that is not, or is no longer, usable
open.apply(this, arguments);
};
})(XMLHttpRequest.prototype.open);
(function (send) {
XMLHttpRequest.prototype.send = function () {
this.setRequestHeader('foo', 'bar'); // OK
send.apply(this, arguments);
};
})(XMLHttpRequest.prototype.send);
for(var i = 0; i < 3; i++){
var rnd = Math.round(Math.random()*3+1),
httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function () { };
httpRequest.open('GET', '/echo/json?delay=' + rnd);
httpRequest.send();
}
http://jsfiddle.net/zrZ3a/2/
What if you swap:
this.setRequestHeader('foo', 'bar');
open.apply(this, arguments);
to get:
open.apply(this, arguments);
this.setRequestHeader('foo', 'bar');
does it work then?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With