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.
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.
Share Improve this question edited Jun 20, 2012 at 23:00 Ry-♦ 225k56 gold badges490 silver badges497 bronze badges asked Jun 20, 2012 at 22:57 Jim_CSJim_CS 4,17213 gold badges46 silver badges81 bronze badges 4- Why not keep track of the button clicks? Or will it load through other means? – TheZ Commented Jun 20, 2012 at 23:04
- It is actually being created with an AJAX callback but I just phrased it in the most straightforward way for the sake of example. So I have to listen for the creation/appearance of the element. – Jim_CS Commented Jun 20, 2012 at 23:28
- Duplicate? stackoverflow.com/questions/7434685/… ... In any case it looks like the most elegant solution is now deprecated (DOM Mutation Events), but there is a hacky solution posted here: stackoverflow.com/questions/6997826/… – Cecchi Commented Jun 21, 2012 at 0:43
- @Cecchi This isn't quite a duplicate, since this question specificallly excludes jQuery. – apsillers Commented Jun 21, 2012 at 15:52
2 Answers
Reset to default 14The 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;
});