Skip to content

Instantly share code, notes, and snippets.

@sleepygarden
Created December 2, 2015 21:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sleepygarden/8a4d2084e49e7f8a596e to your computer and use it in GitHub Desktop.
Save sleepygarden/8a4d2084e49e7f8a596e to your computer and use it in GitHub Desktop.
ARC Storage - localStorage which syncs across tabs and clears once all tabs using it are gone
// ARC Storage - localStorage which syncs across tabs and clears once all tabs using it are gone.
// refreshing with a single tab open also wipes it
// tries awful hardto match the Storage API, but uses
var ARCStorage = (function(){
var arcStorage = {}, arcStoreSharers = 0, didInitSync = false;
$(window).focus(function() {
sync();
});
$(window).on('beforeunload', function(){
save();
var currentSharers = localStorage.getItem('arc-store-shares');
// you're the last one to disconnect, you must also clear the key
if (currentSharers <= 1){
localStorage.removeItem('arc-store');
localStorage.removeItem('arc-store-shares');
}
else {
localStorage.setItem('arc-store-shares', --currentSharers);
}
// pops alert which gives time to read debug log before the window/tab is closed
// return "HALT FOR LOGGING";
});
function sync(){
arcStorage = localStorage.getItem('arc-store');
arcStoreSharers = localStorage.getItem('arc-store-shares');
if (arcStoreSharers === null){
arcStoreSharers = 0;
}
if (arcStorage === null){
arcStorage = {};
save();
}
else {
arcStorage = JSON.parse(arcStorage);
}
if (didInitSync === false){
localStorage.setItem('arc-store-shares', ++arcStoreSharers);
didInitSync = true;
}
}
function save(){
localStorage.setItem('arc-store', JSON.stringify(arcStorage));
}
function length(){
return Object.keys(arcStorage).length;
}
function key(index){
return arcStorage[Object.keys(arcStorage)[index]];
}
function getItem(key){
if (arcStorage[key] === undefined){
return null; // i hate using null, but i'm trying to be compliant to Storage
}
else {
return arcStorage[key];
}
}
function setItem(key, value){
arcStorage[key] = value;
save();
}
function removeItem(key){
delete arcStorage[key];
save();
}
function clear(){
arcStorage = {};
save();
}
return {
length : length,
key : key,
getItem : getItem,
setItem : setItem,
removeItem : removeItem,
clear : clear
};
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment