tab窗口通讯
简介
BroadcastChannel是一个Web API,用于在浏览器的不同窗口、标签页或者甚至不同的浏览器实例之间建立通信。它允许在同一个origin(来源)下的不同上下文之间发送数据,例如在同一个域名下的不同页面之间进行通信。
一、基本使用
- 创建频道
const channel = new BroadcastChannel('id_a');
- 发送信息
channel.postMessage('发送消息xxxxxx');
- 接收消息
channel.onmessage = function(event) {
console.log('接收信息 ', event.data);
};
- 关闭频道
channel.close();
二、使用示例
- 发送界面
<div>
<input type="text" placeholder="请输入内容">
<button onclick="handleSend()">发送消息</button>
</div>
<script>
const channel = new BroadcastChannel('id_a');
function handleSend() {
let input = document.querySelector('input');
if (input.value) channel.postMessage(input.value);
}
</script>
- 接收界面
<script>
const channel = new BroadcastChannel('id_a');
channel.onmessage = function (event) {
let body = document.querySelector('body');
body.textContent = event.data;
};
</script>