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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With