Hi everyone, and welcome to another exciting edition of Boring JavaScript! Today, we’re going to tackle the Broadcast Channel API. It make communicating between your application’s windows, tabs, and iFrames easy, easy, easy.
Don’t like to read? Then watch the video.
Broadcasting on a Frequency of …
If you’ve ever written a browser-based application, you know that you can launch it inside of a browser window, a browser tab, or even inside of an HTML iFrame. And while this isn’t much of a problem, if your application works with things like session/local storage, cookies, and what not, you might run into problems in keeping all instances of your application in sync with each other.
Why? Think of logging into a browser-based gaming application that will log you out after 30 minutes of inactivity. You launch the application in one tab, launch it again in another tab, and start playing. You are about to win the game for the first time in forever when suddenly your application logs out. After throwing your computer out the window, you realize that you forgot the application was running in the first tab, it timed out and logged out, so the server running your game told the other tabs that you had logged out, and so they logged you out. Bummer.
Using BroadcastChannel() fixes that, as it’s an interface that is common to all instances of a browser (window, tab, iFrame). This can facilitate communications between them all.
Let’s take a look:
const processMessage = (event) => {
currentAnimal.textContent = event.data;
}
const broadcastNewAnimal = (event) => {
const newAnimal = newAnimalInput.value;
if (newAnimal) {
broadcastChannel.postMessage(newAnimal);
}
currentAnimal.textContent = newAnimal;
}
const submitButton = document.getElementById('change-animal');
const newAnimalInput = document.getElementById('new-animal');
const currentAnimal = document.getElementById('current-animal');
const channelName = "BoringJavaScript";
const broadcastChannel = new BroadcastChannel(channelName);
broadcastChannel.addEventListener('message', processMessage);
submitButton.addEventListener('click', broadcastNewAnimal);
Line 18 creates the new broadcast channel. The only parameter we use is a string, which represents the name of the channel (meaning, we can have multiple channels!).
There are two operations we need to cover:
“Watson! Come here! I want to see you!”
Line 19 adds an event listener to the broadcast channel. This is used by the broadcast channel to handle any messages posted upon the broadcast channel. Let’s look at the important lines:
const processMessage = (event) => {
currentAnimal.textContent = event.data;
}
// blah, blah, blah code
const channelName = "BoringJavaScript";
const broadcastChannel = new BroadcastChannel(channelName);
broadcastChannel.addEventListener('message', processMessage);
Line 9 above is where we use addEventListener to process any message coming into the broadcast channel. The function (processMessage in our example, Line 1) takes the normal event argument. Within that event argument is the data we’ve passed to the broadcast channel, surprisingly stored in the ‘data’ property of the event (imagine that!). From there, we do anything we wish with the data.
What kind of data can be passed? Anything JavaScript supports! Well, almost anything – as long as it can be serialized. A good rule of thumb here is that if JSON.stringify can be successfully called on the object, then you can use it as data.
Not the Post Office
How do we get data to the broadcast channel? Easy. Let’s look at another snippet of code:
const broadcastNewAnimal = (event) => {
const newAnimal = newAnimalInput.value;
if (newAnimal) {
broadcastChannel.postMessage(newAnimal);
}
currentAnimal.textContent = newAnimal;
}
// blah blah blah code
const channelName = "BoringJavaScript";
const broadcastChannel = new BroadcastChannel(channelName);
submitButton.addEventListener('click', broadcastNewAnimal);
We have an event listener for a click event on a DOM element somewhere on our browser page (Line 14). When it is clicked, it runs a routine to get the value of an input element (Line 2). It then takes that value and uses the ‘postMessage()’ method on our broadcast channel to send that object along for any listeners that may be listening (see previous section).
And that’s it! It’s that simple. After the postMessage(), the broadcast channel will then inform any listeners that new data is available, and they can then do whatever they want with the data.
The Video
You can view the video we made on this subject here.
Shameless Plug
Check us out everywhere on the web!
Check out all our videos at: https://www.boringjavascript.com
Check out everything at: https://www.thevirtuoid.com
Facebook: https://www.facebook.com/TheVirtuoid
Twitter: https://twitter.com/TheVirtuoid
YouTube: https://www.youtube.com/channel/UCKZ7CV6fI7xlh7zIE9TWqgw
Categories: Boring JavaScript Javascript
thevirtuoid
Web Tinkerer. No, not like Tinkerbell.
Creator of the game Virtuoid. Boring JavaScript. Visit us at thevirtuoid.com
Leave a Reply