基于H5的API中postMessage实现的多域名标签页的数据通信

前言

个人在网上找了很多的多标签页的数据通信案例
大概原理就是利用postMessage可以实现跨域问题通信
在个人本地多次测试后,目前方法可以简单时间多个标签页的数据通信
上代码:
A页面
JS部分

function receiveMessage(event) {  
    console.log(event.data);  
 if (event.origin !== "http://localhost:63343"){  
        return;  
  }  
}  
window.addEventListener("message", receiveMessage, false);  
  
function testOneWindowOpen() {  
    var popup = window.open('http://localhost:63343/javascript_top/ifreamtest/test2.html');  
    console.log('开始执行');  
    setTimeout(function () {  
        console.log('执行定时器任务开始');  
        popup.postMessage("The user is 'bob' and the password is 'secret'", "http://localhost:63343/javascript_top/ifreamtest/test2.html");  
        console.log('执行定时器任务结束');  
    },3000);  
    console.log('执行结束');  
}  
function testTwoWindowOpen() {  
    var popup = window.open('http://localhost:63343/javascript_top/ifreamtest/test3.html');
    console.log('开始执行');  
    setTimeout(function () {  
      console.log('执行定时器任务开始');  
      popup.postMessage("The user is 'bob' and the password is 'secret'", "http://localhost:63343/javascript_top/ifreamtest/test3.html");  
      console.log('执行定时器任务结束');  
    },3000);  
    console.log('执行结束');  
}

HTML部分

  

B页面和C页面



本人需求是当前主页使用window.open打开新窗口后可以新窗口发送某些数据告诉主页某些结果。
网上找了很多案例没有效果,就在于主窗口(A)window.open之后直接去发送信息,而此时子页面(B|C)还未渲染完成,子页面JS代码尚未执行,事件尚未被window对象监听,所以发送消息会一直失败,所以此处必须让发送请求延时执行,具体延时多少视项目需求确定。
同样postMessage方法可以直接确定发送的页面,这样就可以让指定页面去监听自己的message事件,返回对应信息,主页面就可以根据不同返回信息在注册事件中去分别处理。

你可能感兴趣的:(前端,html5,es6)