[英]How to override XMLHttpRequest?
I want to override "XMLHttpRequest" this constructor function.我想覆盖“XMLHttpRequest”这个构造函数。
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);我在 orig_XMLHttpRequest.apply(this, arguments);
TypeError: Constructor XMLHttpRequest requires 'new'
So, which step I do wrong?那么,我做错了哪一步? How can I override XMLHttpRequest?
如何覆盖 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.您可以使用原型 open 和 send 方法来覆盖 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查看完整示例: 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) (已编辑 - 我在原来的方法中犯了一个错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.