Skip to content

Instantly share code, notes, and snippets.

@0liver
Last active July 19, 2021 22:22
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 0liver/2ce44676110b537a945b61b99fb9734d to your computer and use it in GitHub Desktop.
Save 0liver/2ce44676110b537a945b61b99fb9734d to your computer and use it in GitHub Desktop.
A safe localStorage access wrapper
(function(n) {
function t(n) {
function i() {
try {
var t = "__some_random_key_we_are_not_going_to_use__";
return n().setItem(t, t),
n().removeItem(t),
!0
} catch (i) {
return false;
}
}
function getItem(r) {
return (console.log("safeLocalStorage.getItem()", r),
i()) ? n().getItem(r) : t[r] || null
}
function setItem(r, u) {
console.log("safeLocalStorage.setItem()", r, u);
i() ? n().setItem(r, u) : t[r] = u
}
function removeItem(r) {
i() ? n().removeItem(r) : delete t[r]
}
function clear() {
i() ? n().clear() : t = {}
}
function key(r) {
return i() ? n().key(r) : Object.keys(t)[r] || null
}
var t = {};
return {
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
key: key
}
}
n.safeLocalStorage = new t(function() {
return n.localStorage
})
}
)(window);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment