BroadcastChannel API: Sending Messages Between Tabs

ยท

4 min read

BroadcastChannel API: Sending Messages Between Tabs
Play this article

Why Tab Communication in Web Browser Matters

Communicating between different tabs or windows in a web browser is super important for many reasons. Imagine you have several open tabs while shopping online. You put an item in your cart in one tab, and you want all the other tabs to know about it instantly. That's one of the reasons we need this kind of communication. Also, think about logging into a website like your bank account. If we log out in one tab, we'd want to be logged out in all the other tabs, too to keep everything safe. It's like making sure you lock all the doors when leaving your house. So, it's not just convenient; it also makes the web safer and more efficient for us.

What is the Broadcast Channel API?

The Broadcast Channel API is like a special communication tool for web browsers. It allows different tabs or windows in our browser to talk to each other. It's a way for them to share information instantly. Think of it as a secret chat system just for our browser. It helps web apps work together and stay in sync, making our online experience smoother.

How Broadcast Channel API works

Here's how it works in simple terms:

  1. Create a Channel: We create a channel with a specific name, like cart_channel

  2. Send Messages: In one tab, we can send a message (like "I added a new item to the cart!") to the cart_channel

  3. Other Tabs Listen: All the other open tabs also tuned into the cart_channel can hear this message.

  4. Instant Updates: So, when we add something to our cart in one tab, all the other tabs can instantly update to show the same thing. It's like magic!

Step-by-Step Guide: Using Broadcast Channel API

Now that we know how this API works, In this section we'll walk through the process of using the Broadcast Channel API step by step. In this article, we will use the Cart Example.

Step 1: Create a Broadcast Channel

To get started, create a javascript file broadcast.js and create a new instance of Broadcast Channel API. This channel serves as the communication medium. We can give it a specific name, like 'chat_channel'.

const cartChannel = new BroadcastChannel('cart_channel');

Here we created a new Broadcast Channel named cart_channel using new BroadcastChannel('cart_channel'). This sets up the communication channel.

Step 2: Send Cart Updates to Tabs

We can send cart updates through the Broadcast Channel, ensuring that all tabs or windows are synchronized. For instance, when a user adds an item to their cart, we can broadcast the update.

function addToCart(itemName) {
    // do actions when adding items to cart
    const updateMessage = `Added "${itemName}" to the cart.`;
    updateCartUI(updateMessage);
    cartChannel.postMessage(updateMessage);
}

In this step:

  • We define a function addToCart takes the itemName as a parameter.

  • Inside the function, we update our active tab UI by calling updateCartUI(updateMessage) and send a message to other tabs connected to the cart_channel using cartChannel.postMessage(updateMessage) and tell them to update themselves with a new cart item.

Step 3: Receive Cart Updates

To receive cart updates in other tabs or windows, set up an event listener for the Broadcast Channel. When a cart update is broadcasted, this listener will capture it.

cartChannel.addEventListener('message', (event) => {
    const receivedUpdate = event.data;
    updateCartUI(receivedUpdate);
});

In this step:

  • We added an event listener to the cart_channel using cartChannel.addEventListener('message', (event) => { ... }).

  • When a cart update is received, the event handler function is called with the received data event.data, which contains the update message.

  • We can then call a function like updateCartUI to update the cart UI with the received update.

Now our broadcast.js file should look like this

// Step 1: Create a Broadcast Channel
const cartChannel = new BroadcastChannel("cart_channel");

// Step 2: Send Cart Updates
function addToCart(itemName) {
  const updateMessage = `Added "${itemName}" to the cart.`;
  updateCartUI(updateMessage);
  cartChannel.postMessage(updateMessage);
}

// Step 3: Receive Cart Updates
cartChannel.addEventListener("message", (event) => {
  const receivedUpdate = event.data;
  updateCartUI(receivedUpdate);
});

// Function to update the cart UI
function updateCartUI(updateMessage) {
  const cartElement = document.getElementById("cart");
  const newItemElement = document.createElement("p");
  newItemElement.textContent = updateMessage;
  cartElement.appendChild(newItemElement);
}

Live Example and Testing

To test this real-time cart updating application follow these steps:

  1. Open this URL in two or three tabs on your browser.

  2. Click on any button (for example Add Product A to Cart) to add an item to the cart

  3. Go to another tab, you should see the cart is added on UI here as well in real-time. You can check this on another browser window as well.

Example

Live URL ๐Ÿ‘‰ https://real-time-cart-update.naimur.repl.co/

Full code on Github ๐Ÿ‘‰ https://github.com/nsourov/broadcast-api

BroadcastChannel API MDN documentation ๐Ÿ‘‰ https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API

ย