Skip to content

Instantly share code, notes, and snippets.

@MoonScript
Created August 27, 2015 00:08
Show Gist options
  • Save MoonScript/0f5f0ba2b967a6dc52a0 to your computer and use it in GitHub Desktop.
Save MoonScript/0f5f0ba2b967a6dc52a0 to your computer and use it in GitHub Desktop.
Cross-tab communication on the same origin.
tabMessenger.on('minimize', function(data) {
// data.id
});
tabMessenger.send('minimize', {
id: 123
});
window.tabMessenger = {
send: function(messageKey, messageData) {
// Set the value in localStorage to generate a storage event that the other windows/tabs can respond to
localStorage.setItem('tab-messenger-message', JSON.stringify({
key: messageKey,
data: messageData
}));
// Immediately delete the localStorage object, since we don't need it to stick around
localStorage.removeItem('tab-messenger-message');
},
on: function(messageKey, callback) {
window.addEventListener('storage', function(e) {
var tabMessage;
// Only respond to first storage event when the value gets initially set ("oldValue" will be null)
// Ignore the 2nd event when it's deleted, when "oldValue" will still be populated
if (e.key !== 'tab-messenger-message' || e.oldValue) {
return;
}
tabMessage = JSON.parse(e.newValue);
if (tabMessage.key === messageKey) {
callback(tabMessage.data);
}
}, false);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment