Let's assume, we have a requirement for the same where we want to broadcast to the same page, for example: if from profile page we have triggered logout and want this to reflect to the other tab and i have receiving event listener on the same page. We can achieve this using 2 BroadcastChannel
, following steps can help achieve the same.
BroadcastChannel
.postMessage
.onmessage
.<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Broadcast channel on the same page</title>
</head>
<body>
<label>Enter your name</label>
<input id="name-field" placeholder="Enter Your Name" />
<h1 id="title">Hi</h1>
<script>
var bcSender = new BroadcastChannel('broadcast-receiver');
var bcReceiver = new BroadcastChannel('broadcast-receiver');
(() => {
const nameField = document.getElementById('name-field');
nameField.onchange = (e) => {
const inputValue = e.target.value;
console.log('inputValue', inputValue);
bcSender.postMessage(inputValue);
}
// receiver
const title = document.getElementById('title');
const setTitle = (name) => {
title.innerHTML = 'Hi ' + name;
}
bcReceiver.onmessage = (messageEvent) => {
console.log('onMessage', messageEvent.data);
setTitle(messageEvent.data);
}
})();
</script>
</body>
</html>
class BroadcasterDualChannel {
constructor(listener, channelName) {
this.broadcaster = new BroadcastChannel(channelName);
this.messageReceiver = new BroadcastChannel(channelName);
this.messageReceiver.onmessage = (event) => {
listener(event.data);
}
}
postmessage(data) {
this.broadcaster.postMessage(data);
}
}
var broadcaster = new BroadcasterDualChannel((data) => alert(data));
broadcaster.postmessage("Hello World, i am on the same page");