Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
543 views
in Technique[技术] by (71.8m points)

javascript - Chrome Extension: fire an event when element created?

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.

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)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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.

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();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...