TIL about the Broadcast Channel API
POSTED ON:
TAGS: javascript browser
The Broadcast Channel API allows communication between browsing contexts (windows, tabs, iframes) and workers on the same origin.
Think of a use-case like, once you logout from an app running in a browser tab, you want to broadcast it to the app instances opened in other tabs of the same browser.
Creating the Broadcast #
First step is to create a broadcast channel by giving it a unique name. Also define the content(message) you want to broadcast.
const CHANNEL_NAME = "greenroots_channel";
const bc = new BroadcastChannel(CHANNEL_NAME);
const message = 'I am wonderful!';
Broadcasting #
To broadcast a message, call the method postMessage() on the channel by passing the message.
const sendMessage = () => {
bc.postMessage(message);
}
Listening for the Broadcast #
At the receiving end, whoever is listening to the broadcast will be notified with the message sent.
const CHANNEL_NAME = "greenroots_channel";
const bc = new BroadcastChannel(CHANNEL_NAME);
bc.addEventListener('message', function(event) {
console.log(`Received message, "${event.data}", on the channel, "${CHANNEL_NAME}"`);
const output = document.getElementById('msg');
output.innerText = event.data;
});
Direct link to the demo: https://demo.greenroots.info/web-apis/web-apis-broadcast/
via Tapas Adhikary's 10 lesser-known Web APIs you may want to use
Related TILs
Tagged: javascript