Search code examples
javascriptinternet-explorerdomiframecross-domain-policy

Can't access an about:blank iframe in IE after the document.domain changes


Does anyone know of any workarounds to creating an about:blank iframe on a page in IE when the document.domain has changed?

IE doesn't seem to allow access to empty/dynamic iframes after the document.domain property has been altered.

For example, imagine you're dynamically creating an iframe and then injecting some html into it:

// Somewhere else, some 3rd party code changes the domain 
// from something.foo.com to foo.com 
document.domain = 'jshell.net';

var iframe = document.createElement('iframe');
document.body.appendChild(iframe);

// In IE, we can't access the iframe's contentWindow! Access is denied.
iframe.contentWindow.document.body.style.backgroundColor = 'red';

Here's a live example on jsfiddle: http://jsfiddle.net/XHkUT/

You'll notice it works fine in FF/Webkit, but not IE. It's particularly frustrating because this affects iframes created after the document.domain property has changed (as in the example above).

The IE rule seems to be "if you create a dynamic/empty iframe after you change document.domain, you can't access its DOM."

Setting the iframe src to about:blank javascript:void(0) or javascript:"" has been unsuccessful.


Solution

  • Are you happy to change the domain of the iframe to? The following works (for me) in IE7,9

    document.domain = 'jshell.net';
    
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);
    iframe.src = "javascript:document.write('<script>document.domain=\"jshell.net\"</script>')";
    
    // Now write some content to the iframe
    iframe.contentWindow.document.write('<html><body><p>Hello world</p></body></html>');
    

    Edit: If this is inline script on a page then you need to split the closing </script> tag up. See why-split-the-script-tag