0

I have prototyped the XMLHttpRequest to add additional functionalities.
But when I try to add a custom header to the call it does not work (no errors and no calls in the chrome developer toolbar)

My code:

(function(){
var originalOpenFunction = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function (method, url, async, user, pass) {

    //Add custom header
    this.setRequestHeader('custom-header', 'value');

    originalOpenFunction.call(this, method, url, async, user, pass);
};
})();

$.ajax("http://www.jsfiddle.net");

When I remove the setRequestHeader line, I get the error I expected (cross-origin not allowed).

Note Although I use jquery to test the javascript, the solution to this should be in native javascript.

JsFiddle

1 Answer 1

1

Expose errors by:

$.ajax("http://www.jsfiddle.net").fail(function (e) {
  console.log(e);
});

You will get:

InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': the object's state must be OPENED.

This means you need to call open() before you call setRequestHeader().

Then you will run into the cross domain issue. Make sure you're not trying to do a cross domain request to an unsupported domain. The shell runs from http://fiddle.jshell.net.

Requesting that domain works (returns HTML).

See: http://jsfiddle.net/HfAZN/3/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.