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

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

问题描述

我希望在将 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 Level 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 to another question 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天全站免登陆