Skip to main content

Cross-Document Communication With The Broadcast Channel API In JavaScript

By Web Design4 min read

In my continued effort to catch up on recent(ish) additions to the “Widely Available” web platform baseline features, I wanted to play with the Broadcast Channel API. This API provides a publish and subscribe (PubSub) paradigm that allows messages to be posted across browser windows and tabs on the same domain and origin context (on the same device – it doesn’t share messages over the network).

Run this demo in my JavaScript Demos project on GitHub.

View this code in my JavaScript Demos project on GitHub.

“loop back” events were an issue I always had to deal with. When a browser would publish an event to the Pusher API, I included a “client UUID” that would be included with the subsequent broadcast event; and then ignored by the browser that emitted it. It’s nice to see that the BroadcastChannel() API side-steps this issue entirely.

I imagine the BroadcastChannel() API will be good for keeping browser tabs in sync. At least from the perspective of a single user. In order to synchronize experiences across users and devices, something more akin to WebSockets or Server Sent Events (SSE) will need to be used.

Want to use code from this post?
Check out the license.


https://bennadel.com/4869


Source link