broadcastchannel
Same-origin messaging between tabs, windows, and workers via the BroadcastChannel API.
Import: @rtorcato/browser-common/broadcastchannel
๐ MDN: Broadcast Channel API ยท ๐ caniuse: broadcastchannel
createBroadcastChannel returns a live channel object, so it throws a
requires a browser environment error where BroadcastChannel is unsupported โ
guard with isBroadcastChannelAvailable() first.
Exampleโ
import {
isBroadcastChannelAvailable,
createBroadcastChannel,
} from '@rtorcato/browser-common/broadcastchannel'
if (isBroadcastChannelAvailable()) {
const channel = createBroadcastChannel<{ type: string }>('sync')
const off = channel.onMessage((data) => {
if (data.type === 'updated') refresh()
})
channel.send({ type: 'updated' })
// later:
off()
channel.close()
}
Exportsโ
isBroadcastChannelAvailable()โ feature checkcreateBroadcastChannel(name)โ returns{ onMessage, send, close, channel }
See the API reference for full signatures.