Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modiying request headers in an XMLHttpRequest

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/

like image 218
Johan Avatar asked Dec 15 '22 09:12

Johan


1 Answers

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?

like image 136
Halcyon Avatar answered Jan 13 '23 04:01

Halcyon