Last active
October 3, 2021 17:12
-
-
Save utilmind/90eab5308a2fe936a1deeed31a892160 to your computer and use it in GitHub Desktop.
lStorage & sStorage -- replacements for localStorage and sessionStorage
This file contains hidden or 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
(function(window) { | |
// lStorage & sStorage -- replacements for localStorage and sessionStorage | |
// =========================== | |
// Brave browser (withe default settings) is blocking access to localStorage. | |
// This is sucks, but in most cases we can live without stored data. Just don't let exception prevent execution of our code. | |
// =========================== | |
/* IDEA: | |
* We have replacement for any storage, that lives only during current instance. (Even less than session.) | |
* We use this replacement only if regular storage not found. (And this is the only sense to use it.) | |
*/ | |
var data = {}, | |
tempStorage = { | |
length: 0, | |
key: function(key) { | |
return Object.keys(data)[key]; | |
}, | |
getItem: function(key) { | |
return data[key]; | |
}, | |
setItem: function(key, val, expireMin) { | |
data[key] = val; | |
this.length = data.length; | |
if (expireMin) { | |
setTimeout(function() { | |
this.removeItem(key); | |
}, expireMin * 1000); // convert seconds to milliseconds | |
} | |
}, | |
removeItem: function(key) { | |
delete data[key]; | |
this.length = data.length; | |
}, | |
clear: function() { | |
data = {}; | |
this.length = 0; | |
} | |
}, | |
lStorage, // replacement for localStorage | |
sStorage; // replacement for sessionStorage | |
try { | |
lStorage = localStorage; | |
sStorage = sessionStorage; | |
}catch(err) { | |
console.error("Storage blocked by browser."); | |
lStorage = tempStorage; | |
sStorage = tempStorage; | |
} | |
window.lStorage = lStorage; | |
window.sStorage = sStorage; | |
})(window); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment