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();
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:
- Medium: https://medium.com/@nhannguyendevjs/
- Dev: https://dev.to/nhannguyendevjs/
- Hashnode: https://nhannguyen.hashnode.dev/
- Linkedin: https://www.linkedin.com/in/nhannguyendevjs/
- X (formerly Twitter): https://twitter.com/nhannguyendevjs/
- Buy Me a Coffee: https://www.buymeacoffee.com/nhannguyendevjs
Top comments (0)