在文档.域更改后无法访问 IE 中的关于:空白 iframe



document.domain发生更改时,有人知道在IE中的页面上创建about:blank iframe的解决方法吗?

在更改了document.domain属性之后,IE似乎不允许访问空/动态iframe。

例如,假设您正在动态创建一个iframe,然后向其中注入一些html:

// 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';

以下是jsfiddle上的一个实际示例:http://jsfiddle.net/XHkUT/

您会注意到它在FF/Webkit中运行良好,但在IE中运行不好。这尤其令人沮丧,因为这会影响在document.domain属性发生更改后创建的iframe(如上例所示)。

IE规则似乎是"如果你在更改document.domain后创建了一个动态/空的iframe,你就不能访问它的DOM。"

将iframe src设置为about:blank javascript:void(0)javascript:""失败。

您愿意将iframe的域更改为吗?以下工作(对我来说)在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>');

编辑:如果这是页面上的内联脚本,那么您需要将关闭的</script>标记拆分。查看拆分脚本标记的原因

我一直通过将iframe的src设置为与父域位于同一域的空白文件来解决此类问题。如果有可能在jshell.net上创建这样一个文件,我建议这样做:

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

其中blank.html只包含一个小样板,例如:

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

如果iframe.src和document.location位于不同的域(或子域),则根据定义,您无权从父级访问子级。但是,您可以从子对象访问父对象。加载跨域JavaScript时使用的技术之一是使用iframe在加载时可以在容器窗口中调用方法的事实。

只有当这两个文档在不同的子域上时,您才能调整document.domain以匹配iframe.src的域以启用访问。

点击此处阅读更多关于同源政策的信息:

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

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

最新更新