Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 577
smithclay Avatar asked Feb 05 '13 19:02

smithclay


People also ask

Can I load an iframe from a different domain?

Generally, web application allows script running between pages(parent and iframe pages) in the same domain based on same-origin-policy. Unfortunately it does not support scripts if different domain. The policy does not allow it.

Why is it bad to set the document domain to a parent domain?

It undermines the security protections provided by the same origin policy, and complicates the origin model in browsers, leading to interoperability problems and security bugs. Attempting to set document. domain is dangerous.

What is #document in iframe?

Definition and Usage. The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.


1 Answers

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

like image 115
Sean Hogan Avatar answered Sep 30 '22 04:09

Sean Hogan