LocalStorage = new (function() {
var _supported = "localStorage" in window;
var _counter = {};
this.set = function(key, value, persistent) {
if(_supported) {
try {
if(typeof(value) == 'object') {
value = JSON.stringify(value);
}
if(persistent) {
key = '@' + key;
}
if(_counter.lastKey != key) {
_counter.lastKey = key;
_counter.count = 1;
}
window.localStorage.setItem(key, value);
}
catch(e) {
console.error('LocalStorage', e);
if(e.name == 'NS_ERROR_DOM_QUOTA_REACHED') {
Object.keys(window.localStorage).forEach(function(key) {
if(key[0] != '@') {
this.remove(key);
}
}.bind(this));
if(_counter.count < 3) {
this.set(key, value);
}
}
}
_counter.count = 1;
}
return this;
};
var _get = function(key) {
var value = window.localStorage.getItem(key);
try {
value = JSON.parse(value);
}
catch(e) {}
return value;
};
this.get = function(key) {
if(_supported) {
if(window.localStorage.hasOwnProperty('@' + key)) {
return _get('@' + key);
}
else {
return _get(key);
}
}
return null;
};
this.remove = function(key, force) {
if(_supported) {
window.localStorage.removeItem(key);
if(force) {
window.localStorage.removeItem('@' + key);
}
}
return this;
};
this.clear = function() {
if(_supported) {
window.localStorage.clear();
}
return this;
};
});