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:
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:
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.
Not the Post Office
How do we get data to the broadcast channel? Easy. Let’s look at another snippet of code:
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.
You can view the video we made on this subject here.
Check us out everywhere on the web!
Check out everything at: https://www.thevirtuoid.com
Web Tinkerer. No, not like Tinkerbell.
Leave a Reply