iframe+postMessage不同源页面通信

父页面

父页面运行在8080端口,通过iframe标签引用子页面,通过postMessage发送消息给iframe中的子页面。

<template>
  <div class="hello">
    <iframe id="iframe" src="http://10.10.30.5:8081" style="display:block;" width="50%" height="100%"></iframe>
    <button @click="action()">发消息</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'parent'
    }
  },
  methods:{
    action(){
      this.show = true
      var iframe = document.getElementById('iframe');
      var data = {
          src:"parent",
          msg:"hello",
          serNo:Math.floor(Math.random() * (1000 - 1)) + 1
      };
      iframe.contentWindow.postMessage(JSON.stringify(data), '*');
    }
  },
  mounted() {
    window.addEventListener('message', function(e) {
        console.log('parent ---> ' + e.data);
    }, false);
  },
  created() {

  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>

子页面

父页面运行在8081端口,通过监听message消息变化接收父页面中传递过来的参数,通过window.parent.postMessage发送消息给父页面。

<template>
  <div class="hello">
     <button @click="sendMessageToParent()">发送消息给父组件</button>
  </div>
</template>

<script>
export default {
  name: 'HelloWorld',
  data () {
    return {
      msg: 'sunyiwei'
    }
  },
  methods:{
    sendMessageToParent(){
      let data = {
        src:"child",
        msg:"hello",
        serNo:Math.floor(Math.random() * (1000 - 1)) + 1
      }

      window.parent.postMessage(JSON.stringify(data),'*');
    }
  },
  created() {
  },
  mounted() {
            window.addEventListener('message', function(e) {
              if(e.data == undefined){
                return
              }
              if (e.data) {
                console.log('child ---> ' + e.data)
              }
              var data = JSON.parse(e.data);

            }, false);
  }
}
</script>


<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .hello{
    width: 100%;
    height: 500px;
    background-color: #fff;
  }
</style>

测试

posted @ 2021-01-04 16:27  奕为  阅读(726)  评论(0编辑  收藏  举报