Skip to content

Instantly share code, notes, and snippets.

@ika18
Last active December 21, 2015 06:39
Show Gist options
  • Save ika18/6265621 to your computer and use it in GitHub Desktop.
Save ika18/6265621 to your computer and use it in GitHub Desktop.
Use localStorage to share one comet across multiple tabs

NOTE:

  • The tab which triggers the localStorage's key/value will not fire 'storage' event. But the others will.
  • If the tab is exited with an exception, then it won't fire 'storage'.
var timeId = (new Date()).getTime();
window.addEventListener('load', function () {
var tabs = localStorage.getItem('tabs');
if (!tabs) {
localStorage.setItem('tabs', JSON.stringify([timeId]));
localStorage.setItem('comet', timeId);
console.log('comet connect');
} else {
var tabArray = JSON.parse(tabs);
tabArray.push(timeId);
localStorage.setItem('tabs', JSON.stringify(tabArray));
}
});
window.addEventListener('storage', function (e) {
var key = e.key;
switch (key) {
case 'comet':
// if comet's new value is null,
// then prepare connect another comet
if (!e.newValue) {
var tabs = localStorage.getItem('tabs');
var tabArray = JSON.parse(tabs);
if (tabArray[0] === timeId) {
console.log('another commet connect');
localStorage.setItem('comet', timeId);
}
}
break;
}
});
window.addEventListener('beforeunload', function (e) {
var tabs = localStorage.getItem('tabs');
var comet = localStorage.getItem('comet');
var tabArray = JSON.parse(tabs);
if (tabArray.length !== 1) {
tabArray = tabArray.filter(function (item) {
return item !== timeId;
});
localStorage.setItem('tabs', JSON.stringify(tabArray));
} else {
localStorage.removeItem('tabs');
}
// if this comet tab is closed, then remove 'comet' key in localStorage
if (comet == timeId) {
localStorage.removeItem('comet');
console.log('comet disconnect');
}
});
@tshao
Copy link

tshao commented Aug 19, 2013

cool!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment