Skip to main content

@rtorcato/browser-common / broadcastchannel

broadcastchannel

Type Aliases

BroadcastChannelWrapper

BroadcastChannelWrapper<T> = object

Defined in: broadcastchannel/index.ts:17

A thin wrapper around a BroadcastChannel for same-origin cross-tab messaging.

Type Parameters

T

T = unknown

Properties

onMessage

onMessage: (handler) => () => void

Defined in: broadcastchannel/index.ts:19

Registers a listener for messages; returns an unsubscribe function.

Parameters
handler

(data) => void

Returns

() => void

send

send: (data) => void

Defined in: broadcastchannel/index.ts:21

Posts a message to all other same-origin contexts on this channel.

Parameters
data

T

Returns

void

close

close: () => void

Defined in: broadcastchannel/index.ts:23

Closes the underlying channel.

Returns

void

channel

channel: BroadcastChannel

Defined in: broadcastchannel/index.ts:25

The underlying native BroadcastChannel.

Functions

isBroadcastChannelAvailable()

isBroadcastChannelAvailable(): boolean

Defined in: broadcastchannel/index.ts:10

Checks if the BroadcastChannel API is available in the current environment.

Example

import { isBroadcastChannelAvailable } from '@rtorcato/browser-common/broadcastchannel'
if (isBroadcastChannelAvailable()) startSync()

Returns

boolean

True if available, false otherwise.


createBroadcastChannel()

createBroadcastChannel<T>(name): BroadcastChannelWrapper<T>

Defined in: broadcastchannel/index.ts:42

Creates a BroadcastChannel wrapper for same-origin cross-tab messaging.

Example

import { createBroadcastChannel } from '@rtorcato/browser-common/broadcastchannel'
const channel = createBroadcastChannel<{ type: string }>('sync')
const off = channel.onMessage((data) => console.log(data))
channel.send({ type: 'updated' })
channel.close()

Type Parameters

T

T = unknown

Parameters

name

string

The channel name shared across tabs.

Returns

BroadcastChannelWrapper<T>

A wrapper with onMessage/send/close helpers.

Throws

If called in a non-browser environment or where BroadcastChannel is unsupported.