Log out in one tab and the other five tabs of the same site keep acting as if you’re still logged in. That’s a small thing that bugs me on a lot of web apps, and the fix is built into the browser: BroadcastChannel.
Every tab, window, iframe or worker of the same origin that creates a channel with the same name can send messages to all the others. You don’t need a reference to the other tabs, only the name:
const channel = new BroadcastChannel("auth");
// in the tab where the user clicks "log out"
channel.postMessage({ type: "logout" });
// in every tab of the site
channel.addEventListener("message", (event) => {
if (event.data.type === "logout") {
location.href = "/login";
}
});
The tab that sends the message doesn’t receive it itself, so it does its own logout as usual and the rest follow. The same idea works for a changed theme, a cart that got a new item, or a settings page that should refresh in the other tabs.
Messages are copied with the structured clone algorithm, so plain objects, arrays, dates and even Blobs go through without JSON.stringify(). Functions don’t. When a page or component no longer needs the channel, call channel.close() so it can be cleaned up.
The caveat is the reach. It’s same-origin, and MDN is precise about it: the tabs need to share a storage partition. An iframe from b.com inside a page on a.com can’t talk to a normal b.com tab, even though they look like the same origin. It also has no protocol at all, so you decide what a message looks like and every tab has to check it. And it only reaches tabs that are open right now: a tab opened later doesn’t see old messages, so I’d still store the real state in a cookie or localStorage.
Support is old news by now: Chrome 54, Firefox 38 and Safari 15.4, Baseline widely available since September 2024.
Further reading: MDN: Broadcast Channel API, MDN: BroadcastChannel