Skip to content

Instantly share code, notes, and snippets.

@kaareal
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaareal/1232403fac91516ece0d to your computer and use it in GitHub Desktop.
Save kaareal/1232403fac91516ece0d to your computer and use it in GitHub Desktop.
Simple cross window communication using localstorage
(function() {
var storage = window.localStorage;
var browserId = Date.now() + (Math.random() * 1000);
function get(key){
var result = storage.getItem(key);
if (typeof(result) == 'undefined') return result;
return JSON.parse(result);
}
function set(key, data) {
storage.setItem(key, JSON.stringify(data));
}
function getClients() {
var clients = get('__crosswindow') || [];
if (clients.length > 20) clients = clients.splice(0, 20);
return clients;
}
function register(){
var clients = getClients();
clients.push(browserId);
set('__crosswindow', clients);
}
function listen() {
register();
setInterval(function(){
var messages = get(browserId) || [];
if (!messages.length) return;
set(browserId, []);
messages.forEach(function(message){
onMessage(message);
});
}, 1000);
}
function send(data) {
var clients = getClients() || [];
clients.forEach(function(client){
if (client == browserId) return;
var old = get(client) || [];
if (old instanceof Array) {
old.push(data);
set(client, old);
}
});
}
function onMessage(data) {
window.dispatchEvent(new CustomEvent('message', { 'detail': data }));
}
window.addEventListener("message", function(e) {
if (e.origin !== window.location.origin) return;
send(e.data + '');
}, false);
listen();
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment