Created
July 8, 2015 16:51
-
-
Save hattwj/b7174f7089c76b5a9ece to your computer and use it in GitHub Desktop.
Cross tab communication in CoffeeScript
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
event_prefix = 'cross-tabs:' | |
## | |
# Global function allows for triggering cross browser events | |
@cross_tabs_trigger = (ename, msg) -> | |
data = JSON.stringify(msg, null, 2) | |
localStorage.setItem(event_prefix + ename, data) | |
cross_tabs_handler = (e) -> | |
if e.key.startsWith(event_prefix) | |
console.log('received message: ' + e.key) | |
msg = JSON.parse(e.newValue); | |
$(document).trigger(e.key, msg) | |
if window.addEventListener | |
window.addEventListener "storage", cross_tabs_handler, false | |
else | |
# for IE | |
window.attachEvent "onstorage", cross_tabs_handler | |
return | |
## | |
# Now in one tab: | |
cross_tabs_trigger('widget:new', xhr) | |
## | |
# And in the other | |
$(document).on 'cross-tabs:widget:new', (e, xhr) -> | |
console.log('WE RECEIVED THE EVENT!!!') | |
console.log(xhr) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment