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

JavaScript

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:

JavaScript

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

JavaScript

Note: document.domain is now deprecated.

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

Advertisement