摘要:窗口通信方案其实很多,但是实际要用的时候,不知道相关的知识点和各自的优势是用不好的。
准备跳转页面
const newPage = window.open('http://127.0.0.1:5173/home/contactsModule', '');
判断跳转页面是否关闭
newPage.closed === true 表示关闭
newPage.closed === false 表示未关闭
判断窗口是否被激活
if (newPage && !newPage.closed && newPage.focus) {
// 聚焦中
} else {
// 没有聚焦或被关闭或不存在
}
切换到跳转页面
newPage.focus();
切换跳转页面后关闭跳转页面
newPage.close();
切换跳转页面后调用主窗口定义方法
/* 注意xxx() 必须绑定再主窗口window上面 */
window.opener.xxx();
跳转窗口不刷新
/* 必须是同源 */
/* 1.在Home页面指定 window.name */
window.name = 'dispatchHome';
const windowFeatures = "width=910,height=699,status=no,toolbar=no,menubar=no,titlebar=no,replace=false,";
/* 2.跳转到一个新页面childPage */
const tmpWindow = window.open(url, '_blank', windowFeatures);
/* 3.在childPage中返回 */
window.open('', 'dispatchHome');
页面通信方式1-双向通信
/*缺点:broadcast channel只支持同源下的跨页面通信,*/
/*页面A*/
const noticeA = new BroadcastChannel('home-task');
// 接收消息
/*@params e: {
data: {name: 'yyh', age: 123};
...
}*/
noticeA.onmessage = e => {console.log('page1: ', e);}
// 发送消息
noticeA.postMessage({name: 'yyh', age: 123});
// 关闭
noticeA.close();
/*页面B*/
const noticeB = new BroadcastChannel('home-task');
// 接收消息
/*@params e: {
data: {name: 'yyh', age: 123};
...
}*/
noticeB.onmessage = e => {console.log('page2: ', e);}
// 发送消息
noticeB.postMessage({name: 'yyh', age: 123});
// 关闭
bc.close();
页面通信方式2单向通信
/*
缺点:
1.触发写入操作的页面下的storage监听器不会被触发;
2.重复设置相同值不会触发storage监听;
3.safari隐身模式下无法设置localStorage值;
*/
/*B页面监听*/
/*
@params e: {
key: 'Refresh';
oldValue: '1';
newValue: '2';
...
}
*/
window.addEventListener("storage", function (e) {
});
/*A页面存*/
localStorage.setItem('Refresh', Math.random()*10);
页面通信方式3单向通信
/*缺点: 必须是自己打开的窗口, 并且能获取到窗口的句柄*/
/*页面A*/
newPage.postMessage({name: 'yyh'});
/*页面B*/
/*
@params e: {
data: {name: 'yyh'};
}
*/
addEventListener('message', function (e) {
console.log('message', e);
});