概述BroadcastChannel 允许同源的多个上下文(标签页、iframe、Service Worker)在命名频道上相互通信。适用于登录态更新、主题切换、队列控制等需要跨页面同步的场景。示例const ch = new BroadcastChannel('session') ch.onmessage = e => { if (e.data.type === 'logout') { doLogout() } } // 发送消息 ch.postMessage({ type: 'logout' }) // 关闭频道 ch.close() 工程建议频道命名:按功能划分频道;避免全局滥用导致噪声与冲突。冲突与一致性:定义消息语义与优先级;对并发更新进行去重与最后写入胜出策略。安全:仅在同源上下文使用;不要传递敏感数据给不可信子文档。参考与验证MDN BroadcastChannel 文档:https://developer.mozilla.org/docs/Web/API/BroadcastChannelHTML 规范相关部分:https://html.spec.whatwg.org/

发表评论 取消回复