Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helping browser windows rendezvous for window.postmessage

I'd like to enable two windows to communicate using window.postMessage. But these windows have no initial connection---one is not an iframe of the other. Is there any way to enable these two windows to "find" each other so that they can communicate? There doesn't seem to be any way for a window to lookup another by "name". I can arrange for both to set a cookie in the same domain, but there's no way to put an object/pointer in a cookie.

like image 951
David Karger Avatar asked May 13 '26 09:05

David Karger


1 Answers

I was wrong! HTML5 weekly just came out, and included a link to an article solving this exact problem.

The technique makes use of localStorage as an observable and modifiable resource shared by all windows on the same domain. It turns out Facebook and Google have been doing this for years!

There's a demo (open this in several windows side by side, it's pretty mindblowing) with very readable code, but the central mechanisms are as follows:

Broadcast an event

window.localStorage.setItem('key', value);

Listen for events

window.addEventListener('storage', function(event){
    var message = event.newValue;
}

Blown away by this. I'm going to have to implement this myself somehow.

like image 191
Barney Avatar answered May 15 '26 22:05

Barney