I have the following html file. When I open it the console only shows "BroadcastChannel created …" and "Posting message to channel". Neither the eventlistener nor the onmessage function triggers.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>BroadcastChannel Simple Test</title>
</head>
<body>
<script>
// Create a BroadcastChannel
const messageChannel = new BroadcastChannel('newMessageChannel');
console.log("BroadcastChannel created:", messageChannel);
// Set up the message event listener
messageChannel.onmessage = (event) => {
console.log("new message received on message!", event.data);
};
messageChannel.addEventListener('message', (event) => {
console.log("new message received eventlistener!", event.data);
});
// Immediately post a message to the channel
setTimeout(() => {
console.log("Posting message to channel");
messageChannel.postMessage("data");
}, 1000);
</script>
</body>
</html>
I tested it on two different machines in two different browsers.
2
Answers
The Broadcast Channel API allows basic communication between browsing contexts (that is, windows, tabs, frames, or iframes) and workers on the same origin.
For the Broadcast Channel API to work you need comminucation with 2 different browsing contexts in this, 2 browser tabs of same origin where one acts as a producer/listener and one acts as a consumer.
Try opening a second browser window with the same url and you should see the message on the first browser tab.
The Broadcast Channel API is designed for inter-window communication. While your code is currently testing within a single browsing context, it’s important to try opening it in multiple tabs to observe its intended behavior. For internal communication within a single window, consider alternative mechanisms like Local Storage, WebSockets, or Custom Events.