I made an ajax call interceptor to listen for XMLHttpRequests.
I would like to change the XHR request headers. For some reason, I can only change them in XMLHttpRequest.send() . Do they used to modify them in XMLHttpRequest.open() ? It throws an exception, which I inserted in the code below.
So why am I getting an error message?
(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/
Johan source share