Entries tagged ‘localstorage’
Using the localStorage object, the storage event and the postMessage() API, it is possible for browser windows to discover each other and to communicate with each other.
Crosscasting is a small Dojo package that publishes Dojo PubSub events to other browser windows that are running the Crosscasting code and are active within the same domain. Crosscasting of course stands for cross-window broadcasting.
Check out the example page, which of course you should open a couple different windows. Right now this only seems to work in the latest WebKit nightly builds.
The implementation is quite straight-forward. The first part is the Window Discovery Phase. An item is set in localStorage, which triggers the storage event. The Storage Event object has a source attribute which points to the Window object that set the item. (The storage implementation in Firefox 3.5 does not support this.) This is how a window informs other windows of its existence. The other windows subsequently use the postMessage() API to send a message to the original window. The Message Event also has a source attribute, pointing at the Window object that posted the message. At this point all windows know of each other’s existence. This phase is triggered by invoking supercollider.crosscast.init()
The second part is broadcasting Dojo PubSub events. Using supercollider.crosscast.subscribe("topic") you can register topics for broadcasting. The topic and any arguments are serialized to JSON and send to all other windows through postMessage(). The other window deserializes the message back to the PubSub event and publishes it locally.
// Initialize and start discovery
supercollider.crosscast.init();
// Subscribe to a topic for crosscasting
supercollider.crosscast.subscribe('crosscast/test');
// Subscribe to the topic
dojo.subscribe('crosscast/test', function(s) { alert(s) });
// Publish a PubSub event, both locally and to other windows
dojo.publish('crosscast/test', ['hello world']);
Again, have a look at the example. You can find the source at js-collider/crosscast.
P.S. I do not believe this is an original idea, but when I set about implementing this earlier today I could no longer find the site where I read this first. If you do know which site I’m talking about, let me know in the comments so I can give proper credit. Thanks!
