我正在开发Google Chrome扩展程序,它会在某个网站中找到一些元素并以某种方式更改它们(这么多“某些”,嗯:-))。加载HTML时不显示这些元素,并将它们加载到页面的脚本中。而且,它们可以出现得更晚。
目前,我每隔一段时间就会运行检查,并忽略已处理的元素:
body
但这看起来很愚蠢,在我看来表现很差。
我可以在创建/更改元素时创建一些触发器吗?这样做的惯用JS方式是什么?
答案 0 :(得分:3)
是的,你可以。一种方法是使用MutationObservers。
MutationObserver
MutationObserver为开发人员提供了一种对DOM中的更改做出反应的方法。它被设计为DOM3事件规范中定义的Mutation事件的替代。
如何从MDN:
中取得的示例// select the target node
var target = document.querySelector('#some-id');
// create an observer instance
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
console.log(mutation.type);
});
});
// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };
// pass in the target node, as well as the observer options
observer.observe(target, config);
// later, you can stop observing
observer.disconnect();
答案 1 :(得分:0)
您可以使用“Mutations events”来侦听body DOM上的更改。 https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Mutation_events
例如,如果您想要在将元素添加到正文时进行侦听:
var body = document.querySelector('body');
body.addEventListener("DOMNodeInserted", function (ev) {
}, false);