iframe中怎么实现父子窗口通信

在业务开发中,经常有需要某个页面嵌入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:"字符串数据"}
    }
 }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值