Vanilla JavaScript Projects

Project 26, PWA and offline

Multi-tab Sync

Open this page in two or three tabs side by side. Type in one and the others update instantly, with no server involved.

424242
Main API
BroadcastChannel
Leader
Web Locks API
Dependencies
None
Your browser
Checking

This tab

Waiting for lock

Shared note

Shared counter

0

Theme for all tabs

Open tabs

    Messages received

      How it works

      1. Join the channelEvery tab opens a BroadcastChannel with the same name and announces itself with a random id.
      2. Broadcast changesEdits are sent as small messages. Other tabs apply them and save the latest state to localStorage.
      3. Elect a leaderEach tab asks for the same Web Lock. Only one gets it. When that tab closes, the lock passes to the next tab.
      const channel = new BroadcastChannel("my-app");
      channel.postMessage({ type: "note", text: "Hello from tab A" });
      channel.onmessage = (e) => { if (e.data.type === "note") note.value = e.data.text; };
      
      // Only one tab at a time holds this lock: that tab is the leader
      navigator.locks.request("leader", () => {
        becomeLeader();
        return new Promise(() => {});   // hold the lock until the tab closes
      });