Skip to content

Instantly share code, notes, and snippets.

@antoine-pous
Created November 12, 2015 14:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save antoine-pous/019cf708dd5587ac7fb0 to your computer and use it in GitHub Desktop.
Save antoine-pous/019cf708dd5587ac7fb0 to your computer and use it in GitHub Desktop.
Choose the best storage place available
/**
* "THE BEER-WARE LICENSE" (Revision 42):
* <gecko@dvp.io> wrote this file. As long as you retain this notice you
* can do whatever you want with this stuff. If we meet some day, and you think
* this stuff is worth it, you can buy me a beer in return Antoine "Gecko" Pous
*/
// See https://gist.github.com/Antoine-Pous/d0a597ca756b5411ebd2
var cookieChecker = function(){return"undefined"!=typeof navigator.cookieEnabled?(document.cookie="ac=test",e=-1!=document.cookie.indexOf("ac")?!0:!1,document.cookie="ac=; expires=Thu, 01 Jan 1970 00:00:00 UTC",e):navigator.cookieEnabled},
// See https://gist.github.com/Antoine-Pous/c73e5a3a3b1e9507597d
LSChecker = function(){try{return localStorage.setItem("test","test"),localStorage.removeItem("test"),!0}catch(t){return!1}},
// Storage status
canStore;
if(canStore = LSChecker()) {
var configRead = function(name) {
return JSON.parse(localStorage.getItem(name));
}, configWrite = function(name, data) {
return localStorage.setItem(name, JSON.stringify(data));
}, configRemove = function(name) {
return localStorage.removeItem(name);
}
} else if(canStore = cookieChecker()) {
var configRead = function(name) {
return AC_config.name;
}, configWrite = function(name, data) {
var d = new Date();
d.setTime(d.getTime() + (365*24*60*60*1000));
return document.cookie = name + "=" + JSON.stringify(data) + "; expires=" + d.toUTCString();
}, configRemove = function(name) {
return document.cookie = name + "=; expires=Thu, 01 Jan 1970 00:00:00 UTC";
}
}
// We now store data in localstorage if available, or in cookies if localstorage is not available
// If both localstorage and cookies are not available no data can be stored
if(canStore) {
configWrite('auth', {login: 'Gecko', hash: 'sha256'});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment