How to communicate between tabs or windows with JavaScript?

Spread the love

Sometimes, we want to communicate between tabs or windows with JavaScript.

In this article, we’ll look at how to communicate between tabs or windows with JavaScript.

How to communicate between tabs or windows with JavaScript?

To communicate between tabs or windows with JavaScript, we use the Broadcast Channel API.

For instance, we write

const bc = new BroadcastChannel("test_channel");

bc.postMessage("This is a test message.");

bc.onmessage = (ev) => {
  console.log(ev);
};

to create a BroadcastChannel object with the channel name.

Then we call postMessage to send a message.

And we received messages with onmessage.

ev has the received message data.

Conclusion

To communicate between tabs or windows with JavaScript, we use the Broadcast Channel API.

Leave a Reply

Your email address will not be published. Required fields are marked *