在业务开发中,经常有需要某个页面嵌入iframe,同时还需要与iframe进行通信。
一、父向子通信
父窗口向子窗口发送消息
iframe.contentWindow.postMessage(参数1为发送的消息数据,参数2为可以接受到消息的源)
<template>
<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>
子窗口接收消息
window.addEventListener(‘message’, 事件名, false)
mounted() {
window.addEventListener('message', this.receiveMsg, false);
},
beforeUnmount() {
window.removeEventListener('message', this.receiveMsg, false);
},
methods: {
receiveMsg(e) {
console.log(e)
// e.data 就是发送过来的消息
}
}
二、子向父通信
子窗口向父窗口发送信息
window.parent.postMessage(参数1为发送的消息数据,参数2为可以接受到消息的源)
window.parent.postMessage({
'type': '自定义事件名', // 自定义事件名
'value':JSON.stringify(ObjData) // 数据,只能是字符串
}, '*');
父窗口接收信息
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:"字符串数据"}
}
}