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
Post a Comment