useBroadcastChannel
useBroadcastChannel 是一个允许你在组件中使用 BroadcastChannel API 的 hook。
useBroadcastChannel 封装了 BroadcastChannel API,用于在同源的浏览上下文(标签页、窗口、iframe)之间进行简单的消息通信。它返回一个包含当前 data、用于发送消息的 post 函数、连接状态、错误状态和 close 函数的对象。该 hook 自动管理频道的生命周期,并在组件卸载时进行清理。
使用场景
- 在同一应用的多个打开标签页之间同步状态(例如主题切换、注销事件)
- 无需服务器即可向应用的所有打开实例广播实时更新
- 在同源的 iframe 或弹出窗口之间协调操作
注意事项
- SSR 安全:在服务端渲染期间返回
isSupported: false和空操作函数。服务端不会调用BroadcastChannel构造函数。 - 浏览器支持:所有现代浏览器均支持。在依赖频道功能前请先检查
isSupported。 - 仅限同源:BroadcastChannel API 仅在同源的浏览上下文之间有效。
Usage
Live Editor
function Demo() { const { isSupported, data, post, error,timeStamp } = useBroadcastChannel({ name: "reactuse-demo-channel", }); const [message, setMessage] = useState(""); useEffect(() => { if (isSupported) { alert(data); } }, [data]); return ( <div> <p>支持状态: {JSON.stringify(isSupported)}</p> <p>请在至少两个标签页中打开此页面</p> <p> <b>频道:</b> reactuse-demo-channel </p> <p> <b>消息:</b> {data}<br/> <b>时间戳:</b> {timeStamp} </p> <input value={message} onChange={(event) => { setMessage(event.currentTarget.value); }} /> <button onClick={() => post(message)} style={{ cursor: isSupported ? "pointer" : "not-allowed", }} > 发送 </button> {error && <p>错误: {error.message}</p>} </div> ); }
Result
API
UseBroadcastChannelOptions
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| name | 频道名称 | string (必填) | - |
UseBroadcastChannel
Returns
UseBroadcastChannelReturn<D, P>
Arguments
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| options | 选项 | UseBroadcastChannelOptions (必填) | - |
UseBroadcastChannelReturn
| 参数名 | 描述 | 类型 | 默认值 |
|---|---|---|---|
| isSupported | 是否支持 | boolean (必填) | - |
| channel | 频道 | BroadcastChannel | undefined (必填) | - |
| data | 数据 | D | undefined (必填) | - |
| post | 发送数据 | (data: P) => void (必填) | - |
| close | 关闭 | () => void (必填) | - |
| error | 错误 | Event | null (必填) | - |
| isClosed | 是否关闭 | boolean (必填) | - |
| timeStamp | 时间戳 | number (必填) | - |