Chrome扩展程序:创建元素时触发事件? [英] Chrome Extension: fire an event when element created?

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

问题描述

我想在元素添加到文档时触发事件。我已阅读关于on()的 jQuery文档以及事件列表,但没有一件事情似乎涉及元素创建。

I'd like to fire an event when an element is added to the document. I've read the JQuery documentation for on() and the list of events but none of the events seem to concern element creation.

我必须监视DOM,因为我无法控制何时将元素添加到文档中(因为我的Javascript是Chrome扩展内容脚本)

I must monitor the DOM as I do not control when the element is added to the document (as my Javascript is a Chrome Extension content script)

推荐答案

我知道这是一个老问题,已经有了答案,但由于事情已经改变,我想我会为登陆此页面的人添加一个更新的答案,寻找答案。

I know this is an old question, that already has an answer, but since things have changed, I thought I'd add an updated answer for people landing on this page looking for an answer.

DOM突变事件 已被弃用。根据MDN(关于 DOM突变事件):

The DOM Mutation Events have been deprecated. According to MDN (regarding DOM Mutation Events):


不推荐使用

此功能已从网络中移除。尽管一些浏览器可能仍然支持它,但它正在被丢弃。不要在旧项目或新项目中使用它。使用它的页面或Web应用程序可能随时中断。

Deprecated
This feature has been removed from the Web. Though some browsers may still support it, it is in the process of being dropped. Do not use it in old or new projects. Pages or Web apps using it may break at any time.

应该使用新的 MutationObserver API ,这也更有效。

突变摘要 库现在提供了一个)

One should use the new MutationObserver API, which is also more efficient.
(The mutation-summary library now provides a useful inteface to this new API.)

示例用法:

Example usage:

// Create an observer instance.
var observer = new MutationObserver(function (mutations) {
  mutations.forEach(function (mutation) {
    console.log(mutation.type);
  });
});

// Config info for the observer.
var config = {
  childList: true, 
  subtree: true
};

// Observe the body (and its descendants) for `childList` changes.
observer.observe(document.body, config);

...

// Stop the observer, when it is not required any more.
observer.disconnect();

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

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