Saad Benbouzid
Saad Benbouzid

Reputation: 531

XMLHttpRequest : Firefox Issue when "setRequestHeader"

I have to set custom request headers for my ajax calls (POST). As I'm behind a client/server framework (ZK), I can't master the whole process (from open() to send()). That's why I can only set the request headers as follows, overriding native "onsomething" functions :

var zk_native_function_to_instanciate_a_xhr_OLD = zk_native_function_to_instanciate_a_xhr();
zk_native_function_to_instanciate_a_xhr = function() {
    var xhr = zk_native_function_to_instanciate_a_xhr_OLD ();
    xhr.onloadstart = function () {
      if (xhr.readyState === 1) {
        xhr.setRequestHeader("XX-MY-CUSTOM-HEADER", "foobarhimself");
      }
    }
};

This works very well using Chrome, but doesn't work at all on Firefox. The point is that using Firefox, I only get ready state 4 when I put a breakpoint at the 'if' line. Using Chrome, my breakpoint stops successfully with xhr.readyState equal to '1' (xhr.OPENED), and xhr.readyState still equals 1 when executing xhr.setRequestHeader(...).

And yet, both with Chrome and Firefox, zk_native_function_to_create_a_xhr_OLD() returns me an instance of XMLHttpRequest object (with same default attributes).

Both calls, ie. the send() on Chrome and on Firefox are made asynchronously. To top it all, when I remove the breakpoint on firebug, my line xhr.setRequestHeader seems to be reached because when executed I get following error on console :

InvalidStateError: An attempt was made to use an object that is not, or is no longer, usable

In my opinion, that's because at the time xhr.setRequestHeader() is called, xhr.readyState already equals '4'... Its value changes from 1 to 4 at the speed of life !

How can I resolve this issue ? Or is there another way I can call "xhr.setRequestHeader()", or in another "prototypable" onsomething handler ?

Thanks a lot.

Upvotes: 1

Views: 3547

Answers (1)

Saad Benbouzid
Saad Benbouzid

Reputation: 531

I finally resolved this issue by directly overriding the native open() function, which happens to be called in the embedded framework.

var zk_native_function_to_instanciate_a_xhr_OLD = zk_native_function_to_instanciate_a_xhr();
zk_native_function_to_instanciate_a_xhr = function() {
  var xhr = zk_native_function_to_instanciate_a_xhr_OLD ();
  var xhr_open_base = xhr.open;
  // native XmlHttpRequest.open() signature from XmlHttpRequest API
  xhr.open = function (method, url, async, user, password) {
    xhr_open_base.apply(this, arguments);
    xhr.setRequestHeader("XX-MY-CUSTOM-HEADER", "foobarhimself");
  }
};

Upvotes: 1

Related Questions