@loghole/consensus

1.0.2 • Public • Published

Consensus

npm version

Allows to select the primary tab among the open. Can use this together with server-sent events.

Installation

Using npm:

npm i @loghole/consensus

Using yarn:

yarn add @loghole/consensus

Example

Base:

import Consensus from "@loghole/consensus";

const consensus = new Consensus("example")

consensus.init(
    () => { // notification about this tab is primary.
      console.log("is primary")
    },
    () => { // notification about this tab is replica.
      console.log("is replica")
    },
)

window.addEventListener('unload', () => {
  consensus.destroy()
})

Simple example with server-sent events:

import Consensus from "@loghole/consensus";

const consensus = new Consensus("sse-example", { debug: true });
const broadcast = new BroadcastChannel("broadcast-bus");

let source = undefined;

broadcast.addEventListener("message", ({ data }) => {
  console.log(`received sse event from broadcast: ${data}`);
});

function initSSE() {
  source = new EventSource(`/sse`, {
    withCredentials: true,
  });

  source.addEventListener("example", ({ data }) => {
    console.log(`received sse event: ${data}`);

    broadcast.postMessage({ data: data });
  });
}

function closeSSE() {
  if (source) {
    source.close();
    source = undefined;
  }
}

consensus.init(
  () => { initSSE(); },
  () => { closeSSE(); }
);

window.addEventListener("unload", () => {
  consensus.destroy();
});

Browser Support

Readme

Keywords

Package Sidebar

Install

npm i @loghole/consensus

Weekly Downloads

2

Version

1.0.2

License

MIT

Unpacked Size

8.93 kB

Total Files

6

Last publish

Collaborators

  • lissteron
  • gadavy