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

牧云@^-^@ 提交于 2019-12-04 01:54:35
Sean Hogan

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

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>

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!