Skip to content

Search v2 documentation only

BroadcastActions

useBroadcastChannel returns this object; useBroadcastProvider reads the same shape from context.

Member Type Description
channelName string Resolved channel name, including the namespace.
messages BroadcastMessage[] Received messages (the log). Empty in a late-joining tab until something arrives.
sentMessages BroadcastMessage[] Local send attempts, including queued/failed sends. Not delivery acknowledgements.
isPingInProgress boolean true while a ping() is collecting answers.
error string | null Set when the browser lacks BroadcastChannel or the channel fails.
postMessage (type: string, content: any, options?: SendMessageOptions) => void Send to every other tab on the channel (fire-and-forget).
sendMessage (type: string, content: any, options?: SendMessageOptions) => Promise<BroadcastMessage> Promise-returning send; resolves when the message was handed to the channel, not when other tabs receive it.
ping (timeoutMs?: number) => Promise<string[]> Discover other tabs on the channel; resolves to their source names (yours excluded).
getLatestMessage (options?: { type?: string; source?: string }) => BroadcastMessage | null Most recent received message, optionally filtered. null when nothing matches.
clearReceivedMessages (options?: ClearReceivedMessagesOptions) => void Clear the received log, optionally by types, sources, or ids.
clearSentMessages (options?: ClearSentMessagesOptions) => void Clear the sent log. sync: true also clears the other tabs’ received copies.
closeChannel () => void Close the channel and remove listeners. Idempotent; automatic on unmount.
reconnect () => boolean Recreate the channel after a creation failure or closeChannel(). No-op (false) while a connection object is held.
requestMessagesHistory (options?: RequestMessagesHistoryOptions) => void Ask open tabs for their recent messages and merge the union into this tab’s log. 2.3.0+

sendMessage is the awaitable form of postMessage, for flows that need “send, then do X, or show an error if the send failed”:

const { sendMessage } = useBroadcastChannel('cart');
try {
const sent = await sendMessage('cart-updated', { count: 2 });
// `sent` is the BroadcastMessage (id, timestamp, source) handed to the channel
} catch (e) {
// The send provably failed: unclonable payload (DataCloneError), a closed
// channel with recovery unavailable or exhausted, or a failed flush on close/unmount
}

The promise resolves once the message was handed to the channel — after batching and, on a provable channel close, one automatic recovery retry. BroadcastChannel has no delivery acknowledgement, so resolution never means another tab received the message; it has the same meaning as a sentMessages entry. A pending batched send is flushed on closeChannel()/unmount and settles with that flush. Attach a catch even for fire-and-forget calls, or a failed send surfaces as an unhandled rejection in addition to the error state. Batching, excludedBatchMessageTypes, and the expiration options behave exactly as with postMessage.

const latest = getLatestMessage();
const latestAlert = getLatestMessage({ type: 'alert' });
const latestFromTab2 = getLatestMessage({ type: 'info', source: 'tab-2' });

Returns the most recently received matching message, or null. Note that in a late-joining tab the log starts empty, so this is null until something arrives.

Use for manual cleanup only: after it, the channel sends and receives nothing. Safe to call repeatedly. You do not need it for normal unmounting.

Explicitly recreates the channel after a creation failure or a deliberate closeChannel():

const { error, reconnect } = useBroadcastChannel('my-channel');
// when error says the channel could not be created, e.g. from a retry button:
const reopened = reconnect(); // true when a new connection was created

Returns false and does nothing while a connection object is held. Reconnecting keeps this tab’s source identity and message logs; it does not resend or replay missed messages — use requestMessagesHistory or useSyncedState to resynchronize data. A messageerror (an incoming payload that failed to deserialize) is reported through error as a read failure and is not treated as a disconnection.

By default (recovery: 'auto', 2.4.0+) the hook also recovers on its own when a channel provably dies outside its control — a send threw InvalidStateError, which per the HTML standard means the held channel object was closed and the message never left this tab, so retrying that send once cannot duplicate delivery. Recovery never triggers on a deliberate closeChannel() or unmount, on payload errors, or on silence (a channel that silently stops receiving is undetectable). It is bounded by maxRecoveryAttempts consecutive failed attempts, after which only an explicit reconnect() revives the channel; onChannelRecovered is the resync point since missed messages are never replayed. Pass recovery: 'manual' to make every recovery an explicit application decision — reconnect() then stays the only way back.

Available in 2.3.0 and later. Asks every other open tab on the channel to send its newest messages and merges the union into this tab’s received log, ordered oldest to newest:

requestMessagesHistory({ types: ['chat'], limit: 50 });

Each open tab answers with its own newest messages, up to limit (default 50, max 500). The requester unions all answers and deduplicates by message ID; when answers together exceed the limit, a later answer carrying newer messages replaces older retained entries, so the request always keeps its newest limit unique messages and no tab gets priority for answering first. Pass types to limit the request to specific message types.

Replayed entries carry isHistory: true, never trigger onMessage, and are not rebroadcast, so they are for display and catch-up, not side effects. Replay needs live peers: only tabs open when the request is made can answer, and once every tab on the channel has closed, those messages are gone.