Marco Pracucci

Chrome 54 introduces BroadcastChannel API and Spreaker is already using it

by Marco Pracucci Comments

Chrome 54 is rolling out today. Among the other features, it introduces the BroadcastChannel API - an easier way to send messages between open windows, tabs or iframes on the same origin.

BroadcastChannel API isn’t actually new, since it was already supported on Firefox 38+, but it definitely amplifies the number of people accessing it, thanks to the wide adoption of Chrome.

How it works

A BroadcastChannel is, well, a channel where you can broadcast and listen to messages, sent and received on same origin contexts. A channel is identified by a unique name and you can instance it with:

var channel = new BroadcastChannel("bus");

Once created, you can send messages via postMessage() or listen to the message events on the channel itself. Messages sent from a context are not dispatched to the context itself, so you will not receive your own messages, but you will receive messages other contexts send on the same channel (identified by the unique name - bus in the example).

// Send a message
channel.postMessage("Hello world");

// Listen for messages
channel.onmessage = function(e) {
    console.log("Received message: %o", e.data);
};

To leave a channel, you can close() it. This will disconnect the link and release the resources allocated by the BroadcastChannel.

channel.close();

BroadcastChannel and the Spreaker Embedded Player

We currently use the BroadcastChannel API in the Spreaker Embedded Player, to ensure that there aren’t two players playing audio at the same time (either they’re in the same page or different pages).

The following example shows how it works (requires Chrome 54+, Firefox 38+ or Opera 41+). Try to click play on the first player, and then play on the second one: once you play the second one, the first one will pause, giving you a much better experience than getting two audios playing at the same time.

Listen to “Jamie Lee's Best of the Worst” on Spreaker.

Listen to “Episode 39: CEREMONIES” on Spreaker.

Feature detection

Checking the BroadcastChannel existence is not enough to ensure the feature is available. When your app runs in a sandboxed iframe, new BroadcastChannel() will throw an exception whenever you try to instance it.

function isBroadcastChannelSupported() {
    if (!("BroadcastChannel" in self)) {
        return false;
    }

    // When running in a sandboxed iframe, the BroadcastChannel API
    // is not actually available and throws an exception
    try {
        const channel = new BroadcastChannel("feature_test");
        channel.close();
        return true;
    } catch(err) {
        return false;
    }
}

Related articles

RSS Feed

To get a notification each time a new article gets published, type the following command on your Slack: /feed subscribe https://pracucci.com/feed.xml

Comments