DEV Community

Nhan Nguyen
Nhan Nguyen

Posted on

Angular Cross Chat Tab with the BroadcastChannel API

Introducing the BroadcastChannel API

The BroadcastChannel API allows communication of different browsing contexts (windows, tabs, iframes). Itโ€™s explicitly designed to broadcast messages to other windows/tabs of the same origin.

The BroadcastChannel API was first introduced in 2015 and has gained wide support across modern browsers. As of 2023, itโ€™s supported in:

  • Chrome (54+)
  • Firefox (38+)
  • Edge (79+)
  • Safari (15.4+)
  • Opera (41+)

We can check caniuse.com for the most up-to-date browser support information.

How BroadcastChannel Works

Hereโ€™s a basic example:

// Create or join a channel
const channel = new BroadcastChannel('my-channel');

// Listen for messages
channel.onmessage = (event) => {
  console.log('Received message:', event.data);
};

// Send a message
channel.postMessage('Hello from this tab!');

// Close the channel when you're done
channel.close();
Enter fullscreen mode Exit fullscreen mode

Key Concepts

  • Channel Creation: When we create a BroadcastChannel, we either create a new channel or join an existing one with the same name.

  • Message Broadcasting: Messages sent through postMessage() are broadcasted to all other tabs/windows that have joined the same channel.

  • Same-Origin Policy: BroadcastChannel only works for pages from the same origin(protocol, domain, and port).

  • Data Types: We can send various data types, including objects, arrays, and ArrayBuffers.

Limitations and Considerations

BroadcastChannel has some limitations:

  • Same-Origin Restriction: It only works within the same origin, so we canโ€™t use it to communicate between different domains.

  • No Persistence: Messages are not stored. If no other tabs are listening when a message is sent, itโ€™s lost.

  • No Guaranteed Delivery: Thereโ€™s no built-in mechanism to ensure message delivery or order.

  • Performance: While generally efficient, it could impact performance.

Implementing Cross-Tab Communication in Angular

Weโ€™ll create a simple chat application that works across multiple tabs using Angular and the BroadcastChannel API. This will demonstrate real-time updates and typing indicators shared across tabs.

GitHub repository: https://github.com/nhannguyendevjs/cross-tab-chat

Demo link: https://cross-tab-chat.vercel.app/


I hope you found it helpful. Thanks for reading. ๐Ÿ™
Let's get connected! You can find me on:

Top comments (0)