两个html窗口间利用JavaScript通信

a 夏天 提交于 2020-08-10 18:53:22

场景:当A页面打开B页面,在B页面操作后,A页面需要同步变更数据时

A 页面 ,http://127.0.0.1:10001/A.html

var domain = 'http://127.0.0.1:10001';

window.open('http://127.0.0.1:10001/B.html');
window.addEventListener('message', function (event) {
    if (event.origin !== domain) return;
    console.log('message received:  ' + event.data, event);
}, false);

 B 页面 ,http://127.0.0.1:10001/B.html,opener是当前窗口的打开者引用

var domain = 'http://127.0.0.1:10001';
window.opener.postMessage("success", domain);
window.close();

如果是需要A打开B的同时向B中发送数据时

// 发送数据方
var domain = 'http://127.0.0.1:10001';
var myPopup = window.open('http://127.0.0.1:10001/B.html');
myPopup.postMessage('数据', domain);

// 接收数据方
window.addEventListener('message', function(event) {
    if(event.origin !== 'http://127.0.0.1:10001') return;
    console.log('message received:  ' + event.data,event);
},false);

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!