Skip to content

Instantly share code, notes, and snippets.

@SmugZombie
Last active July 9, 2018 21:26
Show Gist options
  • Save SmugZombie/08633284ab2cdd7988dd2fe16b14ff5d to your computer and use it in GitHub Desktop.
Save SmugZombie/08633284ab2cdd7988dd2fe16b14ff5d to your computer and use it in GitHub Desktop.
Uses base64 to encode both local storage names and contents.
function getLocalStorage(name){
name = btoa(name);
var now = parseInt(new Date() / 1000);
var expires = localStorage.getItem(name+"_expire");
if(localStorage.getItem(name) === null){ return ""; }
if(!expires){ try { return atob(localStorage.getItem(name)); } catch(err){ return localStorage.getItem(name); } }
else if(now >= expires){ localStorage.removeItem(name+"_expire"); localStorage.removeItem(name); return ""; }
else{ try {return atob(localStorage.getItem(name));} catch(err){return localStorage.getItem(name);} }
}
function setLocalStorage(name, value, minutes){
name = btoa(name); value = btoa(value);
if(minutes == null){ localStorage.setItem(name, value); localStorage.removeItem(name+"_expire"); return true} // No set expiration
else if(minutes == 0){ localStorage.removeItem(name); localStorage.removeItem(name+"_expire"); return true} // Setting to 0 kills the localStorage Item any any expiration
else{
epochExpire = parseInt(new Date() / 1000 + (minutes * 60));
localStorage.setItem(name, value); localStorage.setItem(name+"_expire", epochExpire);
return true
}
return false
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment