在业务中碰到这么一个问题,用户需要保持双屏浏览信息,并实现通信,当其中一个屏幕重新登录/用户设置/管理设置/其他等改变时,其他页面需要相应适配。
最初使用的是socket来进行相互通信,通过传递token也能达到目的,但是当token失效重新登录时,socket连接失败,即使用户多个页签一一重新登录,其产生的token也会不一致,导致通信失败,进而需要维护token一致而使用localstorage来同步,带来更多不必要的麻烦...
众所周知,不同页签间通信的方式有多种:
- localStorage
- Broadcast Channel API
- WebSocket
- SharedWorker
- IndexedDB
- postMessage API
这里我们采用BroadcastChannel允许同源的不同浏览器窗口、标签页、frame 或者 iframe 下的不同文档之间相互通信。消息通过 message 事件进行广播,该事件在侦听该频道的所有 BroadcastChannel
对象上触发,发送消息的对象除外。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div>
<button onclick="openNewWindow()">打开新窗口</button>
<button onclick="postMessage(true)">主屏发送消息</button>
<button onclick="postMessage()">次屏发送消息</button>
</div>
</body>
<script>
const channel = new BroadcastChannel("my-channel");
channel.onmessage = e => {
console.log(e, "接收消息");
};
const openNewWindow = () => {
window.open("./BroadcastChannel.html");
};
const postMessage = (isMain = false) => {
if (isMain) {
channel.postMessage("主屏发送消息");
} else {
channel.postMessage("次屏发送消息");
}
};
</script>
</html>