监听创建元素并在Chrome扩展程序中的页面上显示时触发事件 [英] Listen for creation of an element and fire an event when it appears on the page in Chrome Extension

查看:775
本文介绍了监听创建元素并在Chrome扩展程序中的页面上显示时触发事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能让Chrome扩展程序侦听尚未创建的元素的外观?

假设用户点击一个按钮并点击事件会创建一个元素< div id ='myDiv'>我的div< / div> 并将其添加到页面/ DOM中。是否有可能设置一个监听器,当元素出现时会自动触发一个事件?



或者我必须求助于轮询页面并每X检查一次这个元素毫秒数量?

jQuery和其他库不适合我btw。

解决方案

新的 DOM4 MutationObserver 可以做到这一点。我认为它还没有得到广泛的支持,但幸运的是,它在Chrome中支持,如 WebKitMutationObserver



在链接教程页面中进行了修改,它会监听页面上的各处突变:

  var observer = new WebKitMutationObserver(function (突变){
mutations.forEach(function(mutation){
for(var i = 0; i< mutation.addedNodes.length; i ++){
if(mutation.addedNodes [ i] .id ==myDiv){
//添加了目标节点,现在回复...
}
}
});
});
observer.observe(document,{subtree:true});

如果您可以在 observer.observe 转换为比文档更具体的元素,这会给你一些性能提升。


Is it possible to have a Chrome extension listen for the appearance of a yet-to-be-created element?

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. 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?

jQuery and other libraries are not an option for me btw.

解决方案

The new DOM4 MutationObserver can do this. I don't think it's widely supported yet, but luckily enough for you, it is supported in Chrome, as 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.

这篇关于监听创建元素并在Chrome扩展程序中的页面上显示时触发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆