• 4 Ways to Communicate Across Browser Tabs in Realtime
  • Dilantha Prasanjith
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: zenblo
  • Proofread by: HurryOwen, TiaossuP

Four ways to communicate in real time across browser tabs

Over the years, as the need for Web applications has increased, so have the capabilities of Web browsers. As a result, you can find multiple ways to implement similar functionality. This article introduces a little-noticed feature: communicating between browser tabs. Here are a few examples:

  • Theme changes to the application (for example, dark or light themes) are applied to all open browser tabs.
  • Request the latest token for authentication and share it between browser tabs.
  • Synchronize application state across browser tabs.

This article focuses on several ways to communicate across browsers. However, each approach has its advantages and disadvantages. Therefore, this article will discuss them in detail so that you can find the best approach for practical development.

1. Use the LocalStorage event LocalStorage

By using LocalStorage, you can enable communication between tabs within the same application source. LocalStorage also supports events, which can be used to communicate across browser tabs, and other tabs will receive events after updates are stored.

For example, execute the following JavaScript code in a TAB.

window.localStorage.setItem("loggedIn"."true");
Copy the code

Other tabs that listen for the event will receive it, as shown below:

window.addEventListener('storage'.(event) = > {
 if(event.storageArea ! =localStorage) return;
 if (event.key === 'loggedIn') {
   // Test using event.newValue}});Copy the code

However, it has several limitations:

  • Tabs that perform storage set operations do not trigger this event.
  • For large data blocks, since LocalStorage is synchronous, this approach can have the perverse effect of blocking the main UI thread.

You can find more information in MDN’s stored event documentation.

2. Use the BroadcastChannel API

The BroadcastChannel API allows communication between tabs, Windows, Frames, Iframes, and Web Workers. A TAB can create a Channel and send messages in it, as follows:

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

Other tabs can listen for channels, as shown below:

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

channel.addEventListener ('message'.(event) = > {
 console.log(event.data);
});
Copy the code

This allows communication between browser contexts (Windows, Tabs, Frames, or Iframes). While this is a convenient way to communicate between browser tabs, safari and IE don’t support it. You can see the details in the MDN’s BroadcastChannel documentation.

3. Use the Service Worker to send messages

You might wonder how the Service Worker gets into this scenario. But fundamentally, Service workers support sending messages that can be used to communicate between browser tabs.

Using the Service Worker, you can send messages like the following:

navigator.serviceWorker.controller.postMessage({
 broadcast: data
});
Copy the code

At the same time, events can be monitored in other browser tabs that receive workers.

addEventListener('message'.async (event) => {
 if ('boadcast' in event.data ) {
  const allClients = await clients.matchAll();
  for (const client ofallClients) { client.postMessage(event.broadcast); }}});Copy the code

This method provides more control assurance and is a reliable way to deliver messages. However, implementing the Service Worker requires some additional knowledge and work on the Service Worker API. So, in this case, if nothing else works, it’s best to try this one. You can find more information in MDN’s Service Worker API documentation, as well as a complete example.

Use the window.postmessage () method

The window.postMessage () method is one of the traditional ways to communicate across browser tabs, pop-ups, and Iframes. Messages can be sent as follows:

targetWindow.postMessage(message, targetOrigin)
Copy the code

The target window can listen for events, as follows:

window.addEventListener("message".(event) = > {
  if(event.origin ! = ="http://localhost:8080")
    return;
  // You can do tests
}, false);
Copy the code

This approach has one advantage over other approaches: it supports cross-source communication. But there is one limitation: you need to reference another browser TAB. So this method only works with the window.open() or document.open() methods. You can find more information in the MDN documentation.

conclusion

Hopefully, this article will be interesting enough to provide some useful technical knowledge for Web application development. Each approach is unique and has its own usage scenario.

In addition to the methods discussed, we can also use Websockets and server-sent events to communicate in real time across browser tabs and even across devices. However, that would require a Web server to use these. The server listed in this article does not rely on a Web server, so it will be able to quickly handle traffic within the browser.

Thanks for reading! Welcome to exchange and study, help each other and make progress together!

Happy programming! ❤ ️

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.