Angular Cross Chat Tab with the BroadcastChannel API

nhannguyendevjs

Nhan Nguyen

Posted on August 21, 2024

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:

💖 💪 🙅 🚩
nhannguyendevjs
Nhan Nguyen

Posted on August 21, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related