Exploring the BroadcastChannel API
An example would be a case like Facebook or Instagram where a user likes a post on a detail page and then the change is reflected when the user returns to the timeline screen.
As a result, when you clicked on a post on the main screen to open a new tab, then clicked on Like and closed the activity, the like status had to be reflected in the previous main screen as well, and in this regard, data synchronization between activities was necessary.
1. BroadcastChannel API
Web applications often require seamless communication between different components, tabs, or iframes. The BroadcastChannel API provides a powerful solution, allowing developers to establish real-time communication channels within the same origin.
It's pretty simple to use...
Creating a BroadcastChannel is very simple. It doesn’t require any libraries to be imported in your code. You just need to invoke the constructor with a String that contains the name of the channel to be created.
const bc = new BroadcastChannel('app-test-channel');
2. Send message
Now that we’ve set up a channel, we can use it to post messages. Posting a message can be done by calling the postMessage
on the BroadcastChannel
that you created earlier.
bc.postMessage("Happy New Year ✨");
Almost everything can pass as the messages:
All primitive types except symbols (Boolean, Null, Undefined, Number, BigInt, String)
Boolean and String objects
Dates
Regular Expressions
Blobs
Files, FileLists
ArrayBuffers, ArrayBufferViews
ImageBitmaps, ImageDatas
Arrays, Objects, Maps and Sets
3. Receive message
You can receive messages onmessage
by using or addEventListeneradding
.
// onmessage method
bc.onmessage = function(event) {
console.log(event);
};
// or use addEventListener method
bc.addEventListener('message', function(event) {
console.log(event);
});
Close channel
close If you close the channel by calling the method, postMessageyou will not receive messages even if you send them through .
bc.close();
4. Practical Usecase
Real-time Collaboration in Document Editing
Multi-tab Dashboard Updates: Multiple tabs displaying real-time analytics or monitoring data can update simultaneously using BroadcastChannel when new information arrives.
Live Chat/ Whiteboards Applications.
Shopping Cart Synchronization: As items are added, removed, or updated in a shopping cart, BroadcastChannel can ensure the cart's consistency across various tabs or devices.
Offline Data Syncing: In offline-first web applications, changes made in one tab while offline can be synced across other tabs once the connection is restored, ensuring consistency using BroadcastChannel.
Notifications and Alerts: Broadcast notifications or alerts across different tabs or windows of an application to inform users about important updates or events.
Multi-Step Workflows or Wizard Forms: Progress made in one step of a multi-step process can trigger updates across other tabs guiding users through the workflow.
5. Shopping Cart Example
Creating basic example which will sync cart count across (windows, tabs, iframes, etc)
Showing cart count
<div class='cart-wrapper'>
<div class="cart">
<ion-icon name="cart-outline"></ion-icon>
</div>
<div class="cart-badge"><span id="cart-count">1</span></div>
<div class="box" id="box">
<ion-icon name="cube-outline"></ion-icon>
</div>
</div>
Added to buttons to add and remove item from cart
<!-- index.html -->
<div class='button-section'>
<div id="add-btn">Add to Cart</div>
<div id="remove-btn">Remove</div>
</div>
Below script will be trigger on "Add to Cart" button click
// script.js
let cartCount = 1;
const channel = new BroadcastChannel("cart-channel");
// Event listener for "Add to Cart" button
document.getElementById("add-btn").addEventListener("click", () => {
cartCount++;
document.getElementById("cart-count").innerHTML = cartCount;
sendMessage();
});
// Function to send cart count via BroadcastChannel
const sendMessage = () => {
const message = { action: "update", count: cartCount };
channel.postMessage(message);
};
To receive change at other context using onmessage
method.
//script.js
// Event listener for receiving messages from BroadcastChannel
channel.onmessage = (event) => {
if (event.data.action === "update") {
cartCount = event.data.count;
document.getElementById("cart-count").innerHTML = cartCount;
}
};
Below script will be trigger on "Remove" button click.
//script.js
// Event listener for "Remove" button
document.getElementById("remove-btn").addEventListener("click", () => {
if (cartCount > 0) {
handleBoxAnimation("remove-box");
cartCount--;
document.getElementById("cart-count").innerHTML = cartCount;
sendMessage();
}
});
Result
6. Conclusion
In conclusion, the BroadcastChannel API in JavaScript emerges as a powerful tool for enabling seamless communication between different parts of a web application. Its ability to broadcast messages across windows, tabs, iframes, and more, within the same origin, empowers developers to handle small tasks directly in the UI without relying on server interactions.
Happy Coding 🙂
Please share your feedback...
Subscribe to my newsletter
Read articles from Priya Jain directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by