如何利用js在两个html窗口间通信

网络编程 2021-07-04 14:07www.168986.cn编程入门
这篇文章主要介绍了如何利用js在两个html窗口间通信,如果读者们有类似的需求,可以参考下

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

以上就是如何利用js在两个html窗口间通信的详细内容,更多关于js在两个html窗口间通信的资料请关注狼蚁SEO其它相关文章!

Copyright © 2016-2025 www.168986.cn 狼蚁网络 版权所有 Power by