Today I Learned - Rocky Kev

TIL about the Broadcast Channel API

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.