Jim_CS
Jim_CS

Reputation: 4172

Listen for creation of an element and fire an event when it appears on the page in Chrome Extension

Is it possible to have a Chrome extension listen for the appearance of a yet-to-be-created element?

Say the user clicks a button and the click event creates an element <div id='myDiv'>My Div</div> and adds it to the page/DOM. Is it possible to set a listener that will automatically fire an event when that element appears?

Or do I have to resort to polling the page and checking for this element every X amount of milliseconds?

jQuery and other libraries are not an option for me btw.

Upvotes: 11

Views: 5347

Answers (2)

Uzair Farooq
Uzair Farooq

Reputation: 2427

You can use arrive.js, it wraps the Mutation Observers api. Usage:

document.arrive(".test-elem", function() {
    // 'this' refers to the newly created element
    var newElem = this;
});

Upvotes: 3

apsillers
apsillers

Reputation: 115910

The new DOM4 MutationObserver can do this. I don't think it's widely supported yet, but luckily enough for you, it is supported in Chrome, as WebKitMutationObserver.

Modified from the linked tutorial page, this listens for mutations everywhere on the page:

var observer = new WebKitMutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
        for (var i = 0; i < mutation.addedNodes.length; i++) {
            if(mutation.addedNodes[i].id == "myDiv") {
                // target node added, respond now...
            }
        }
    });
});
observer.observe(document, { subtree: true });

If you can narrow your listening in observer.observe to a more specific element than document, that would give you some performance gain.

Upvotes: 14

Related Questions