Skip to main content

4 Ways to Communicate Across Browser Tabs in Realtime

1. Local Storage Events

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
}
});

2. Broadcast Channel API

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);
});



3. Service Worker Post Message

You might wonder, how Service Workers comes in to the picture. Basically, Service Workers also supports sending messages, which we can use to communicate across Browser Tabs.

Using Service Workers, you can send a message like shown below.

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

And in the receiving Worker in the other Browser Tab can listen to the event.

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

This method gives more control and is a reliable way of passing messages. But implementing Service Workers requires some extra knowledge on Service Worker API and a little bit more work. So, in that case, if the other methods are not working, it would be better to look into this one. You can find more information in MDN documentation for Service Worker API and a complete example referring to this link.


4. Window Post Message

One of the traditional ways of communicating across Browser Tabs, Popups, and Iframes is Window.postMessage() method. You can send the message as follows.

targetWindow.postMessage(message, targetOrigin)

And the target window can listen to the events, as shown below.

window.addEventListener("message", (event) => {
if (event.origin !== "http://localhost:8080")
return;
// Do something
}, false);

One advantage of this method over the others is the support for cross-origin communication is possible. But one of the limitations is that you need to have a reference to the other Browser Tab. So this approach only for Browser Tabs opened via window.open() or document.open(). You can find more information in MDN documentation.















 

Comments

Popular posts from this blog

How to use Ngx-Charts in Angular ?

Charts helps us to visualize large amount of data in an easy to understand and interactive way. This helps businesses to grow more by taking important decisions from the data. For example, e-commerce can have charts or reports for product sales, with various categories like product type, year, etc. In angular, we have various charting libraries to create charts.  Ngx-charts  is one of them. Check out the list of  best angular chart libraries .  In this article, we will see data visualization with ngx-charts and how to use ngx-charts in angular application ? We will see, How to install ngx-charts in angular ? Create a vertical bar chart Create a pie chart, advanced pie chart and pie chart grid Introduction ngx-charts  is an open-source and declarative charting framework for angular2+. It is maintained by  Swimlane . It is using Angular to render and animate the SVG elements with all of its binding and speed goodness and uses d3 for the excellent math functions, scales, axis and shape ge

JavaScript new features in ES2019(ES10)

The 2019 edition of the ECMAScript specification has many new features. Among them, I will summarize the ones that seem most useful to me. First, you can run these examples in  node.js ≥12 . To Install Node.js 12 on Ubuntu-Debian-Mint you can do the following: $sudo apt update $sudo apt -y upgrade $sudo apt update $sudo apt -y install curl dirmngr apt-transport-https lsb-release ca-certificates $curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - $sudo apt -y install nodejs Or, in  Chrome Version ≥72,  you can try those features in the developer console(Alt +j). Array.prototype.flat && Array.prototype. flatMap The  flat()  method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth. let array1 = ['a','b', [1, 2, 3]]; let array2 = array1.flat(); //['a', 'b', 1, 2, 3] We should also note that the method excludes gaps or empty elements in the array: let array1

Understand Angular’s forRoot and forChild

  forRoot   /   forChild   is a pattern for singleton services that most of us know from routing. Routing is actually the main use case for it and as it is not commonly used outside of it, I wouldn’t be surprised if most Angular developers haven’t given it a second thought. However, as the official Angular documentation puts it: “Understanding how  forRoot()  works to make sure a service is a singleton will inform your development at a deeper level.” So let’s go. Providers & Injectors Angular comes with a dependency injection (DI) mechanism. When a component depends on a service, you don’t manually create an instance of the service. You  inject  the service and the dependency injection system takes care of providing an instance. import { Component, OnInit } from '@angular/core'; import { TestService } from 'src/app/services/test.service'; @Component({ selector: 'app-test', templateUrl: './test.component.html', styleUrls: ['./test.component