我正在实现一个Chrome扩展程序。我想用“#”替换我的Web应用主页上标签中的href属性。问题是,标签可能会被Ajax动态加载,并且可能会被用户操作重新加载。有什么建议可以让Chrome扩展程序检测到Ajax加载的HTML内容吗?
有两种方法可以做到这一点,
jQuery中有一个.ajaxComplete()函数来处理页面上的所有ajax请求。
在内容脚本
中,
var actualCode = '(' + function() {
$(document).ajaxComplete(function() {
alert('content has just been changed, you should change href tag again');
// chaging href tag code will be here
});
} + ')();';
var script = document.createElement('script');
script.textContent = actualCode;
(document.head||document.documentElement).appendChild(script);
script.parentNode.removeChild(script);
这可以通过使用 mutation events 在 content script
中实现。
$(document).bind("DOMSubtreeModified", function() {
alert("something has been changed on page, you should update href tag");
});
你可以使用一些不同的选择器来限制你要控制更改的元素。
$("body").bind("DOMSubtreeModified", function() {}); // just listen changes on body content
$("#mydiv").bind("DOMSubtreeModified", function() {}); // just listen changes on #mydiv content
script.parentNode.removeChild(script);
?这样做不会移除渲染页面上的所有现有脚本吗? - LondonAppDev接受的答案已经过时。截至2019年,Mutation事件已被弃用。人们应该使用 MutationObserver 。以下是纯javascript如何使用它:
// Select the node that will be observed for mutations
var targetNode = document.getElementById('some-id');
// Options for the observer (which mutations to observe)
var config = { attributes: true, childList: true, subtree: true };
// Callback function to execute when mutations are observed
var callback = function(mutationsList, observer) {
for(var mutation of mutationsList) {
if (mutation.type == 'childList') {
console.log('A child node has been added or removed.');
}
else if (mutation.type == 'attributes') {
console.log('The ' + mutation.attributeName + ' attribute was modified.');
}
}
};
// Create an observer instance linked to the callback function
var observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
observer.disconnect();