
Modern web applications often allow users to open the same website in multiple browser tabs or windows. For example, a user might open an online shopping website in one tab and their account dashboard in another.
When an action takes place in one tab, other tabs may need to know about it. If a user logs out, updates their profile or changes application settings, the other open tabs should ideally reflect that change.
The Broadcast Channel API is a browser technology that allows different browsing contexts to exchange messages when they share the same origin and channel name.
It provides a simple messaging mechanism for communication between tabs, windows, frames and certain other compatible browsing contexts.
This guide explains how the Broadcast Channel API works, how to create and receive messages, how to use it in JavaScript and React, its security considerations, practical applications and project ideas.
The Broadcast Channel API is a JavaScript browser API that allows communication between browsing contexts through a named communication channel.
A browsing context can include:
A browser tab.
A separate browser window.
An iframe.
Other compatible contexts within the same origin.
Each context can create a BroadcastChannel using a channel name.
Contexts that create channels with the same name and compatible origin can exchange messages through that channel.
For example, imagine a user has opened three tabs of the same application. Each tab creates a channel named user-session.
If one tab broadcasts a logout message, the other tabs listening to that channel can receive the message and respond.
The API handles message delivery between participating contexts without requiring developers to manually identify each tab.
Applications often need to keep multiple browser contexts consistent.
Without a messaging mechanism, developers might use repeated server requests, shared storage checks or custom communication techniques.
These approaches can introduce unnecessary complexity.
The Broadcast Channel API provides a direct way to exchange messages between compatible browsing contexts.
Its advantages include:
Simple communication between browser tabs.
No need to maintain a server connection just for local tab messaging.
Support for structured message data.
Useful coordination between application windows.
Reduced reliance on repeated polling for certain synchronisation tasks.
A straightforward event-based programming model.
It is important to understand that the API only coordinates contexts that can access the same channel. It does not automatically synchronise application data or guarantee that messages are permanently stored.
The API uses a channel name to identify a communication group.
The basic process is:
A browsing context creates a BroadcastChannel.
Another compatible context creates a channel using the same name.
One context sends a message using postMessage().
Other listening contexts receive the message through a message event.
Each context processes the message according to its application logic.
A context closes its channel when it no longer needs it.
The sender does not need to know how many other tabs are listening.
A channel is not a permanent message queue. A context that starts listening after a message was sent should not expect to receive that earlier message.
The BroadcastChannel constructor creates a channel with a specified name.
Example:
const channel = new BroadcastChannel("app-channel");
Every compatible browsing context using the same channel name can participate in that communication group.
A channel name should be descriptive so that its purpose is easy to understand.
Examples include:
user-session
cart-updates
theme-settings
notification-events
dashboard-sync
A separate channel can be created for each communication purpose, or an application can use one channel with different message types.
The postMessage() method sends data through a BroadcastChannel.
Example:
const channel = new BroadcastChannel("app-channel");
channel.postMessage({
type: "USER_LOGIN",
username: "Aarav"
});
Other contexts listening to the same channel can receive the message.
The message is structured-cloneable data. Common supported values include:
Strings.
Numbers.
Booleans.
Arrays.
Plain objects.
Dates.
Maps and Sets.
ArrayBuffer and other supported structured data.
Functions and certain other values cannot be cloned through the structured clone algorithm.
For example, this is not a suitable message:
channel.postMessage({
callback: () => console.log("Hello")
});
Functions cannot be transferred as ordinary message data using this API.
Instead, send data that the receiving context can interpret.
A browsing context can listen for messages using the message event.
Example:
const channel = new BroadcastChannel("app-channel");
channel.addEventListener("message", (event) => {
console.log("Received message:", event.data);
});
The received data is available through event.data.
A complete example can use separate sender and receiver logic.
Sender:
const channel = new BroadcastChannel("app-channel");
channel.postMessage({
type: "THEME_CHANGED",
theme: "dark"
});
Receiver:
const channel = new BroadcastChannel("app-channel");
channel.addEventListener("message", (event) => {
if (event.data.type === "THEME_CHANGED") {
console.log("New theme:", event.data.theme);
}
});
Both code examples must run in compatible browsing contexts that use the same channel name and origin.
The API also supports the onmessage event handler.
Example:
const channel = new BroadcastChannel("notifications");
channel.onmessage = (event) => {
console.log("Notification:", event.data);
};
Developers can use either addEventListener() or onmessage to receive messages.
Using addEventListener() can be convenient when a component needs to register and remove a specific handler without replacing another handler.
A channel should be closed when a browsing context no longer needs it.
The close() method releases the channel object from the context's participation in messaging.
Example:
const channel = new BroadcastChannel("app-channel");
channel.close();
After closing, the channel object should no longer be used for sending or receiving messages.
Closing channels when they are no longer needed is particularly important in applications that frequently create and remove components or communication sessions.
The following example demonstrates communication between two browser tabs.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Broadcast Channel Demo</title>
</head>
<body>
<h1>Cross-Tab Communication</h1>
<input id="messageInput" placeholder="Enter a message">
<button id="sendButton">Send Message</button>
<ul id="messages"></ul>
<script src="script.js"></script>
</body>
</html>
const channel = new BroadcastChannel("demo-channel");
const input = document.getElementById("messageInput");
const button = document.getElementById("sendButton");
const messages = document.getElementById("messages");
button.addEventListener("click", () => {
const message = input.value.trim();
if (!message) return;
channel.postMessage({
type: "NEW_MESSAGE",
text: message,
timestamp: Date.now()
});
input.value = "";
});
channel.addEventListener("message", (event) => {
if (event.data.type !== "NEW_MESSAGE") return;
const item = document.createElement("li");
item.textContent = event.data.text;
messages.appendChild(item);
});
window.addEventListener("pagehide", () => {
channel.close();
});
Open the same page in two browser tabs. When a message is sent from one tab, the other tab can display it.
The example uses textContent rather than innerHTML to display received text safely.
The sending context does not receive its own message through the channel. If the sender also needs to update its own interface, it should update its local state separately.
The Broadcast Channel API can be integrated into React applications using useEffect.
A React component can create a channel when it is mounted, listen for incoming messages and close the channel during cleanup.
Example:
import { useEffect, useState } from "react";
function MessageSync() {
const [messages, setMessages] = useState([]);
useEffect(() => {
const channel = new BroadcastChannel("react-message-channel");
function handleMessage(event) {
setMessages(previous => [
...previous,
event.data
]);
}
channel.addEventListener("message", handleMessage);
return () => {
channel.removeEventListener("message", handleMessage);
channel.close();
};
}, []);
function sendMessage() {
const channel = new BroadcastChannel("react-message-channel");
channel.postMessage({
text: "Hello from React"
});
channel.close();
}
return (
<div>
<button onClick={sendMessage}>
Send Message
</button>
{messages.map((message, index) => (
<p key={index}>{message.text}</p>
))}
</div>
);
}
export default MessageSync;
This example demonstrates the API, but a production application should usually manage a shared channel through a reusable hook or service instead of creating separate channel objects for every action.
A reusable hook can provide a consistent interface for sending and receiving messages.
One important application of the Broadcast Channel API is session coordination.
Consider an application where a user is logged in through multiple tabs.
If the user logs out in one tab, the other tabs should also update their interface and stop treating the session as active.
Example:
const sessionChannel = new BroadcastChannel("user-session");
function logout() {
sessionChannel.postMessage({
type: "LOGOUT"
});
// Perform the local logout process.
}
sessionChannel.addEventListener("message", (event) => {
if (event.data.type === "LOGOUT") {
// Clear local application state.
// Redirect to the login page.
}
});
The receiving tab should also verify its authentication state with the server when appropriate.
A broadcast message is not proof that a user has been authenticated or logged out. It is only a signal to update local application behaviour.
The server must remain responsible for authoritative session validation.
An online shopping application may have several tabs open at the same time.
A user could add a product to the cart in one tab and expect the cart count in another tab to change.
Broadcast Channel can communicate that update.
Example:
const cartChannel = new BroadcastChannel("cart-updates");
function notifyCartUpdate(productId) {
cartChannel.postMessage({
type: "CART_UPDATED",
productId
});
}
cartChannel.addEventListener("message", (event) => {
if (event.data.type === "CART_UPDATED") {
// Refresh or reconcile the local cart.
}
});
The message should be treated as a notification that the cart may have changed.
The receiving tab can retrieve the latest cart data from an authoritative source or reconcile it with its existing state.
This helps avoid treating an individual broadcast message as the complete cart record.
Users may change their display preferences in one tab and expect the same settings to apply in other tabs.
For example:
const settingsChannel = new BroadcastChannel("app-settings");
function updateTheme(theme) {
document.documentElement.dataset.theme = theme;
settingsChannel.postMessage({
type: "THEME_CHANGED",
theme
});
}
settingsChannel.addEventListener("message", (event) => {
if (event.data.type === "THEME_CHANGED") {
document.documentElement.dataset.theme = event.data.theme;
}
});
This allows compatible open tabs to respond to theme changes.
For long-term persistence, the application can also store the preference in a suitable storage system.
Messages sent through Broadcast Channel use the structured clone algorithm.
This mechanism creates a copy of supported data for delivery to another context.
For example:
const channel = new BroadcastChannel("data-channel");
channel.postMessage({
user: {
name: "Ravi",
skills: ["JavaScript", "React"]
},
active: true
});
The receiver gets a structured copy of the data.
This means that changing the received object does not directly modify the original object in the sending context.
Developers should avoid sending unnecessarily large objects because cloning and delivering large amounts of data can consume memory and processing resources.
Both Broadcast Channel and localStorage can be used in multi-tab application designs, but they serve different purposes.
Broadcast Channel:
Designed for direct messaging between compatible contexts.
Supports structured-cloneable messages.
Does not automatically persist messages.
Uses an event-based communication model.
localStorage:
Provides persistent key-value storage.
Stores values as strings.
Can notify other documents through the storage event when relevant changes occur.
Is useful when information needs to remain available after a tab closes.
The storage event is generally fired in other relevant documents, not in the document that performed the storage update.
Broadcast Channel is more suitable for message-based coordination, while localStorage is useful when persistence is required.
Some applications use both: localStorage for stored preferences and Broadcast Channel for immediate notifications.
A SharedWorker is a worker that can be accessed by multiple browsing contexts within a compatible origin and environment.
It can provide shared processing and communication through ports.
Broadcast Channel has a simpler purpose: exchanging messages between contexts through a named channel.
Use Broadcast Channel when the application mainly needs straightforward message distribution.
Consider SharedWorker when shared background processing, centralised state or more advanced connection management is required.
The two technologies solve related but different problems.
The Broadcast Channel API is supported by modern browsers, but developers should verify compatibility for their target browser versions.
Important limitations include:
Communication is restricted by origin and channel rules.
Messages are not stored for future listeners.
The API does not provide authentication.
It does not guarantee delivery to contexts that are closed or unavailable.
It does not automatically resolve conflicting application state.
It is not a replacement for server-to-client messaging across different devices.
Large message payloads can create unnecessary processing overhead.
Developers should also handle environments where the API is unavailable.
A simple feature check is:
if ("BroadcastChannel" in window) {
const channel = new BroadcastChannel("app-channel");
// Use the channel.
} else {
console.log("Broadcast Channel API is unavailable.");
}
Applications can provide an alternative communication mechanism when required.
The Broadcast Channel API is designed for communication between contexts within the same origin. However, same-origin access does not mean every message should automatically be trusted.
Security practices include:
Validate the structure and type of received messages.
Avoid transmitting passwords, authentication tokens or other secrets unnecessarily.
Never treat a broadcast message as proof of authentication.
Do not execute received strings as JavaScript.
Avoid displaying untrusted message content through unsafe HTML insertion.
Keep channel names specific to their application purpose.
Limit message sizes and frequency.
Revalidate important operations with the server.
For example, a receiving context should validate message types before acting:
channel.addEventListener("message", (event) => {
const message = event.data;
if (
!message ||
typeof message !== "object" ||
message.type !== "THEME_CHANGED"
) {
return;
}
if (!["light", "dark"].includes(message.theme)) {
return;
}
document.documentElement.dataset.theme = message.theme;
});
A well-designed application treats cross-tab messages as coordination signals, not as trusted authority for sensitive operations.
Using different channel names: Contexts must use the same channel name to communicate.
Assuming messages are stored: A new listener does not receive messages sent before it joined the channel.
Forgetting to close channels: Long-running applications should close channels when they are no longer required.
Sending unsupported data: Functions and other non-cloneable values cannot be sent as ordinary message payloads.
Broadcasting sensitive information: Do not use the channel to distribute secrets that do not need to be shared.
Trusting every incoming message: Validate received data before updating application state.
Expecting cross-origin communication: Different origins cannot use a shared BroadcastChannel simply by choosing the same name.
Assuming the sender receives its own message: A context should update its own interface separately when it also needs to respond to its outgoing message.
Ignoring state conflicts: Simultaneous updates from multiple tabs need a clear reconciliation strategy.
Use descriptive channel names.
Define a consistent message format.
Include a type field in messages.
Validate all received data.
Send only the information required by the receiving context.
Avoid transmitting credentials or secrets.
Close channels when they are no longer needed.
Handle unsupported browsers.
Keep server-side authentication authoritative.
Design a strategy for conflicting updates.
Avoid unnecessary high-frequency messaging.
Test behaviour with multiple tabs and windows.
Use persistent storage when messages or preferences must survive page closure.
Build a simple page where users can send messages between two open tabs.
Display incoming messages and timestamps. Remember that the browser channel is local to compatible contexts, not a replacement for an internet-based chat server.
Create a login interface that broadcasts a logout event when the user signs out.
Other open tabs should respond by clearing their local application state and showing the login screen.
Build a shopping cart demo with multiple tabs.
When a product is added or removed, broadcast an update notification and refresh the other tab's cart data.
Create a website with light and dark themes.
Changing the theme in one tab should update the appearance of other open tabs.
Build a dashboard where one tab changes a filter or setting and other tabs receive the update.
Add message validation and a clear strategy for handling simultaneous changes.
Developers should understand:
JavaScript objects and events.
Browser APIs.
Same-origin policy.
Structured cloning.
Asynchronous programming.
HTML and CSS.
localStorage and sessionStorage.
React state and effects.
Client-side authentication.
Message validation.
Application state synchronisation.
Browser developer tools.
These skills are useful when building multi-tab applications and coordinating frontend behaviour.
Knowledge of browser communication APIs can support several development roles.
Frontend Developer: Builds applications that coordinate state and interactions across browser tabs.
JavaScript Developer: Uses browser APIs to implement communication and application behaviour.
React Developer: Integrates cross-tab messaging with reusable components and application state.
Full Stack Developer: Connects frontend synchronisation with reliable backend session and data management.
Web Application Engineer: Builds dashboards, collaboration tools and multi-window interfaces.
Practical projects demonstrating reliable cross-tab communication can help developers strengthen their frontend portfolios.
Follow this learning sequence:
Learn JavaScript events and event listeners.
Understand browser tabs, windows and browsing contexts.
Study the same-origin policy.
Learn how to create a BroadcastChannel.
Practise sending messages with postMessage().
Receive messages through the message event.
Learn structured cloning and supported data types.
Implement channel cleanup with close().
Integrate messaging into a React application.
Build projects involving session, cart and settings synchronisation.
You can explore additional learning resources through EasyShiksha Online Courses, search for relevant topics through EasyShiksha Course Search, and explore the Web Development learning section.
The Broadcast Channel API provides a simple way for compatible browser contexts to exchange messages through named communication channels.
It is useful for synchronising sessions, shopping carts, application preferences and dashboard updates across multiple tabs.
Its event-based interface and structured message support make it easier to coordinate local browser contexts without building a separate server communication system for every task.
However, developers must understand its limitations. Messages are not permanently stored, communication is origin-restricted and application state conflicts still need to be managed.
By combining Broadcast Channel with proper message validation, lifecycle cleanup and reliable server-side data handling, developers can build more consistent multi-tab web applications.
The Broadcast Channel API is a browser feature that allows compatible browsing contexts within the same origin to exchange messages through a named communication channel.
BroadcastChannel is the JavaScript interface used to create and manage a named channel. It provides methods and events for sending and receiving messages.
Each tab creates a BroadcastChannel with the same name. One tab sends a message using postMessage(), and other listening tabs receive it through the message event.
The postMessage() method sends structured-cloneable data to other compatible contexts listening on the same channel.
Developers can register a message event listener using addEventListener() or assign a handler through the onmessage property.
No. The API is restricted by origin. Contexts from different origins cannot communicate simply by creating channels with identical names.
No. A BroadcastChannel message is delivered to other channel objects rather than the channel object that sent it. The sender should update its own state separately when needed.
Call the close() method on the channel object. This removes that object from participation in the channel.
Yes. It supports structured-cloneable data, including common objects, arrays, dates, maps and sets. Functions cannot be sent as ordinary message payloads.
They serve different purposes. Broadcast Channel is designed for direct message communication, while localStorage provides persistent key-value storage and can notify other documents of changes through the storage event.
Yes. Developers can create a channel inside useEffect, register a message listener and close the channel during cleanup.
Yes. A tab can broadcast a logout event so other tabs can update their local state. However, the backend must remain responsible for authoritative authentication and session validation.
No. It is not a persistent message queue. Contexts should not expect to receive messages that were sent before they started listening.
It follows browser origin restrictions, but applications must still validate messages and avoid sending sensitive information unnecessarily. Same-origin messages should not automatically be treated as trusted instructions.
Compatible iframe contexts can participate when they share the required origin and channel name. Cross-origin iframe communication is not provided simply by using the same channel name.
Broadcast Channel provides straightforward message distribution between compatible contexts. SharedWorker can provide shared background processing and communication through worker ports.
Yes. A tab can broadcast that the cart has changed. Other tabs can then refresh or reconcile their cart information using the appropriate data source.
The message is not stored for future listeners. A tab that joins the channel later will not automatically receive earlier messages.
No. Communication between compatible local browsing contexts can happen directly through the browser API. A backend may still be necessary for authentication, persistent data and communication between different devices.
It helps developers build applications that coordinate information across multiple tabs and windows. It is useful for session management, settings synchronisation, dashboards and other multi-context web applications.
More News Click here
Discover thousands of colleges and courses, enhance skills with online courses and internships, explore career alternatives, and stay updated with the latest educational news..
Gain high-quality, filtered student leads, prominent homepage ads, top search ranking, and a separate website. Let us actively enhance your brand awareness.