4 Ways to Communicate Across Browser Tabs in Realtime

Get to know different ways of communicating across Browser Tabs in Realtime

Dilantha Prasanjith
Photo by JOHN TOWNER on Unsplash

Over the years, Web Browser capabilities have ever increased due to the demands coming from web applications. As a result, we can find multiple ways of achieving similar functionality. One such feature we rarely look at is the ability to communicate across Browser Tabs. Let’s look at a few scenarios where you need this.

  • Changing theme (e.g., Dark or Light theme) of the application propagates across the already opened Browser Tabs.
  • Retrieve the latest token for authentication and share it across Browser Tabs.
  • Synchronize the application state across Browser Tabs.

At the moment of writing this article, there were several approaches we can consider to communicate across Browsers. However, each method has its strengths and weaknesses. Therefore, I will discuss them in detail so that you can find the best one applicable to your use case.

You might have already used LocalStorage, which is accessible across Tabs within the same application origin. But do you know that it also supports events? You can use this feature to communicate across Browser Tabs, where other Tabs will receive the event once the storage is updated.

For example, let’s say in one Tab, we execute the following JavaScript code.

window.localStorage.setItem("loggedIn", "true");

The other Tabs which listen to the event will receive it, as shown below.

window.addEventListener('storage', (event) => {
if (event.storageArea != localStorage) return;
if (event.key === 'loggedIn') {
// Do something with event.newValue
}
});

However, it comes with several limitations.

  • This event is not triggered for the Tab, which performs the storage set action.
  • For a large chunk of data, this approach has adverse effects since LocalStorage is synchronous. And hence can block the main UI thread.

You can find more information in MDN documentation for Storage Events.

The Broadcast Channel API allows communication between Tabs, Windows, Frames, Iframes, and Web Workers. One Tab can create and post to a channel as follows.

const channel = new BroadcastChannel('app-data');
channel.postMessage(data);

And other Tabs can listen to channel as follows.

const channel = new BroadcastChannel('app-data');channel.addEventListener ('message', (event) => {
console.log(event.data);
});

This way, Browser contexts (Windows, Tabs, Frames, or Iframes) can communicate. Even though this is a convenient way of communication between Browser Tabs, safari and IE does not support this. You can find more details in MDN documentation for BroadcastChannel.

Author: admin

Leave a Reply

Your email address will not be published.