Other tabs

Exchange messages with the other tabs of the same browser over a BroadcastChannel. What arrives is always checked before you use it.

On this page

Sending and receiving

deck-sync.tsx
type Sync = { type: 'sync'; index: number };

const post = useBroadcastChannel(`deck:${slug}`, {
  parse: parseSync,
  onMessage: ({ index }) => {
    goTo(index);
  },
});

post({ type: 'sync', index: next });
Sent from an event handler

useBroadcastChannel(name, { parse, onMessage }) joins the BroadcastChannel called name while the component is mounted.

It returns post, which sends a message to the other tabs on that channel. A tab never receives its own messages.

onMessage is the latest render’s when it runs, so even when goTo above is a prop, the current one is called.

parse

deck-sync.tsx
const parseSync = (data: unknown): Sync | undefined =>
  typeof data === 'object' &&
  data !== null &&
  'type' in data &&
  data.type === 'sync' &&
  'index' in data &&
  Number.isInteger(data.index)
    ? { type: 'sync', index: data.index as number }
    : undefined;

parse is required. What another tab sends is outside this code’s control: an older deployment still open in another tab, or a page that picked the same name.

onMessage only sees what parse accepts. Return undefined to drop a message.

A sender that receives nothing still passes parse: the type of what post takes is the type parse returns.

Joining nothing

session-sync.tsx
const channel = sessionId === null ? null : `session:${sessionId}`;
const post = useBroadcastChannel(channel, { parse: parseSync });

null as the name joins nothing, for a session that has not started yet.

Posting then sends nothing, and neither does posting before the component has mounted.

k8ordo

React libraries that use Baseline features without holding back.