Skip to content

Instantly share code, notes, and snippets.

@nchase
Last active May 10, 2019 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nchase/84b148a1603c8c2660a2 to your computer and use it in GitHub Desktop.
Save nchase/84b148a1603c8c2660a2 to your computer and use it in GitHub Desktop.
MutationObserver doesn't observer inner frame on `document.write` in IE11
<h1>Run A Web Server Here Via <pre style="display: inline-block; background-color: #ddd; padding: 0.5em; border-radius: 5px;">python -m SimpleHTTPServer 9999</pre><h1>
Outer Frame. Hello!
<br/>
<iframe id="our-frame" style="width: 100%;"></iframe>
<script src="script.js"></script>
(function() {
var iframe = document.querySelector('iframe#our-frame');
// todo: use a setInterval fallback for older browsers
if (!window.MutationObserver) {
// older browsers don't get responsive iframe height, for now
return;
}
console.log('attaching an iframe observer...\n\n');
var iframeObserver = new MutationObserver(function(){
// this code should run every time a mutation is detected
// wherever we attach the observer:
console.log('iframe mutation observed!');
});
var interval = setInterval(function(){
if (iframe.contentWindow && iframe.contentWindow.document) {
iframeObserver.observe(iframe.contentWindow.document, {
attributes: true,
subtree: true,
childList: true,
characterData: true
});
console.log('now that we have a handle on our inner frame and an observer is set up there, let\'s write some stuff to it. this should trigger a mutation, which should trigger an "iframe mutation observed!" log message.\n\nsince the observer should be attached, the same thing should also happen through the browser\'s console e.g. `document.querySelector(\'#our-frame\').contentWindow.document.write(\'foo\');`\n\n');
iframe.contentWindow.document.write('hello');
clearInterval(interval);
}
}, 100);
})();
@ZeeshanAdilButt
Copy link

did you find a solution for this? I'm unable to attach mutation observer to Iframe

@mclark-newvistas
Copy link

I ended up delaying 100ms before attaching the observer in Chrome - the body DOM object changed at some point. Might work for you, if a bit ugly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment