【问题标题】:Can't access an about:blank iframe in IE after the document.domain changesdocument.domain 更改后,无法在 IE 中访问 about:blank iframe
【发布时间】:2013-01-20 20:18:06
【问题描述】:

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:"" 失败。

【问题讨论】:

标签: javascript internet-explorer dom iframe cross-domain-policy


【解决方案1】:

您愿意将 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>');

编辑:如果这是页面上的内联脚本,那么您需要拆分结束 &lt;/script&gt; 标记。见why-split-the-script-tag

【讨论】:

【解决方案2】:

如果 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

【讨论】:

    【解决方案3】:

    我一直通过将 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>
    

    【讨论】:

    • 不幸的是,脚本所在的域没有写入权限(Javascript 代码本身是一个需要在任何地方运行的小部件)。
    猜你喜欢
    • 1970-01-01
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2012-12-25
    • 2011-10-13
    • 2010-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多