@nsev/broadcast-channel

@nsev/broadcast-channel

documentation npm github
mit license mom made pizza mom made spaghetti

About

A Wrapper around BroadcastChannel that uses @3xpo/events for node-style events in the browser.

Installation

pnpm i @nsev/broadcast-channel

Usage

Basics

Tab 1
import { BroadcastChannel } from '@nsev/broadcast-channel';
const channel = new BroadcastChannel('foobar');
channel.send('I am not alone');
Tab 2
import { BroadcastChannel } from '@nsev/broadcast-channel';
const channel = new BroadcastChannel('foobar');
channel.on('message', (message) => {
console.log(message); // I am not alone
});

Typesafety

Just like in the original, just pass the type as a generic.

import { BroadcastChannel } from '@nsev/broadcast-channel';
type Message = {
foo: 'bar';
bar: 'hi';
} | {
foo: 'baz';
baz: string;
};
const channel = new BroadcastChannel<Message>('foobar');

channel.on('message',e=>{
// e is of type Message
})

// ok
channel.send({
foo: 'bar',
bar: 'hi',
});

// ok
channel.send({
foo: 'baz',
baz: 'hi',
});

// ok
channel.send({
foo: 'baz',
baz: 'hello there',
});

// not ok
channel.send({
foo: 'bar',
baz: 'hi',
});

// not ok
channel.send({
foo: 'baz',
bar: 'hi',
});

// not ok
channel.send({
foo: 'bar',
bar: 'hi',
baz: 'hello there',
});

Generated using TypeDoc