chenyuxian chenyuxian - 6 months ago 61
Ajax Question

How to override XMLHttpRequest?

I want to override "XMLHttpRequest" this constructor function.

And I just want to alert something when I new a instance, just like this:
(this is not what I actually want to do, just an example)

var ajax_request = new XMLHttpRequest(); //then alert "new a XMLHttpRequest instance!"


then I try this:

var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
alert("new a XMLHttpRequest instance!");
orig_XMLHttpRequest.apply(this, arguments);
};


but when I new an instance,

I get this error at orig_XMLHttpRequest.apply(this, arguments);

TypeError: Constructor XMLHttpRequest requires 'new'


So, which step I do wrong? How can I override XMLHttpRequest? Or it is impossible?

I still try this:

var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
alert("new a XMLHttpRequest instance!");
new (Function.prototype.bind.apply(orig_XMLHttpRequest, arguments));
};

var ajax_request = new XMLHttpRequest();
ajax_request.open("POST", "./php/register.php", true);
ajax_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax_request.onreadystatechange = function() {.....};
ajax_request.send();


but I still got an error :(

TypeError: ajax_request.open is not a function

Answer

Interesting question.

I've been able to modify your second code sample to get something working:

var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
  document.write("new a XMLHttpRequest instance!");
  return new orig_XMLHttpRequest();
};

var ajax_request = new XMLHttpRequest();
ajax_request.open("POST", "./php/register.php", true);
ajax_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajax_request.onreadystatechange = function() {
  if (ajax_request.readyState === XMLHttpRequest.DONE) {
    console.log("request returned status code: " + ajax_request.status);
  }
}
ajax_request.onerror = function(e) {
  console.log("request failed: " + e.target.status);
  }

ajax_request.send();