小编典典
当你说…
我根据DOM的更改时间找到了另一种方法,但是这使得加载需要很长时间,因此DOM中有太多的事情要做。我需要监听AJAX请求,并在它们完成后再次运行我的代码。
…您在哪里使用突变事件或突变观察者?因为我认为观察员应该在哪里解决该问题。我以前从未对Observers做过任何事情,并使用过Mutation
Summary。它似乎能够完成您想要的事情,只是它直到文件准备就绪/空闲(不确定哪个)才开始观察,因此您可能必须对文件准备就绪进行扫描,然后解雇观察员。
这是我的测试代码(在内容脚本中)的样子……
handleChanges = function(summaries) {
// There may be more things to ignore
var ignore = {
SCRIPT: true,
NOSCRIPT: true,
CDATA: true,
'#comment': true
}
summaries.forEach(function(summary) {
summary.added.forEach(function(node) {
if (!ignore[node.nodeName] || (node.parentNode && !ignore[node.parentNode.nodeName]) && node.nodeValue.trim()) {
node.nodeValue='PAEz woz ere - '+node.nodeValue;
}
})
})
}
var observer = new MutationSummary({
callback: handleChanges,
// required
rootNode: document,
// optional, defaults to window.document
observeOwnChanges: false,
// optional, defaults to false
queries: [{
characterData: true
}]
});
检查XMLHttpRequest的另一种方法是劫持它,它看起来就像(在文档开始时的内容脚本中一样).....
function injectScript(source) {
var elem = document.createElement("script"); //Create a new script element
elem.type = "text/javascript"; //It's javascript
elem.innerHTML = source; //Assign the source
document.documentElement.appendChild(elem); //Inject it into the DOM
}
injectScript("("+(function() {
function bindResponse(request, response) {
request.__defineGetter__("responseText", function() {
console.warn('Something tried to get the responseText');
console.debug(response);
return response;
})
}
function processResponse(request,caller,method,path) {
bindResponse(request, request.responseText);
}
var proxied = window.XMLHttpRequest.prototype.open;
window.XMLHttpRequest.prototype.open = function(method, path, async) {
var caller = arguments.callee.caller;
this.addEventListener('readystatechange', function() {
if (this.readyState === 4)
processResponse(this,caller,method,path);
}, true);
return proxied.apply(this, [].slice.call(arguments));
};
}).toString()+")()");
…我在超级棒的Supper Happy Fun Blog中学不到。
但是,正如您现在可能知道的那样,这对于ajax驱动的站点来说还不够。通常,您必须为网站编写一些特定的内容,否则Mutation
Observer可能会满足您的需求。
2020-07-26