I have an iframe that is rendering content from another domain. Obviously I cannot access the contentDocument from the other domain (returns null). But when a user performs an action on the rendered iframe, it redirects back to my domain. So at that point I am able to read the document. Basically once the contentDocument is not null, I want to perform an action.
Currently I'm just trying to fire an alert if a child of the iframe (in this case its contentDocument mutates...
window.onload = () => {
setTimeout(initializeObserver, 2000)
}
const initializeObserver = () => {
const iframe = document.getElementById('my_iframe')
observer.observe(
iframe,
{
attributes: true,
childList: true,
subtree: true
}
)
}
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
if(mutation.addedNodes.length) {
alert("SOMETHING HAPPENED!")
}
})
})
But the alert never fires even when child nodes are added and elements within the iframe change. I've read a lot of examples, but maybe I'm still missing how this works. Can someone help explain why this observer isn't triggering on the mutation?
Thanks in advance
When a browsing context in an
<iframe>has itslocationchanged, thesrcattribute of the containing<iframe>doesn't change, so your page can not see any difference.What you could do since you apparently control the other page is to post a message to your main page.
Then you just have to listen for that message and you know your frame has come back.