JavaScript 中 iframe 跨域通信与同域读写兼容性测试

作者:望舒

时间:2026-10-27

浏览:600

本文通过九个不同版本的浏览器测试,详细解析了 iframe 在同域、跨子域及完全跨域场景下的数据交互方案。重点对比了 document.domain 设置与 hash 通信机制的兼容性,并提供了父页面与子页面互相读写内容的具体代码实现及注意事项。

文章目录

iframe 同域与跨域通信概述

同域或跨子域环境下,父页面与子页面可便捷地进行数据读写;全不同域时,可通过修改 hash 实现通信。下文在九种不同版本的浏览器中执行了相关数据传输与变更的兼容性验证。


同域或跨子域读写操作 iframe 里的内容
父页面读写操作子页面:

同域或跨子域读写操作 iframe 里的内容

代码示例如下:

<iframe id="test-iframe" name="test-iframe" src="child.html" scrolling="no" frameborder="0"></iframe>
<script>
window.onload = function () {
  /*
* 以下两种获取节点内容的方法均可行。
* 鉴于 IE6, IE7 不支持 contentDocument 属性,此处采用通用方法
* window.frames["iframe Name"] 或 window.frames[index]
   */
var d = window.frames["test-iframe"].document;
d.getElementsByTagName('h1')[0].innerHTML = 'pp';
alert(d.getElementsByTagName('h1')[0].firstChild.data);
}
</script>

注:

务必通过 window.onload 方法访问 iframe 内的节点,否则浏览器将报错提示拒绝访问。在 IE8, Firefox3.6, Opera11 环境下,于 DOMReady 阶段亦可访问 iframe 节点。


子页面读写操作父页面:

代码示例如下:

<script>
parent.document.getElementsByTagName('h1')[0].innerHTML = 'pp';
alert(parent.document.getElementsByTagName('h1')[0].firstChild.data);
</script>

小结:

•1 测试通过 IE6, IE7, IE8, Firefox2.0, Firefox3.0, Firefox3.6, Chrome8, Opera11, Safari5。


•2 查阅资料可知 document.getElementById(‘id name').contentDocument 等同于 window.frames["iframe Name"].document。


•3 跨子域时,需在父页面和子页面的 JS 中分别设置 document.domain = 'xxx.com';


跨域操作 iframe 里内容

当两个网页所在域不同时,实现数据互相调用仅能通过 JS 修改 location 对象的 hash 属性值来进行通信。


父页面:

跨域操作 iframe 里内容

代码示例如下:

<iframe id="test-iframe" src="http://www.yyy.com/child.html" scrolling="no" frameborder="0"></iframe>
<input type="button" value="send" onclick="sendRequest()" />
<script>
function sendRequest() {
document.getElementById('test-iframe').src += '#a';
}
var interval = window.setInterval(function(){
if(location.hash) {
alert(location.hash);
window.clearInterval(interval);
  }
},1000);
</script>

子页面:

代码示例如下:

<h1>RRRRRR</h1>
<script>
var url = 'http://www.xxx.com/father.html';
oldHash = self.location.hash,
newHash,
interval = window.setInterval(function(){
newHash = self.location.hash;
if(oldHash != self.location.hash) {
document.getElementsByTagName('h1')[0].innerHTML = 'pp';
//alert(parent.location.href); //取消此注释,浏览器会提示无权限
parent.location.href = url + '#b';
window.clearInterval(interval);
        }
},500);
</script>

小结:

•1 经测试 IE6, IE7, IE8, Firefox2.0, Firefox3.0, Firefox3.6, Chrome8, Opera11, Safari5,除 IE6, IE7 外,只要改变 hash 就会记录在浏览器历史中。


•2 曾尝试在子页面使用 parent.location.replace 方法以避免父页面向服务器发送请求从而进行跳转,理论上浏览器不会记录历史,但未能成功。


•2 子页面无权读取父页面的 url,但可对父页面的 url 进行写操作,因此跨域操作时需提前获知父页面的 url


鉴于前端解决跨域问题的局限性较大,建议优先采用服务器端解决方案

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章