- 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'.
Last active
December 21, 2015 06:39
-
-
Save ika18/6265621 to your computer and use it in GitHub Desktop.
Use localStorage to share one comet across multiple tabs
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
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'); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
cool!