zoukankan      html  css  js  c++  java
  • window.open()不同源页面通信

    父页面

    运行端口:8080

    <template>
      <div>
        <el-button @click="open()">发送消息给子页面</el-button>
      </div>
    </template>
    
    <script>
      export default{
    	name:'Opener',
        data(){
          return{
    
          }
        },
        methods:{
          open(){
            let param = {
              data:"父页面:给我选择一个元素"
            }
            let child = window.open('http://localhost:8081/#/opener','child')
            setTimeout(function(){
              child.postMessage(param, '*');
            },100)
    
          }
    
        },mounted() {
          window.addEventListener('message', function(event) {
            if(event.data.data){
              console.log('子页面发送来的消息:',event.data);
            }
          });
        }
      }
    </script>
    
    <style scoped lang="scss">
      div el-button{
        margin-left: 500px;
      }
    </style>
    
    

    子页面

    运行端口:8081

    <template>
      <div>
        <el-button @click="sendMsg()">发送消息给父页面</el-button>
      </div>
    </template>
    
    <script>
      export default{
        name:'Opener',
        data(){
          return{
    
          }
        },
        methods:{
          sendMsg(){
            if(window.opener){
                let param = {
                  data:"子页面:我选择了一个元素"
                }
                window.opener.postMessage(param,'*');
                window.close();
            }else{
              console.log("父页面已经关了")
            }
          }
        },mounted() {
            window.addEventListener('message', function(event) {
              if(event.data.data){
                console.log('子页面接收了父页面发送来的消息',event.data);
              }
          });
        }
      }
    </script>
    
    <style scoped lang="scss">
      div el-button{
        margin-left: 500px;
      }
    </style>
    
    

    测试

    父页面给子页面发送消息

    子页面给父页面发送消息


  • 相关阅读:
    HDOJ:1051
    新sort的用法
    python课堂整理14---函数式编程
    python课堂整理13---函数的作用域及匿名函数
    python课堂整理12---递归
    python课堂整理11---函数即变量
    python课堂整理10---局部变量与全局变量
    python课堂整理9---函数1
    python课堂整理8---字符串格式化
    python课堂整理7---集合
  • 原文地址:https://www.cnblogs.com/yiweiblog/p/14233811.html
Copyright © 2011-2022 走看看