前端跨页面通信,你知道哪些方法?
参考答案
指同源下多个标签页/窗口之间通信。按推荐度排列:
1. BroadcastChannel(首选)
const bc = new BroadcastChannel('app');
bc.postMessage({ type: 'logout' });
bc.onmessage = e => console.log(e.data);
- 同源的多标签页、iframe、Worker 共享同一频道;实时、无轮询、支持结构化克隆(可传 Blob/ArrayBuffer);
- 限制:不支持 IE 与老 Safari(可用 storage 事件降级);消息不持久化,后开的页面收不到历史消息。
2. localStorage + storage 事件(兼容最好)
localStorage.setItem('msg', JSON.stringify({ id: Date.now(), data }));
window.addEventListener('storage', e => {
if (e.key === 'msg' && e.newValue) handle(JSON.parse(e.newValue));
});
- 只在其他标签页触发,本页不触发,自己发的消息要本地先处理;
- 写入相同值不触发事件;同步 API,大对象序列化有开销;可加自增 id 或时间戳去重。
3. SharedWorker
多个页面共享同一个 Worker 实例,作为消息总线(port.postMessage),适合需要中心化状态的场景;兼容性一般、调试麻烦。
4. postMessage + 窗口引用
父窗口 ↔ iframe(iframe.contentWindow.postMessage)、window.opener 打开的窗口、BroadcastChannel 不可用时的兜底;**必须校验 event.origin 与 event.source**,否则有 XSS/信息泄露风险。
5. Service Worker 中转
页面把消息发给 SW,SW 通过 clients.matchAll() + client.postMessage() 广播;适合需要离线/后台能力的场景。
6. IndexedDB / 轮询
无事件通知,需配合定时轮询或与 storage 事件组合;适合大数据量持久共享,实时性差。
7. 服务端中转
WebSocket / SSE 由服务端广播,可跨浏览器、跨设备;成本最高。
选型
同源实时轻量 → BroadcastChannel;需兼容老浏览器 → storage 事件;跨域 iframe → postMessage(校验 origin);需要跨端 → 服务端。注意所有方案都要考虑消息去重(自己发的消息别被自己再次处理)与安全(不传敏感明文)。