Can browser tabs talk (between one another)?
One interesting thing I have learned recently (and I admit I didn't know and never used this before) is that it is super easy to send messages between browser tabs using BroadcastChannel:
// Create channel (both tabs).
const channel = new BroadcastChannel( 'my-channel-name' );
// Listen to messages (tab 1).
channel.addEventListener( 'message', evt => {
console.log( evt.data );
} );
// Send messages (tab 2).
channel.postMessage( { ... } );
So what exactly is broadcast channel? As MDN describes:
The BroadcastChannel interface represents a named channel that any browsing context of a given origin can subscribe to. It allows communication between different documents (in different windows, tabs, frames or iframes) of the same origin. Messages are broadcasted via a message event fired at all BroadcastChannel objects listening to the channel.
It means that BroadcastChannel allows sending message between different documents (so windows, tab, frames and iframes) within the same origin. It is based on publish subscribe pattern which should make it easier to understand.
Does postMessage
sounds familiar?
For anyone who have ever tried to send data between, for example, iframe and its parent window, postMessage()
may ring a bell. There is a very similar mechanism which allows passing messages directly between Window
objects. The main difference is that it allows for cross-origin communication so its scope is broader in this regard. On the other hand, it does not utilize publish subscribe pattern, only direct messages (and one needs target window handle), which means it is more cumbersome to use.
Demo time!
Were simple demo is available on my codepen (you need to open both tabs):
Have you ever used BroadcastChannel? Or have any interesting cases or solutions using it to share?
Any thoughts?