loading...

How to communicate between different tabs?

akashvarma9 profile image Akash Varma ・2 min read

Hello Everyone, I hope you're doing great.

In this article, I'm going to discuss how to communicate between different tabs using Broadcast Channel API.

Broadcast Channel API allows basic communication between browsing contexts(i.e windows, tabs, frames, or iframes) and workers on same origin.

Websites not come under the same origin

Wesbites come under same origin are:

Let's get our hands dirty🚀.

We will try to update heading in all the tabs when user updates heading in one tab.

Create 2 HTML pages and 2 javascript files. Lets say tab1.html, tab2.html, tab1.js, tab2.js. Import tab1.js in tab1.html and same order for tab2. Create a broadcast channel in both js files and should have the same channel names.

const bc = new BroadcastChannel('update-heading');
bc.onmessage = (eventMessage) => {

}

In both HTML pages add a title and in tab1.html add input element so that we can listen to this event and update the value in localstorage.

HTML in tab1 should be

<h1 id="title"> Hello </h1>
<input type="text" id="input" />
const bc= new BroadcastChannel('update-heading');
const title = document.getElementById('title');
const input = document.getElementById('input');
input.onkeyup = (e) => {
    const val = e.target.value;
    title.textContent = 'Hello ' + val;
    localStorage.setItem('title', val);
    bc.postMessage('update-title');
}

On every keypress, we will call a method 'postMessage' in broadcastChannel.
When broadcast posts something, we will listen onmessage method from broadcast. And also updating the title in localStorage. So that in tab2.js, when broadcast onmessage is triggered, we can fetch value from localStorage and update DOM.

In tab2.js

const bc = new BroadcastChannel('update-heading');
const title = document.getElementById('title');
bc.onmessage = (eventMessage) => {
 const val = localStorage.getItem('title');
 title.textContent = 'Hello ' + val;
}

For code, Please visit here .

Broadcast Channel is used for communication between same origin.

If you want to do cross origin communication, you can use window.postMessage() method, where window is the reference object of other domain's window.

Thank you for your time. Have a great day🙂.

Posted on May 8 by:

Discussion

markdown guide