Giter VIP home page Giter VIP logo

broadcast-channel's Introduction

BroadcastChannel

A BroadcastChannel to send data between different browser-tabs or nodejs-processes
+ LeaderElection over the channels

follow on Twitter

demo.gif


A BroadcastChannel that allows you to send data between different browser-tabs or nodejs-processes.

  • It works completely client-side and offline.
  • Tested on old browsers, new browsers, WebWorkers, Iframes and NodeJs

This behaves similar to the BroadcastChannel-API which is currently only featured in some browsers.

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);
// > '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'
});

Clear tmp-folder:

When used in NodeJs, the BroadcastChannel will communicate with other processes over filesystem based sockets. When you create a huge amount of channels, like you would do when running unit tests, you might get problems because there are too many folders in the tmp-directory. Calling BroadcastChannel.clearNodeFolder() will clear the tmp-folder and it is recommended to run this at the beginning of your test-suite.

// jest
beforeAll(async () => {
  const hasRun = await BroadcastChannel.clearNodeFolder();
  console.log(hasRun); // > true on NodeJs, false on Browsers
})
// mocha
before(async () => {
  const hasRun = await BroadcastChannel.clearNodeFolder();
  console.log(hasRun); // > true on NodeJs, false on Browsers
})

Methods:

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

Using the LeaderElection

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.

In this example the leader is marked with the crown โ™›: leader-election.gif

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');
})

If more than one tab is becoming leader adjust LeaderElectionOptions configuration.

const LeaderElection = require('broadcast-channel/leader-election');
const elector = LeaderElection.create(channel, {
  fallbackInterval: 2000, // optional configuration for how often will renegotiation for leader occur
  responseTime: 1000, // optional configuration for how long will instances have to respond
});
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();

What this is

This module is optimised for:

  • low latency: When you postMessage on one channel, it should take as low as possible time until other channels recieve the message.
  • lossless: When you send a message, it should be impossible that the message is lost before other channels recieved it
  • low idle workload: During the time when no messages are send, there should be a low processor footprint.

What this is not

  • This is not a polyfill. Do not set this module to window.BroadcastChannel. This implementation behaves similiar to the BroadcastChannel-Standard with these limitations:
    • You can only send data that can be JSON.stringify-ed.
    • While the offical API emits onmessage-events, this module directly emitts the data which was posted
  • This is not a replacement for a message queue. If you use this in NodeJs and want send more than 50 messages per second, you should use proper IPC-Tooling

Browser Support

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

Thanks to Hemanth.HM for the module name.

broadcast-channel's People

Contributors

birne94 avatar pubkey avatar rianmcguire avatar rob-64 avatar steven87vt avatar xesenix avatar

Watchers

 avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.