当元素添加到页面时如何通知我?
我希望在将 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,为弃用的突变事件.请参阅 this answer 另一个问题,以获得比此处提供的更好的解决方案.严重地.不要每 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.
相关文章