Skip to content

BroadcastChannel to send data between different browser-tabs

Notifications You must be signed in to change notification settings

LNSD/broadcast-channel

Repository files navigation

BroadcastChannel

A BroadcastChannel that works in old browsers, new browsers and web workers

demo.gif


Getting started

npm install --save @lnsd/broadcast-channel
# or
yarn add @lnsd/broadcast-channel
# or
pnpm add @lnsd/broadcast-channel

Usage

Create a channel instance:

import BroadcastChannel from '@lnsd/broadcast-channel';

type Message = { foo: string };

const channel = new BroadcastChannel<Message>('example');

Post a message to the channel:

channel.postMessage({ foo: 'Hello world!' });

Listen to channel messages:

channel.onmessage = function(message: MessageEvent<Message>) {
  console.log(message.data.foo);
};
// Hello world!

Close a channel if it is no longer needed:

channel.close();