iframe父子窗口通信
在业务开发中,经常有需要某个页面嵌入iframe,同时还需要与iframe进行通信。
1. 子窗口对父窗口发出消息
window.parent.postMessage(参数1为发送的消息数据,参数2为可以接受到消息的源)
window.parent.postMessage({
'type': '自定义事件名', // 自定义事件名
'value':JSON.stringify(ObjData) // 数据,只能是字符串
}, '*');
2. 父窗口接受消息
window.addEventListener('message', 事件名, false);
mounted() {
window.addEventListener('message', this.receiveMsg, false);
},
beforeUnmount() {
window.removeEventListener('message', this.receiveMsg, false);
},
methods:{
receiveMsg(e){
// e.data = 子窗口发送消息传来的数据,上面示例这里就会接受到 {type:"事件名",value:"字符串数据"}
}
}
3. 父窗口向子窗口发送消息
Iframe.contentWindow.postMessage(消息,源)
注意:只有当iframe加载完毕,即onLoad完成后,才能接收到消息,所以当load完毕后父窗口再去发送消息,不然发了也白发。
<iframe class="map" src="xxxx" @load="iframeLoad"/>
</template>
<script>
export default {
data(){
return {
loadFinish:false
}
}, methods:{ postMessage() {
if(!this.loadFinish)return this.$el.querySelector('.map').contentWindow.postMessage('主页面消息', '*'); },
iframeLoad(){
this.loadFinish = true
}
}
} </script>
4. 子窗口接收消息
子窗口接收消息和父窗口接收消息一样的。window.addEventListener('message', 事件名, false);
window.addEventListener('message', this.receiveMsg, false);
},
beforeUnmount() {
window.removeEventListener('message', this.receiveMsg, false);
},
methods: {
receiveMsg(e) {
console.log(e)
// e.data 就是发送过来的消息 上面的示例,那 e.data = "主页面消息"
}
}

浙公网安备 33010602011771号