Tab presence detection
The problem
Section titled “The problem”You want to know how many tabs of your app the user currently has open — for example, to show a “your session is also open in another tab” notice, or to avoid duplicating tasks across tabs.
The solution
Section titled “The solution”The internal tab:join and tab:leave events notify you when a tab connects to or disconnects from the channel. That’s enough to keep a registry of active tabs.
import { Tabus } from "tabus-js";
const bus = new Tabus("presence");
// Starts at 1: this tab itself already counts.const activeTabs = new Set<string>([bus.tabId]);
bus.on("tab:join", ({ tabId }) => { activeTabs.add(tabId); renderCount();});
bus.on("tab:leave", ({ tabId }) => { activeTabs.delete(tabId); renderCount();});
function renderCount() { console.log(`Active tabs: ${activeTabs.size}`);}
window.addEventListener("beforeunload", () => bus.destroy());Why it works
Section titled “Why it works”- Every
Tabusinstance emitstab:joinshortly after being created, notifying existing peers that a new tab joined — see Lifecycle events. - When
destroy()is called (for example, onbeforeunload), that instance emitstab:leave, and the other tabs remove itstabIdfrom the registry. - Since its own
tabIdis manually added to the set on startup, every tab always counts itself without depending on receiving its owntab:join.
Next step
Section titled “Next step”Combine this with Synchronized logout to, for example, only force a global logout when the last tab closes.
