Broadcasting Magic Across Tabs with the Broadcast Channels API
Using Broadcast Channels to instantly log out of all Browser Tabs.
In this rapidly evolving web world, it's crucial for applications to communicate effectively. When multiple tabs are open, it's sometimes essential for them to chat. But how can we, as developers, make this happen? Enter the Broadcast Channel API!
In this post, we will delve into the capabilities of the Broadcast Channel API and put it to practical use by implementing a "log out from all tabs" functionality. So, without further ado, let's dive in!
What are Broadcast Channels?
Broadcast Channels support communication between browsing contexts (such as tabs, windows, or iframes) on the same origin (domain, protocol, and port). It's akin to a magical string attached between different parts of your application, enabling them to send messages to one another. see (Broadcast Channel API on MDN)
This API provides a simple and powerful way to communicate between different tabs without the need for complicated setups or server-side help.
Getting Started
To create a Broadcast Channel, you create a new BroadcastChannel object and give it a name. Any browsing context that creates a BroadcastChannel with the same name can communicate with each other!
const channel = new BroadcastChannel('my_channel');
Now let's send and receive messages:
// Sending a message
channel.postMessage('Hello across tabs!');
// Receiving a message
channel.onmessage = (event) => {
console.log('Received: ', event.data);
};
Logging Out Across All Tabs - A Real-world Scenario
Imagine an application where a user is logged in across multiple tabs. When they log out from one tab, it's a best practice to log them out from all the tabs. Let's see how we can do this using the Broadcast Channel API.
Step 1: Setup the Broadcast Channel
When the user logs in, create a new Broadcast Channel. This can be done in your main JavaScript file or where your application initializes.
const logoutChannel = new BroadcastChannel('logout_channel');
Step 2: Listen for Logout Events
On each tab, listen for messages. If a message indicating that the user has logged out is received, perform the logout operation on this tab as well.
logoutChannel.onmessage = (event) => {
if (event.data === 'logout') {
// Perform the logout operation here
console.log('Logging out from this tab as well...');
}
};
Step 3: Broadcast the Logout Event
When the user initiates a logout in one tab, broadcast this event to all other tabs.
function userInitiatedLogout() {
// Perform the logout operation for the current tab
console.log('User logged out from this tab.');
// Notify other tabs
logoutChannel.postMessage('logout');
}
And that’s it! Whenever userInitiatedLogout() is called in any of the tabs, all other tabs will receive the message and log the user out.
Show me it working…..
Below is a small code example in VueJS, you can preview it here:
<template>
<div id="app">
<div v-if="isLoggedIn">
<h1>You are logged in</h1>
<button @click="userInitiatedLogout">Log out</button>
</div>
<div v-else>
<h1>You are logged out</h1>
</div>
</div>
</template>
<script setup>
import { shallowRef, onMounted, onBeforeUnmount } from 'vue'
// Create a reactive variable to store the login status
const isLoggedIn = shallowRef(true)
// Create a BroadcastChannel to communicate with other tabs
const logoutChannel = new BroadcastChannel('logout_channel')
// Create a function to log the user out
function userInitiatedLogout() {
isLoggedIn.value = false
logoutChannel.postMessage('logout')
}
onMounted(() => {
// Listen for logout events from other tabs
logoutChannel.onmessage = (event) => {
if (event.data === 'logout') {
isLoggedIn.value = false
}
}
})
onBeforeUnmount(() => {
// Close the channel when the component is unmounted
logoutChannel.close()
})
</script>
<style>
#app {
text-align: center;
margin-top: 60px;
}
</style>
Closing the Channel
Don't forget to close the channel when it's no longer needed, like when the user is logged out, to free up resources.
logoutChannel.close();
Conclusion
The Broadcast Channel API offers an elegant and simple way to communicate between browsing contexts on the same origin. As we have seen, it can be incredibly useful for synchronizing actions like logging out from all tabs. With just a few lines of code, you can make your web applications more responsive and user-friendly.
Happy coding! 🚀