[英]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.