Created
August 27, 2015 00:08
-
-
Save MoonScript/0f5f0ba2b967a6dc52a0 to your computer and use it in GitHub Desktop.
Cross-tab communication on the same origin.
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
tabMessenger.on('minimize', function(data) { | |
// data.id | |
}); | |
tabMessenger.send('minimize', { | |
id: 123 | |
}); |
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
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