简体   繁体   中英

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 also 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

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();

You can use the prototype open and send methods to override the XMLHttpRequest.

XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
...
}

and

XMLHttpRequest.prototype.send = function () {
...
}

see full example at: https://runkiss.blogspot.com/2021/03/capture-xmlhttprequest-calls.html

Try this:

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

(EDITED - I made a mistake in my original approach)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM