子窗口对父窗口发出消息
window.parent.postMessage({
'type': '自定义事件名', // 自定义事件名
'value':JSON.stringify(ObjData) // 数据,只能是字符串
}, '*');
父窗口接受消息
window.addEventListener('message', this.receiveMsg, false);
父窗口向子窗口发送消息
<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>
//子窗口接收消息
mounted() {
window.addEventListener('message', this.receiveMsg, false);
},
beforeUnmount() {
window.removeEventListener('message', this.receiveMsg, false);
},
methods: {
receiveMsg(e) {
console.log(e)
// e.data 就是发送过来的消息 上面的示例,那 e.data = "主页面消息"
}
}
封装好的代码
//子向父发数据
export const sonSendFather = (type, data) => {
window.parent.postMessage({
'type': type, // 自定义事件名
'value': data // 数据,只能是字符串
}, '*');
}
//父向子发数据
export const fatherSendSon = (data, id = 'posterIframe') => {
let dom = document.querySelector('#' + class);
dom.contentWindow.postMessage(data, '*');
}
//接收数据
export const receive = () => {
window.addEventListener('message', receiveMsg, false);
}
//接收处理
const receiveMsg = (e) => {
console.log('接收到的数据', e)
}