将元素添加到页面时如何通知我? [英] How can I be notified when an element is added to the page?

查看:73
本文介绍了将元素添加到页面时如何通知我?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望我选择的功能在将DOM元素添加到页面时运行.这是在浏览器扩展的上下文中,因此该网页独立于我运行,并且我无法修改其来源.我在这里有什么选择?

I want a function of my choosing to run when a DOM element is added to the page. This is in the context of a browser extension, so the webpage runs independently of me and I cannot modify its source. What are my options here?

我想,从理论上讲,我可以只使用setInterval()来连续搜索元素的存在并在元素存在的情况下执行我的操作,但是我需要一个更好的方法.

I guess that, in theory, I could just use setInterval() to continually search for the element's presence and perform my action if the element is there, but I need a better approach.

推荐答案

警告!

此答案现在已过时. DOM级别4引入了 MutationObserver ,为不推荐使用的产品提供了有效的替代方法突变事件.请参阅此答案,以获得比此处提供的解决方案更好的解决方案.严重地.不要每100毫秒轮询一次DOM.这会浪费CPU资源,而您的用户会讨厌您.

This answer is now outdated. DOM Level 4 introduced MutationObserver, providing an effective replacement for the deprecated mutation events. See this answer for a better solution than the one presented here. Seriously. Don't poll the DOM every 100 milliseconds; it will waste CPU power and your users will hate you.

由于变异事件在2012年被弃用,并且您无法控制插入的元素,因为它们是别人的代码添加的,唯一的选择是不断地检查它们.

Since mutation events were deprecated in 2012, and you have no control over the inserted elements because they are added by someone else's code, your only option is to continuously check for them.

function checkDOMChange()
{
    // check for any new element being inserted here,
    // or a particular node being modified

    // call the function again after 100 milliseconds
    setTimeout( checkDOMChange, 100 );
}

一旦调用此函数,它将每100毫秒运行一次,即1/10(十分之一秒).除非您需要实时元素观察,否则就足够了.

Once this function is called, it will run every 100 milliseconds, which is 1/10 (one tenth) of a second. Unless you need real-time element observation, it should be enough.

这篇关于将元素添加到页面时如何通知我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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