← Tous les articles

JavaScript: sign users out of every open tab with BroadcastChannel

A user signs out, yet their other tabs still show their data. BroadcastChannel lets you keep the session in sync across tabs in a few lines.

JavaScript: sign users out of every open tab with BroadcastChannel

Key points

  • BroadcastChannel lets tabs from the same site message each other, no server involved.
  • Broadcast the logout so every tab leaves the signed-in area straight away.
  • Don’t destroy unsaved input, and watch out for pages restored by the Back button.

A customer of one of our SaaS products reported this: on a shared computer, someone signs out, but a second tab left open still shows her dashboard and invoices. The server will reject the next request because the session is gone, but whatever is already on screen stays readable for the next person. The fix takes a few lines and an API every current browser supports.

Broadcast the logout

BroadcastChannel opens a named channel shared by every page from the same origin in the same browser. A message posted on it reaches the other tabs but not the sender, so the event is never handled twice:

const session = new BroadcastChannel('session');

function logout() {
  fetch('/logout', { method: 'POST', credentials: 'same-origin' })
    .finally(() => {
      session.postMessage({ type: 'logout' });
      window.location.assign('/login');
    });
}

session.addEventListener('message', (event) => {
  if (event.data?.type === 'logout') {
    window.location.assign('/login');
  }
});

finally makes sure the current tab and the others leave the signed-in area even if the logout request fails on the network. This is purely a front-end courtesy: the real protection is still destroying the session server-side and checking it on every request.

Don’t throw away unsaved work

Redirecting every tab blindly has a downside: if the user was halfway through a long message in one of them, it’s gone. On our projects, pages with an edited form get special treatment:

let unsaved = false;
document.querySelector('form').addEventListener('input', () => { unsaved = true; });

session.addEventListener('message', (event) => {
  if (event.data?.type !== 'logout') return;

  if (unsaved) {
    showBanner('You were signed out in another tab. Copy your text before leaving this page.');
  } else {
    window.location.assign('/login');
  }
});

showBanner() stands for your own notification component. The form can’t be submitted any more, but the user gets a chance to rescue their text. The channel works the other way too: broadcast a login message to reload tabs still sitting on the sign-in page.

The Back button trap

Browsers can keep a whole page in memory (the back-forward cache) and show it instantly when the user hits Back, with no server request and no load scripts running. A signed-out user going back may therefore see an account page again. The pageshow event lets you catch that:

window.addEventListener('pageshow', (event) => {
  if (!event.persisted) return; // normal page load

  fetch('/api/me', { credentials: 'same-origin' }).then((response) => {
    if (response.status === 401) {
      window.location.assign('/login');
    }
  });
});

For truly sensitive pages, a Cache-Control: no-store header also keeps them out of the cache, at the cost of slightly slower navigation.

Know the limits

The channel only connects pages from the same origin: app.example.com and www.example.com can’t hear each other. If sign-in is shared across subdomains, each app has to check the session itself, for instance by calling /api/me when a tab becomes visible again.

It doesn’t connect different browsers either, or a private window with a normal one. Signing a user out of every device means revoking their sessions on the server.

FAQ

What if I can’t use BroadcastChannel?

The older trick is writing a value to localStorage and listening for the storage event, which fires in the other tabs. It still works, but BroadcastChannel reads better and leaves nothing behind in storage.

Does this work with WordPress?

Yes, for a members’ area for example. Post the message from a small script attached to the logout link, before redirecting to wp_logout_url().

Handling sensitive data and want session management you can trust? We build and audit customer portals and SaaS applications.

Partager LinkedIn Facebook X WhatsApp
</>

webtestudio

Agence web : sites WordPress sur mesure, thèmes premium et logiciels SaaS.

Parler de votre projet →