問題描述
我正在為 Firefox、Safari、Chrome 開發(fā)一個瀏覽器插件,它將攔截頁面上的數(shù)據(jù),針對正則表達式運行它,然后如果匹配 - 重新格式化它.我使用以下方法處理頁面加載:
I am working on a browser plugin for Firefox, Safari, Chrome that will intercept data on the page, run it against a regex and then if it matches - reformat it. I have this working on page load using:
var meth = {
replaceInElement : function(element, find, replace) {
// iterate over child nodes and replace
},
run : function(evt){
// doc is the document that triggered "run" event
if (!(evt.target.nodeName === "#document")) { return; }
var doc = evt.target; // document that triggered "onload" event
if (!(doc instanceof HTMLDocument)) { return; }
if (!doc.location) { return; }
// perform substitutions on the loaded document
var find = /regex/gi
meth.replaceInElement(doc.body, find, function(match) {
var new_content;
//do stuff
return new_content;
});
//content.document.addEventListener('DOMNodeInserted', ezcall.node_inserted, false);
}
}
window.addEventListener("load", meth.run, false);
這適用于靜態(tài)頁面,但對于使用 ajax 調(diào)用的任何內(nèi)容,它都會失敗.我找不到合適的偵聽器或弄清楚如何攔截 XMLHttpRequest.
This is working for static pages, but for anything using ajax calls, it fails. I cannot find the right listener or figure out how to intercept the XMLHttpRequest.
我為 XMLHttpRequest 嘗試了類似的事件偵聽器,但沒有成功.
I have tried similar event listeners for XMLHttpRequest with no luck.
XMLHttpRequest.addEventListener('load', meth.run, false);
我想攔截請求并修改內(nèi)容.或者找到更新的目標,在ajax調(diào)用完成后掃描.
I would like to either intercept the request and modify the content. Or find the target that was updated and scan it after the ajax call is finished.
更新:
我會接受無法完成的回答,但我需要一些支持數(shù)據(jù)來說明為什么無法完成.
I will accept an answer that says it cannot be done, but I will need some supporting data as to why it cannot be done.
推薦答案
比較臟但是你可以覆蓋XMLHttpRequest.prototype.open
.這是一個演示頁面.由于您正在編寫擴展程序,因此您必須將此代碼放在頁面上下文中:
Rather dirty but you can overwrite XMLHttpRequest.prototype.open
. Here is a Demo page. Since you're writing an extension, you must put this code in page context:
(function() {
// save reference to the native method
var oldOpen = XMLHttpRequest.prototype.open;
// overwrite open with our own function
XMLHttpRequest.prototype.open = function(method, url, async, user, pass) {
// intercept readyState changes
this.addEventListener("readystatechange", function() {
// your code goes here...
console.log("Interception :) " + this.readyState);
}, false);
// finally call the original open method
oldOpen.call(this, method, url, async, user, pass);
};
})();
在這之后你可以做任何我猜的事情.替換 instance.readystatechange
,替換 instance.addEventListener
,或者監(jiān)聽突變事件(雖然它們是 已棄用).
After this you can do anything I guess. Replace instance.readystatechange
, replace instance.addEventListener
, or listen to mutation events (although they are deprecated).
這篇關(guān)于檢索和修改 XMLHttpRequest 的內(nèi)容的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!