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 (必填) | - |