简体   繁体   中英

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM