What is broadcast-channel?
The broadcast-channel npm package allows different browser tabs, iframes, web workers, and node.js processes to communicate with each other. It uses various methods like IndexedDB, local storage, or native events to create a channel that can be used to broadcast messages across different contexts running on the same machine.
What are broadcast-channel's main functionalities?
Creating a Broadcast Channel
This code sample demonstrates how to import the BroadcastChannel class from the package and create a new channel named 'my-channel'.
const { BroadcastChannel } = require('broadcast-channel');
const channel = new BroadcastChannel('my-channel');
Sending a Message
This code sample shows how to send a message ('Hello World') through the channel to other listening contexts.
channel.postMessage('Hello World');
Receiving Messages
This code sample sets up an event listener to receive messages sent to the channel and logs them to the console.
channel.onmessage = (message) => console.log('Received:', message);
Closing a Channel
This code sample demonstrates how to close the channel when it is no longer needed to free up resources.
channel.close();
Other packages similar to broadcast-channel
pubsub-js
PubSubJS is a topic-based publish/subscribe library that's similar to broadcast-channel but does not support communication between different browser tabs or node processes.
localforage
While primarily a local storage library, localForage can be used to store and retrieve messages across sessions, which can be a form of communication similar to broadcast-channel, but it's not designed specifically for message broadcasting.
BroadcastChannel
A BroadcastChannel that works in old browsers, new browsers, WebWorkers and NodeJs
+ LeaderElection over the channels
A BroadcastChannel that allows you to send data between different browser-tabs or nodejs-processes.
Using the BroadcastChannel
npm install --save broadcast-channel
Create a channel in one tab/process and send a message.
const BroadcastChannel = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');
channel.postMessage('I am not alone');
Create a channel with the same name in another tab/process and recieve messages.
const BroadcastChannel = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');
channel.onmessage = msg => console.dir(msg);