两个html窗口间利用JavaScript通信

场景:当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();

豌豆资源搜索网站https://55wd.com 广州vi设计公司http://www.maiqicn.com

如果是需要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);
posted @ 2020-09-18 14:32  浅笑·  阅读(444)  评论(0编辑  收藏  举报