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.