EN
JavaScript - send messages between windows with BroadcastChannel
8 points
In this article, we would like to show you how we can communicate between different browser tabs.

Quick solution:
xxxxxxxxxx
1
const broadcastChannel = new BroadcastChannel('my-channel-name');
2
3
broadcastChannel.addEventListener('message', event => {
4
const message = event.data;
5
6
});
7
8
const broadcastMessage = (message) => {
9
broadcastChannel.postMessage(message);
10
};
BroadcastChannel
allows communication between tabs, frames, iframes and windows. The connection is made in the browser and doesn't need a backend.
The message is broadcast using the postMessage()
method and the recipients are windows that listen through the addEventListener.
Note:
Open this post in two or more tabs/windows, run example and send messages.
Practical example:
xxxxxxxxxx
1
<html>
2
<body>
3
<div id="window-name">Window name: null</div>
4
<div>
5
<input id="message-text" />
6
<button onclick="handleClick()">Broadcast</button>
7
</div>
8
<div>
9
<div>Recived messages:</div>
10
<textarea id="recived-messages" style="width: 260px; height: 200px"></textarea>
11
</div>
12
<script>
13
14
const windowNameElement = document.querySelector('#window-name');
15
const messageTextElement = document.querySelector('#message-text');
16
const recivedMessagesElement = document.querySelector('#recived-messages');
17
18
// ---------------------------------
19
20
const windowName = `window-${Date.now()}${Math.random()}`; // ~~ unique window name
21
const channelName = 'my-notifications'; // any name here
22
23
const broadcastChannel = new BroadcastChannel(channelName);
24
25
broadcastChannel.addEventListener('message', event => {
26
const message = event.data;
27
recivedMessagesElement.value += `${message.windowName}: ${message.windowMessage}\n`;
28
});
29
30
const broadcastMessage = (windowMessage) => {
31
const message = {
32
windowName: windowName,
33
windowMessage: windowMessage
34
};
35
broadcastChannel.postMessage(message);
36
};
37
38
// ---------------------------------
39
40
windowNameElement.innerText = `Window name: ${windowName}`;
41
42
const handleClick = (windowMessage) => {
43
broadcastMessage(messageTextElement.value);
44
messageTextElement.value = '';
45
};
46
47
</script>
48
</body>
49
</html>
Note:
BroadcastChannel
interface is not supported in Internet Explorer, Safari and older browsers, so use with caution.