BroadcastChannel

Introduction
For one of my earlier engagements, we implemented a notifications component for the end users. Users, when logged in, can see the actionable notifications. When users click on the notification, the respective link opens in a new tab, allowing the user to take action.
Challenge
When the action is completed, the notification count isn’t getting updated automatically. The user needs to refresh the page to see the updated notification count.. This was not a good user experience, and we were determined to work on it.
Next Steps
We explored a few options to address the above:
setInterval(): This was the most common suggestion explored: using
setInterval()
. However, it requires making calls to backend systems at regular intervals, which increases network load. Moreover, it also caused the page to crash after a certain time.Web Socket: It needs to keep a communication open with the Backend systems. So if there are multiple tabs, we are looking at multiple Web Sockets per user.
BroadcastChannel: Then we came across “BroadcastChannel“. It doesn’t require continuous polling of the backend systems regularly or opening a communication channel.
BroadcastChannel
BroadcastChannel helps in updating the content across the windows, tabs, frames, or iframes within the same origin.
Messages are broadcasted via a
message
event fired at allBroadcastChannel
objects listening to the channel, except the object that sent the message. (Source: MDN docs)
Step 1: Create an object of BroadcastChannel and post a message with data. The constructor creates a new channel and connects with other channels with same name (Refer Step 2)
const myObserver = new BroadcastChannel('my-event');
if(myObserver){
myObserver.postMessage(JSON.parse('{"firstname":"John", "lastName":"Doe"}'));
}
Step 2: Create an object of BroadcastChannel with the same name and add an Event Listener to capture the message posted earlier.
const myObserver = new BroadcastChannel('my-event');
if(myObserver){
myObserver.addEventListener('message', (event) => {
console.log(event.data);
// Add a business logic
});
}
Step 3: Once the event is posted on the channel, the event listener will intercept it, and the logic can be written to implement business requirements, like updating the notifications in the scenario discussed above.
Hope this helps. Feel free to reach out if you have any questions or want to chat more about this!
Subscribe to my newsletter
Read articles from Nitish Jain directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Nitish Jain
Nitish Jain
Nitish Jain is a seasoned Adobe AEM/CQ developer and architect with deep expertise in crafting connected digital experiences using the AEM technology stack. He has led the implementation of numerous large-scale AEM solutions across diverse industries, adhering to best practices and delivering scalable, high-performance architectures.