Oliver Jumpertz

Syncing Multiple Browser Tabs Locally

Category: JavaScript

Share this snippet to:

// sender
const bc = new BroadcastChannel("topic");
bc.postMessage({
type: "msg",
message: "Hello from the BroadcastChannel!",
});
// receiver
const bc = new BroadcastChannel("topic");
bc.onmessage = (event) => {
const { data } = event;
handleData(data);
};

Usage

You can use a BroadcastChannel if you want to keep browser tabs in sync. If you, for example, change some state in one tab, you might want to sync it with other tabs a user potentially has open.

You can now either fetch the current data from your backend if you reactivate a tab, or you keep it updated directly by using a BroadcastChannel, even saving your users some network bandwidth.

Let’s say you have a table with data and add a new entry. You want all browser tabs with the same page open to always stay in sync. In this case, your code could look similar to this:

const bc = new BroadcastChannel("userTableUpdate");
// onmessage is only triggered in different tabs.
// You'll never receive the message you sent in the same tab,
// at least not as long as you use the same BroadcastChannel object
// to send AND receive messages.
bc.onmessage = (event) => {
const { data } = event;
if (data.type === "userTableUpdate") {
updateTable(data.entry);
}
};
const tBody = document.getElementById("userDataBody");
function updateTable(entry) {
const newRow = tBody.insertRow();
const newCell = newRow.insertCell();
const text = document.createTextNode(entry.userName);
newCell.appendChild(text);
}
function updateTableAndSend(entry) {
updateTable(entry);
bc.postMessage({
type: "userTableUpdate",
entry,
});
}

Share this snippet to: