Modifying request headers in XMLHttpRequest

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/

+4
source share
1 answer

What to do if you change:

 this.setRequestHeader('foo', 'bar'); open.apply(this, arguments); 

To obtain:

 open.apply(this, arguments); this.setRequestHeader('foo', 'bar'); 

Does it work?

+12
source

Source: https://habr.com/ru/post/1485679/


All Articles