javascript – 在document.domain更改后无法访问about:空白iframe在IE中

有没有人知道在document.domain发生更改时在IE中创建一个关于:空白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>标记.见why-split-the-script-tag

相关文章

什么是深拷贝与浅拷贝?深拷贝与浅拷贝是js中处理对象或数据...
前言 今天复习了一些前端算法题,写到一两道比较有意思的题:...
最近在看回JavaScript的面试题,this 指向问题是入坑前端必须...
js如何实现弹出form提交表单?(图文+视频)
js怎么获取复选框选中的值
js如何实现倒计时跳转页面