zoukankan      html  css  js  c++  java
  • 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{
         100%;
        height: 500px;
        background-color: #fff;
      }
    </style>
    
    

    测试

  • 相关阅读:
    Android——用Activity和Service实现简单的音乐播放器
    Android——indexof()
    Android——简易计算器(转)
    Android——计算器第一次完善
    Android——Service
    Android——ViewPager滑动背景渐变(自定义view,ViewPager)
    Android ——利用OnDraw实现自定义View(转)
    Android——自定义视图(一)转
    OpenERP在哪储存附件?
    销售预付款达到指定比例方可发货
  • 原文地址:https://www.cnblogs.com/yiweiblog/p/14230577.html
Copyright © 2011-2022 走看看