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