Can't access an about:blank iframe in IE after

2019-04-05 14:17发布

问题:

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.

回答1:

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



回答2:

I've always worked around issues like this by setting the iframe's src to a blank file that lives on the same domain as the parent's domain. If it's possible to create such a file on jshell.net, I would recommend something like:

var iframe = document.createElement('iframe');
iframe.src = 'http://jshell.net/blank.html';
document.body.appendChild(iframe);

Where blank.html just contains a little boilerplate, for example:

<html><head><title>about:blank</title><head><body></body></html>


回答3:

If the iframe.src and document.location are on different domains (or subdomains) you by definition do not have access from the parent to the child. However, you have access from the child to the parent. One of the techniques used when loading cross-domain JavaScript is using the fact that the iframe can call a method in the container window when loaded.

Only if the two documents are on different subdomains, you may tweak the document.domain to match the domain of the iframe.src to enable access.

Read more about same origin policy here:

http://en.wikipedia.org/wiki/Same_origin_policy

http://softwareas.com/cross-domain-communication-with-iframes