js在两个html窗口间通信 怎样利用js在两个html窗口间通信

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

js在两个html窗口间通信 怎样利用js在两个html窗口间通信

浅笑·   2021-04-27 我要评论
想了解怎样利用js在两个html窗口间通信的相关内容吗,浅笑·在本文为您仔细讲解js在两个html窗口间通信的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:js,html窗口,js,窗口,通信,下面大家一起来学习吧。

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

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们