How can I be notified when an element is added to the page?(当元素添加到页面时如何通知我?)
问题描述
我希望在将 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.
这篇关于当元素添加到页面时如何通知我?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:当元素添加到页面时如何通知我?
基础教程推荐
- 直接将值设置为滑块 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01