Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)

like image 347
mikemaccana Avatar asked Dec 19 '11 11:12

mikemaccana


People also ask

How do I view events fired on an element in Chrome?

To view events fired on an element, follow the below steps in Google Chrome: Open Google Chrome and press F12 to open Dev Tools. Go to Event Listener Breakpoints, on the right: Click on the events and interact with the target element.

What is an unpacked Chrome extension?

Chrome extensions can be either packed or unpacked. Packed extensions are a single file with a . crx extension. Unpacked extensions are a directory containing the extension, including a manifest. json file.

How do I view javascript events in Chrome?

Right-click on the search icon button and choose “inspect” to open the Chrome developer tools. Once the dev tools are open, switch to the “Event Listeners” tab and you will see all the event listeners bound to the element. You can expand any event listener by clicking the right-pointing arrowhead.


2 Answers

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();
like image 70
gkalpak Avatar answered Oct 18 '22 22:10

gkalpak


As mentioned, I am not creating my own elements, so firing off an event when I create the element isn't an option.

The best solution to this is the Mutation Observer API, for which the Mutation Summary provides a friendly interface.

like image 43
mikemaccana Avatar answered Oct 19 '22 00:10

mikemaccana