Skip to content

Instantly share code, notes, and snippets.

@guanzo
Last active April 30, 2020 11:02
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 guanzo/571a0026ba90454fa9a6fde77f7701b6 to your computer and use it in GitHub Desktop.
Save guanzo/571a0026ba90454fa9a6fde77f7701b6 to your computer and use it in GitHub Desktop.
localStorage API that swallows errors.
// https://developer.mozilla.org/en-US/docs/Web/API/Storage
// Wraps all methods in a try/catch.
// Useful for non-critical storage, and when swallowing errors is acceptable.
// Reasons why localStorage might fail:
// * Simply referencing window.localStorage when in a 3rd party iframe. (brave & safari)
// * localStorage can be null
// * Storage quota exceeded
const methods = ['key', 'getItem', 'setItem', 'removeItem', 'clear']
const idgafLocalStorage = {}
for (const m of methods) {
idgafLocalStorage[m] = (...args) => {
try {
return window.localStorage[m](...args)
} catch {}
}
}
export default idgafLocalStorage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment