I think I have come up with a solution to your problem. It involves using the MutationObserver API, in order to detect changes to the iFrame's DOM.
MutationObserver provides developers a way to react to changes in a
DOM. It is designed as a replacement for Mutation Events defined in
the DOM3 Events specification.
I also used the window.postMessage API to notify the parent page when the MutationObserver
has detected DOM events, so as to allow the parent to respond.
I have created a simple example below. Please note that I have used *
for origin, but it is recommended that you do origin checks for security reasons. Also note that Chrome doesn't allow frames to access other frames in the local file system, but it will work on a web server or you can test locally using FireFox, which doesn't have that restriction.
iframe.html
<head>
<meta charset="utf-8">
</head>
<body>
<script>
var observer = new MutationObserver(function(mutations) {
mutations.forEach(function(mutation) {
if (mutation.type == 'childList') {
if (mutation.addedNodes.length >= 1) {
if (mutation.addedNodes[0].nodeName != '#text') {
window.parent.postMessage("DOMChanged", "*");
}
} else if (mutation.removedNodes.length >= 1) {
window.parent.postMessage("DOMChanged", "*");
}
} else if (mutation.type == 'attributes') {
window.parent.postMessage("DOMChanged", "*");
}
});
});
var observerConfig = {
attributes: true,
childList: true,
characterData: true
};
// listen to all changes to body and child nodes
var targetNode = document.body;
observer.observe(targetNode, observerConfig);
</script>
</body>
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div>
<input type="submit" value="Update iFrame" onclick="updateiFrameDOM()" />
</div>
<iframe src="iframe.html" id="iframeResult"></iframe>
<script>
function updateiFrameDOM() {
var ifr = document.getElementById("iframeResult");
var ifrw = (ifr.contentWindow) ? ifr.contentWindow : (ifr.contentDocument.document) ? ifr.contentDocument.document : ifr.contentDocument;
var div = document.createElement("div");
var text = document.createTextNode("Hello");
div.appendChild(text);
var body = ifrw.document.getElementsByTagName("body")[0];
body.appendChild(div);
}
// Create IE + others compatible event handler
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
// Listen to message from child window
eventer(messageEvent, function(e) {
console.log(e.data);
}, false);
</script>
</body>
</html>
Some additional sources I used:
Respond to DOM Changes with Mutation Observers
window.postMessage Tip: Child-To-Parent Communication
I hope this helps you.