I am writing a chrome extension where I want to fetch all the images exist on a page but some of the images load after some time (may be through ajax) which I could not fetch once the DOM is idle. Is there any way to track the DOM change after the page is loaded?
Asked
Active
Viewed 2.3k times
2 Answers
34
Updated for 2020:
The recommended way nowadays is to use the Mutation Observer API.
let observer = new MutationObserver(mutations => {
for(let mutation of mutations) {
for(let addedNode of mutation.addedNodes) {
if (addedNode.nodeName === "IMG") {
console.log("Inserted image", addedNode);
}
}
}
});
observer.observe(document, { childList: true, subtree: true });

Jeril Sebastian
- 793
- 7
- 10
-
3This code should be added to background.js? – Vikalp Jain Dec 31 '20 at 14:29
-
10This should be in a content script. Only content scripts can access the DOM. – Jeril Sebastian Dec 31 '20 at 18:26
-
You mean content scripts can only access the DOM. Right? – Matt Montag Apr 19 '23 at 22:53
29
You can use document.addEventListener with the DOMNodeInserted event. Your callback will have to check each node insertion to see if it is the type of node you are looking for. Something like the following should work.
function nodeInsertedCallback(event) {
console.log(event);
};
document.addEventListener('DOMNodeInserted', nodeInsertedCallback);

abraham
- 46,583
- 10
- 100
- 152
-
1Thanks abraham. It worked. For those who do not know were to put the above code: http://reminiscential.wordpress.com/2011/10/04/building_google_reader_plugin/ – codef0rmer Jan 17 '12 at 11:54
-
16Heads up: this event is **deprecated**. The modern way is to use DOM mutation observers, and [this](http://stackoverflow.com/a/11546242/934239) is the canonical answer. – Xan Jun 18 '14 at 13:05