vue iframe父子页面通信postmessage
时间: 2025-05-09 14:52:49 浏览: 25
### 使用 PostMessage 实现在 Vue 中的 Iframe 父子页面通信
#### 父页面设置与配置
为了使父页面可以向嵌入的子页面发送消息,在父页面中需要先获取到 iframe 的 DOM 对象,并调用其 `contentWindow.postMessage` 方法来传递数据给子页面。
```html
<!-- Parent.vue -->
<template>
<div id="app">
<iframe ref="myFrame" src="http://localhost:8081/" width="600" height="400"></iframe>
<button @click="sendDataToChild">Send Data to Child</button>
</div>
</template>
<script>
export default {
name: "App",
mounted() {
this.$refs.myFrame.onload = () => console.log("iFrame loaded");
},
methods: {
sendDataToChild() {
const data = { message: "Hello from parent!" };
let frameElement = this.$refs.myFrame;
frameElement.contentWindow.postMessage(data, "*"); // '*' 表示不限制目标源域名,实际使用时应指定具体地址[^3]
}
}
};
</script>
```
当点击按钮时会触发 `sendDataToChild()` 函数执行,该函数负责构建要传输的数据对象并通过 postMessage 发送给子页面。注意这里使用了通配符 "*" 来表示接收方不受限于特定来源;但在生产环境中建议明确指出预期的目标 URL 以提高安全性。
#### 子页面监听来自父级的消息
在子页面里可以通过添加 event listener 监听由父页面发出的信息:
```javascript
// 子页面 JavaScript 文件
window.addEventListener('message', function(event) {
// 安全验证:确保信息确实来自于信任的父窗口
if (event.origin !== 'http://expected-parent-domain.com') return;
alert(`Received ${JSON.stringify(event.data)} from parent`);
}, false);
```
这段脚本会在接收到新消息时弹出提示框显示所收到来自父页面的内容。同样重要的是要注意安全性的考量——即只处理那些已知可信源头发来的请求。
#### 反向操作:子页面向父页面发送通知
如果希望从子页面主动发起交流,则可以在子页面内部定义相应的方法用于构造并发射消息回传至父页面。
```html
<!-- Child.vue 或者其他 HTML 文档内含有的 script 标签 -->
<button onclick="notifyParent()">Notify Parent Page</button>
<script type="text/javascript">
function notifyParent(){
window.parent.postMessage({
action:"childNotification",
content:"This is a notification from the child"
},'*');
}
</script>
```
而在对应的父页面上则需注册相应的处理器等待这些反馈的到来:
```javascript
// 在 Parent.vue 组件内的 created 生命周期钩子里加入下面这行代码
created(){
window.addEventListener('message',(e)=>{
console.log(e.data); // 处理来自子页面的通知
});
}
```
以上就是完整的双向交互流程说明以及具体的实现方式[^4]。
阅读全文
相关推荐


















