Skip to main content

Command Palette

Search for a command to run...

Exploring the Broadcast Channel API for Real-Time Browser Tab Communication

Updated
•3 min read
W

Hey there! đź‘‹ I'm Wilson, a Senior Software Engineer with a passion for building accessible, secure, and efficient web applications. With years of experience across various industries including fintech, healthtech, e-commerce, proptech, and more, I've learned a thing or two about creating software that not only works but delights users.

A couple of years ago, in 2022, I think, my product manager requested an enhancement to ensure that when users log out of the application in one browser tab, they are automatically logged out of all other open tabs (the same application). Initially, I thought of opening all new tabs and saving the instances of the opened windows in a global state that persisted in local or session storage. This seemed complicated, so I did some more research and found out I could achieve this with the Broadcast Channel API.

What is Broadcast Channel API?

According to MDN docs, the Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin.

The "same origin" aspect means all participating contexts must share the same protocol, host, and port. For example, if you have multiple tabs open, they can communicate with each other using the Broadcast Channel API. However, a tab open to http://example.com (note the different protocol) or https://another-example.com (note the different host) would not be able to join the same communication channel. This restriction ensures that only scripts from the same site can interact, enhancing security by preventing unauthorized cross-origin data sharing.

Below are some examples to illustrate where the Broadcast Channel API will and will not work:

URL 1URL 2Will Work?
https://example.comhttps://example.com/page1Yes
https://example.comhttps://example.com/page2Yes
https://example.comhttps://example.com/subdirectory/pageYes
https://example.com:8080https://example.com:8080/pageYes
https://sub.example.comhttps://sub.example.com/page1Yes
https://example.comhttp://example.comNo
https://example.comhttps://another-example.comNo

Now, let's write some code

import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';

const LogoutComponent = () => {
  const navigate = useNavigate();

  useEffect(() => {
    // Create a new BroadcastChannel
      const channel = new BroadcastChannel('logout-channel');

    // Function to handle incoming messages
    channel.onmessage = function(event) {
      if (event.data === 'logout') {
        // Perform logout action here
        console.log('Received logout message, logging out...');
        // Example: redirect to login page
        navigate('/');
      }
    };

    return () => {
      // Clean up the BroadcastChannel on component unmount
      channel.close();
    };
  }, [navigate]);

  // Function to send a logout message to other tabs
  const sendLogoutMessage = () => {
    const channel = new BroadcastChannel('logout-channel');
    channel.postMessage('logout');
    channel.close();
  };

  // Example usage: Call sendLogoutMessage() when user logs out
  const handleLogout = () => {
    sendLogoutMessage();
    // Also redirect to login page in current tab
    navigate('/');
  };

  return (
    <button onClick={handleLogout}>
      Log Out
    </button>
  );
};

export default LogoutComponent;

If I have three tabs open—one showing notifications, one for my profile, and another for my dashboard—and I log out from the profile page, the other two tabs will automatically reflect the logout status when I switch to them without having to refresh.

Browser Support

The Broadcast Channel API is widely supported across modern web and mobile browsers, enabling effective cross-tab communication. Below is a summary of its compatibility with various browsers:

BrowserSupported Version
Google Chrome54+
Mozilla Firefox38+
Microsoft Edge79+
Opera41+
Internet ExplorerNot Supported
Mobile BrowserSupported Version
Chrome Android54+
Firefox for Android38+
Opera Android41+
Safari on IOS41+

Further Reading

For further reading, you can check out MDN docs. You can also check out a small chat application i built using.

You can also explore a demo chat application I built to demonstrate the use of Broadcast Channel API on GitHub or try it out live