How to communicate between browser tabs using javascript

There are certain instances when you need to pass data between your website that is opened in multiple tabs. In this scenario, we have an API available known as Broadcast Channel API.

Broadcast Channer API is used to open communication channel between browser tabs.

Let's look at how can we implement this.

Firstly, we will create a channel object using the BroadcastChannel constructor.

 const channel = new BroadcastChannel('my-channel');

This will connect you to the channel named 'my-channel'.

Now, to send some data via this channel, use the following code -

channel.postMessage('Hi');

And, to receive the data, we will be listening to message events.

channel.onmessage = (event) => {
    console.log(event);
}

This would be all to start communication between tabs.

To close the connection, use the close() method.

channel.close();

This is all you need to do, to transfer data between tabs.

Hope you learned something new.

Thanks for reading.

My Twitter