在ie下如果两个 子站点的iframe页面之间需要交互,就必须在两个页面中都配置document.domain属性,比如页面A是http://xxx.aaa.com/a.html ,页面B是http://yyy.aaa.com/b.html 这时候两个页面中都写上document.domain=”aaa.com”,这样两个页面就可以交互了。
上面的情况只适用于嵌入的页面是事先已经已<iframe src=”xxxxx”></iframe>的形式在页面中写好了,如果要在页面中动态创建一个iframe标签,上面的方法就不适用 了,这个问题经常会出现在富文本编辑器的代码中。最近这个问题可是困扰了我很长时间,今天总算解决了,其实问题就出在document.domain生效 的时机,做法就是在被调用的iframe页面中设置一个脚本变量,然后在父页面中不停地去尝试获取这个值,什么时候获得到了,就停下来执行自己的业务逻 辑。事先声明一下这个做法是参考了国外的一篇博客文章。
场景如下:
要在页面A(http://xxx.aaa.com/a.html )中动态创建一个 iframe,iframe的src指向页面B(http://yyy.aaa.com/b.html ), 然后在页面A中获取或更改页面B中的内容。
代码如下:
页面A:
<html>
<head>
<title>http://xxx.aaa.com/a.html</title>
</head>
<body>
<script type="text/javascript">
document.domain = 'aaa.com';
var iframe = document.createElement("iframe");
iframe.src = 'http://yyy.aaa.com/b.html';
document.body.appendChild(iframe);
var timer = setInterval(function(){
if(iframe.contentWindow.canAccess){
clearInterval(timer);
//iframe.contentWindow.document.body.innerHTML = '这是新设置的页面内容';
alert('iframe的页面内容是:' + iframe.contentWindow.document.body.innerHTML);
}
}, 100);
</script>
</body>
</html>
页面B:
<html>
<head>
<title>http://yyy.aaa.com/b.html</title>
<script type="text/javascript">
document.domain = 'aaa.com';
var canAccess = true;
</script>
</head>
<body>
这是页面的原始内容
</body>
</html>