Broadcast Channel API 是浏览器提供的一个用于同源上下文之间通信的接口,它允许同一源下的多个标签页、iframe 或 worker 之间通过命名频道互相收发消息,非常适合实现跨标签页的数据同步与状态共享。

什么是 Broadcast Channel API
Broadcast Channel API 通过 BroadcastChannel 构造函数创建一个通信频道对象。所有使用相同频道名称并处于同一源下的上下文,都可以成为该频道的订阅者,彼此之间能够广播消息。
基本使用步骤
1. 创建频道
在需要通信的每一个标签页中,使用相同的频道名创建 BroadcastChannel 实例:
// 创建名为 'app_channel' 的广播频道
const channel = new BroadcastChannel('app_channel');
2. 发送消息
调用 postMessage 方法即可向频道中所有其他订阅者发送数据:
// 发送一条普通对象消息
channel.postMessage({
type: 'login',
user: 'xiaoming'
});
3. 接收消息
通过监听 message 事件来接收来自其他标签页的消息:
channel.onmessage = function(event) {
// event.data 为接收到的消息内容
console.log('收到消息:', event.data);
if (event.data.type === 'login') {
// 更新当前标签页的登录状态
updateLoginState(event.data.user);
}
};
4. 关闭频道
当页面不需要再通信时,应调用 close 方法释放资源:
// 关闭频道,停止接收消息 channel.close();
完整示例
下面给出一个简单的跨标签页聊天示例,在任意标签页输入内容,其他标签页都会收到:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>跨标签页通信示例</title>
</head>
<body>
<input id="msgInput" type="text" placeholder="输入消息">
<button id="sendBtn">发送</button>
<ul id="msgList"></ul>
<script>
const channel = new BroadcastChannel('chat_room');
const input = document.getElementById('msgInput');
const btn = document.getElementById('sendBtn');
const list = document.getElementById('msgList');
btn.onclick = function() {
const text = input.value;
if (text) {
channel.postMessage(text);
input.value = '';
}
};
channel.onmessage = function(e) {
const li = document.createElement('li');
li.textContent = e.data;
list.appendChild(li);
};
</script>
</body>
</html>
注意事项
- Broadcast Channel 仅支持同源通信,不同域名或协议下的页面无法互通。
- 发送的消息会被结构化克隆,函数、DOM 节点等无法被传递。
- 在 Safari 等浏览器中需注意版本兼容性,必要时可使用 localStorage 事件作为降级方案。
总结
使用 Broadcast Channel API 实现跨标签页通信非常直接,只需创建同名频道、发送与监听消息即可,避免了手动管理 storage 事件或 postMessage 目标源的麻烦。对于大多数现代浏览器项目,它是轻量级跨标签页同步的首选方案。
Broadcast_Channel_API跨标签页通信前端通信修改时间:2026-07-27 07:27:22