Last active
July 19, 2021 22:22
-
-
Save 0liver/2ce44676110b537a945b61b99fb9734d to your computer and use it in GitHub Desktop.
A safe localStorage access wrapper
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(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