Sending a message to all open windows/tabs using JavaScript

19.3k Views Asked by At

I hear HTML5 has window.postMessage(), but it seems to require having a handle on the window (or tab, throughout this question) you're posting the message to. What if I want to broadcast to all open windows? Is this possible?

(What I'm trying to do is warn other windows without any server round-trips when a user does something in one window that affects the others, so that they can update their content. However, while some windows may be opened from existing ones--allowing me to intercept and store references to them--some fresh windows may be opened manually by the user and then a bookmark selected or URL typed in. In this case there doesn't seem to be a way to intercept and store references.)

3

There are 3 best solutions below

0
On BEST ANSWER

Assuming you don't need to broadcast a message to other websites (just your own), BroadcastChannel is made for this purpose.

const channel = new BroadcastChannel('myChannel');
channel.postMessage('myMessage');
channel.addEventListener('message', m => {
    console.log('Received message from other document', m);
});
6
On

I wrote a library to do just this: intercom.js (for the same reasons you outlined).

We're currently using it to broadcast notifications to all windows, so only one window needs to maintain a socket connection to the server. As some others suggested, it uses the localStorage API.

Usage is really simple:

var intercom = Intercom.getInstance();

$('a').on('click', function() {
     intercom.emit('notice', {message: 'Something just happened!');
});

To catch the message,

intercom.on('notice', function(notice) {
    console.log(notice.message);
});

The interface is designed to mimic socket.io.

5
On

IMO this is not possible using the postMessage. How about using sessionStoragelocalStorage? Writing to it should generate a storage event that should be propagated to all windows sharing the same session storage.