Security News
RubyGems.org Adds New Maintainer Role
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
broadcast-channel
Advanced tools
A BroadcastChannel implementation that works with new browsers, older browsers and Node.js
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.
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();
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.
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.
A BroadcastChannel that works in old browsers, new browsers, WebWorkers and NodeJs
+ LeaderElection over the channels
A BroadcastChannel allows simple communication between browsing contexts with the same origin or different NodeJs processes.
This implementation works with old browsers, new browsers, WebWorkers and NodeJs. You can use it to send messages between multiple browser-tabs, iframes, WebWorkers and NodeJs-processes.
This behaves similar to the BroadcastChannel-API which is currently not featured in all browsers.
This API behaves similar to the javascript-standard.
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);
// > 'I am not alone'
Add and remove multiple eventlisteners
const BroadcastChannel = require('broadcast-channel');
const channel = new BroadcastChannel('foobar');
const handler = msg => console.log(msg);
channel.addEventListener('message', handler);
// remove it
channel.removeEventListener('message', handler);
Close the channel if you do not need it anymore.
channel.close();
Set options when creating a channel (optional):
const options = {
type: 'localstorage', // (optional) enforce a type, oneOf['native', 'idb', 'localstorage', 'node']
webWorkerSupport: true; // (optional) set this to false if you know that your channel will never be used in a WebWorker (increases performance)
};
const channel = new BroadcastChannel('foobar', options);
Create a typed channel in typescript:
import BroadcastChannel from 'broadcast-channel';
declare type Message = {
foo: string;
};
const channel: BroadcastChannel<Message> = new BroadcastChannel('foobar');
channel.postMessage({
foo: 'bar'
});
Depending in which environment this is used, a proper method is automatically selected to ensure it always works.
Method | Used in | Description |
---|---|---|
Native | Modern Browsers | If the browser supports the BroadcastChannel-API, this method will be used because it is the fastest |
IndexedDB | Browsers with WebWorkers | If there is no native BroadcastChannel support, the IndexedDB method is used because it supports messaging between browser-tabs, iframes and WebWorkers |
LocalStorage | Older Browsers | In older browsers that do not support IndexedDb, a localstorage-method is used |
Sockets | NodeJs | In NodeJs the communication is handled by sockets that send each other messages |
This module also comes with a leader-election which can be used so elect a leader between different BroadcastChannels. For example if you have a stable connection from the frontend to your server, you can use the LeaderElection to save server-side performance by only connecting once, even if the user has opened your website in multiple tabs.
Create a channel and an elector.
const BroadcastChannel = require('broadcast-channel');
const LeaderElection = require('broadcast-channel/leader-election');
const channel = new BroadcastChannel('foobar');
const elector = LeaderElection.create(channel);
Wait until the elector becomes leader.
const LeaderElection = require('broadcast-channel/leader-election');
const elector = LeaderElection.create(channel);
elector.awaitLeadership().then(()=> {
console.log('this tab is now leader');
})
Let the leader die. (automatically happens if the tab is closed or the process exits).
const elector = LeaderElection.create(channel);
await elector.die();
This module is optimised for:
window.BroadcastChannel
. This implementation behaves similiar to the BroadcastChannel-Standard with these limitations:
JSON.stringify
-ed.I have tested this in all browsers that I could find. For ie8 and ie9 you must transpile the code before you can use this. If you want to know if this works with your browser, open the demo page.
Thanks to Hemanth.HM for the module name.
FAQs
A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers, NodeJs, Deno and iframes
The npm package broadcast-channel receives a total of 1,158,790 weekly downloads. As such, broadcast-channel popularity was classified as popular.
We found that broadcast-channel demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 1 open source maintainer collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
RubyGems.org has added a new "maintainer" role that allows for publishing new versions of gems. This new permission type is aimed at improving security for gem owners and the service overall.
Security News
Node.js will be enforcing stricter semver-major PR policies a month before major releases to enhance stability and ensure reliable release candidates.
Security News
Research
Socket's threat research team has detected five malicious npm packages targeting Roblox developers, deploying malware to steal credentials and personal data.