Sending a message to all open windows/tabs using JavaScript [duplicate]

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.)

Answers:

Answer

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.

Answer

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.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.