页面通信本质分 3 类1. 同源页面通信 2. 跨源页面通信 3. 不同上下文Tab / iframe / Worker一、同源页面通信同协议 域名 端口1. localStorage / sessionStorage基于Web Storage APIlocalStorage.setItem(msg,hello)监听window.addEventListener(storage,(e){console.log(e.key,e.newValue)})✅ 跨 Tab 通信❌ 当前页面不会触发❌ 只能字符串2. BroadcastChannel基于BroadcastChannelconstchannelnewBroadcastChannel(test)channel.postMessage(hello)channel.onmessage(e){console.log(e.data)}API 简单支持多 Tab实时通信兼容性略差老浏览器3. window.open window.openerconstchildwindow.open(/page)child.postMessage(hello,*)父子页面通信4. SharedWorker多页面共享一个 worker多个 tab → 同一个 worker → 中转通信二、跨源页面通信不同域名比如 iframe1. postMessage基于Window.postMessage// 发送iframe.contentWindow.postMessage(hello,https://a.com)// 接收window.addEventListener(message,(e){if(e.originhttps://a.com){console.log(e.data)}})支持跨域安全可校验 origin最通用必须校验 origin否则有安全风险2. iframe URL 参数iframe srchttps://a.com?msghello通过 URL 传参不实时只能单向不安全页面通信方式可以分为同源和跨源两类。同源场景下可以使用 localStorage、BroadcastChannel 或 SharedWorker 实现多 Tab 通信跨源场景下主要使用 postMessage它通过消息机制实现不同窗口间安全通信。