前端实现多标签页通讯
需求分析
现代浏览器,比如谷歌,微软edge等都可以实现同时打开多个标签页。在实际工作当中,笔者发现,有些用户确实喜欢用多个标签页来操作。比如在A页面浏览,在B页面提交。那么,在某些场景下,需要保持多个标签页之间的数据、状态是一致的。因此,我们需要解决多标签页通讯问题。
现有解决方案
1、BroadcastChannel
BroadcastChannel 接口表示给定源的任何浏览上下文都可以订阅的命名频道。它允许同源 的不同浏览器窗口 、标签页 、frame 或者 iframe 下的不同文档之间相互通信。消息通过 message 事件进行广播,该事件在侦听该频道的所有 BroadcastChannel 对象上触发,发送消息的对象除外。
A页面
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A</title>
</head>
<body>
<script>
const bc = new BroadcastChannel('room');
bc.postMessage({type: 'init', content: 'hi,b'})
</script>
</body>
</html>
B页面
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>B</title>
</head>
<body>
<script>
const bc = new BroadcastChannel('room');
bc.onmessage = function (event) {
console.log(event.data)
}
</script>
</body>
</html>
2、localStorage或sessionStorage的storage事件
localStorage 和 sessionStorage 都是 HTML5 新增的 API,用于存储数据。它们都提供了 setItem()、getItem()、removeItem() 等方法,用于设置、获取和删除数据。
当存储区域(localStorage 或 sessionStorage)被修改时,将触发 storage 事件。
我们可以通过监听特定key的改变来变相实现标签页的通讯。
A页面
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>A</title>
</head>
<body>
<script>
// room 这个key 充当通讯渠道标识
window.localStorage.setItem('room','hi,b');
</script>
</body>
</html>
B页面
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>B</title>
</head>
<body>
<script>
/**
* 监听storage事件
* @description 监听storage事件,可以通过如下信息来定义通讯逻辑
* @param e
* @param e.key 被修改的key
* @param e.oldValue 修改前的值
* @param e.newValue 修改后的值
* @param e.url 触发storage事件的页面的URL
* @param e.storageArea 触发storage事件的存储区域
*/
window.addEventListener('storage',(e)=>{
console.log(e);
if(e.key === 'room'){
// 处理逻辑
}
})
</script>
</body>
</html>