[英]Listen for creation of an element and fire an event when it appears on the page in Chrome Extension
Is it possible to have a Chrome extension listen for the appearance of a yet-to-be-created element? 是否可以让Chrome扩展程序侦听尚未创建的元素的外观?
Say the user clicks a button and the click event creates an element <div id='myDiv'>My Div</div>
and adds it to the page/DOM. 假设用户单击一个按钮,click事件会创建一个元素
<div id='myDiv'>My Div</div>
并将其添加到页面/ DOM中。 Is it possible to set a listener that will automatically fire an event when that element appears? 是否可以设置一个侦听器,该侦听器会在该元素出现时自动触发事件?
Or do I have to resort to polling the page and checking for this element every X amount of milliseconds? 或者我是否必须使用轮询页面并每隔X毫秒检查一次这个元素?
jQuery and other libraries are not an option for me btw. 对我来说,jQuery和其他库不是一个选择顺便说一句。
The new DOM4 MutationObserver can do this. 新的DOM4 MutationObserver可以做到这一点。 I don't think it's widely supported yet, but luckily enough for you, it is supported in Chrome, as
WebKitMutationObserver
. 我不认为它得到了广泛的支持,但幸运的是,它在Chrome中得到了支持,就像
WebKitMutationObserver
。
Modified from the linked tutorial page, this listens for mutations everywhere on the page: 从链接的教程页面修改,它会在页面上的任何位置侦听突变:
var observer = new WebKitMutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
for (var i = 0; i < mutation.addedNodes.length; i++) {
if(mutation.addedNodes[i].id == "myDiv") {
// target node added, respond now...
}
}
});
});
observer.observe(document, { subtree: true });
If you can narrow your listening in observer.observe
to a more specific element than document
, that would give you some performance gain. 如果你可以在
observer.observe
缩小你的听力。 observer.observe
一个比document
更具体的元素,这会给你一些性能提升。
You can use arrive.js , it wraps the Mutation Observers api. 你可以使用arri.js ,它包含了Mutation Observers api。 Usage:
用法:
document.arrive(".test-elem", function() {
// 'this' refers to the newly created element
var newElem = this;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.