Last active
August 29, 2015 14:00
-
-
Save kaareal/1232403fac91516ece0d to your computer and use it in GitHub Desktop.
Simple cross window communication using localstorage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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