[英]How to override XMLHttpRequest in Firefox's WebExtension
[英]How to override XMLHttpRequest?
我想覆盖“XMLHttpRequest”这个构造函数。
我只是想在我新建一个实例时提醒一些事情,就像这样:(这不是我真正想要做的,只是一个例子)
var ajax_request = new XMLHttpRequest(); //then alert "new a XMLHttpRequest instance!"
然后我试试这个:
var orig_XMLHttpRequest = window.XMLHttpRequest;
window.XMLHttpRequest = function() {
alert("new a XMLHttpRequest instance!");
orig_XMLHttpRequest.apply(this, arguments);
};
但是当我新建一个实例时
我在 orig_XMLHttpRequest.apply(this, arguments);
TypeError: Constructor XMLHttpRequest requires 'new'
那么,我做错了哪一步? 如何覆盖 XMLHttpRequest? 或者这是不可能的?
我也试试这个:
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();
但我仍然遇到错误:(
TypeError: ajax_request.open is not a function
有趣的问题。
我已经能够修改您的第二个代码示例以使其正常工作:
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();
您可以使用原型 open 和 send 方法来覆盖 XMLHttpRequest。
XMLHttpRequest.prototype.open = function (method, url, async, user, password) {
...
}
和
XMLHttpRequest.prototype.send = function () {
...
}
查看完整示例: https : //runkiss.blogspot.com/2021/03/capture-xmlhttprequest-calls.html
试试这个:
window.XMLHttpRequest = function() {
alert("new a XMLHttpRequest instance!");
orig_XMLHttpRequest.apply(this, arguments);
};
(已编辑 - 我在原来的方法中犯了一个错误)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.