Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 437
Kev Avatar asked Jul 08 '09 20:07

Kev


People also ask

How to communicate between two Browser Tabs?

Broadcast Channel is a web API that enables communication across tabs, windows, frames, iframes and even workers from the same source, and unlike localStorage, the message object sent can be of any Object type, making it ideal for cross-tab communication. The downside of Broadcast Channel is its browser compatibility.

What is postMessage?

postMessage() is a safe way to send messages between windows in different domains or origins. One can also post to an IFrame. The data being sent is serialized using the structured clone algorithm and will accept almost any type of simple or complex data.

Is localStorage shared between tabs?

The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.


2 Answers

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.

like image 172
brianreavis Avatar answered Sep 19 '22 01:09

brianreavis


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.

like image 45
Rafael Avatar answered Sep 19 '22 01:09

Rafael