Skip to content
Advertisement

MutationObserver – how to detect dom changes within iframe

Let me first explain the problem: My script has a mutationobserver, which detects added nodes, and does some processing on the content – like compare and highlight some values. The current implementation detects changes in the entire document body, the target looks like this

var target = document.querySelector('body');

Everything works well, except when there is an iframe. Some client pages have an iframe or multiple iframes, others do not.

My script is added within a script tag in the parent document.

Question: a) is it possible to get the same MutationObserver to detect changes in body and iframe ? ie everything in the dom including the iframe b) if it is not possible with a single observer, what is the alternate method?

please note: my script can only go to the main/parent document

Advertisement

Answer

You will need to have a different mutationobserver for each iframe that you want to watch. So if you want one on the current document you will also need a different observer there as well.

If you have access to the iframe, you can then watch it like so:

// Get the iframe body
let iframe = document.getElementById('my-iframe').document.body
// Setup the config
let config = { attributes: true, childList: true }
// Create a callback
let callback = function(mutationsList) { /* callback actions */ }

// Watch the iframe for changes
let observer = new MutationObserver(callback)
observer.observe(iframe, config)

If the iframe is on a sub-domain of the parent you can use this in the iframe:

// where parent.com is the parent domain of the iframe
document.domain = 'parent.com'

Note: document.domain is now deprecated.

If you do not own the domain of the iframe you’re out of luck.

Advertisement