iframe传参父页面给子页面传参:iframe父子页面传参,跨域通信的完整指南
父子页面通信的基本原理
iframe中的子页面与父页面属于两个独立的文档上下文,通过同源策略限制了直接访问对方的DOM或数据,但HTML5引入了window.postMessage和window.name等机制,允许跨域通信。
同域情况下的传参方法
父页面向子页面传参
父页面可通过修改子页面的src参数传递数据,
// 父页面
window.open('child.html?param=value', '_blank');
子页面通过window.location.search解析URL参数:
// 子页面
const urlParams = new URLSearchParams(window.location.search);
const param = urlParams.get('param');
子页面向父页面传参
子页面可通过window.parent.location.search修改父页面的URL:
// 子页面 window.parent.location.search = '?result=data';
跨域情况下的传参方法
使用window.name属性
父页面设置window.name:
// 父页面 window.name = 'parentData';
子页面通过window.name获取数据:

// 子页面 console.log(window.name); // 输出 'parentData'
注意:window.name的值会一直保留,且大小写敏感,适用于多次通信。
使用window.postMessage
父页面向子页面发送消息:
// 父页面
const iframe = document.getElementById('childFrame');
iframe.contentWindow.postMessage('parentData', 'https://child-domain.com');
子页面监听消息:
// 子页面
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-domain.com') return;
console.log(event.data); // 输出 'parentData'
});
子页面向父页面发送消息:

// 子页面
window.parent.postMessage('childData', 'https://parent-domain.com');
父页面监听消息:
// 父页面
window.addEventListener('message', (event) => {
if (event.origin !== 'https://child-domain.com') return;
console.log(event.data); // 输出 'childData'
});
关键点:postMessage需指定目标源(event.origin),避免安全风险。
注意事项
- 跨域限制:不同源的iframe无法直接访问对方的DOM或属性。
- 安全性:使用
postMessage时,务必验证event.origin,防止恶意页面窃取数据。 - 兼容性:
window.name适用于旧版浏览器,但postMessage是现代标准。 - 数据格式:建议通过JSON.stringify序列化复杂数据。
iframe父子页面传参的核心在于利用window.name或postMessage机制突破同源限制,同域场景可通过URL参数直接传递,而跨域通信需严格遵循安全规范,开发者应根据实际需求选择合适的方法,并注意兼容性和安全性。
参考代码:
<!-- 父页面 -->
<iframe id="childFrame" src="https://child-domain.com/child.html"></iframe>
<script>
const iframe = document.getElementById('childFrame');
iframe.onload = () => {
iframe.contentWindow.postMessage('Hello from parent!', 'https://child-domain.com');
};
</script>
<!-- 子页面 -->
<script>
window.addEventListener('message', (event) => {
if (event.origin !== 'https://parent-domain.com') return;
console.log('Received:', event.data);
});
</script>
通过本文的方法,您可以轻松实现iframe父子页面的参数传递,提升Web应用的交互能力。
文章已关闭评论!