session-storage.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /**
  2. * sessionStorage can throw browser exceptions, for example if it is full.
  3. * We don't use sessionStorage for anything critical, so in that case just fail gracefully.
  4. */
  5. import { debugConsole } from '@/utils/debugging'
  6. /**
  7. * Catch, log and otherwise ignore errors.
  8. *
  9. * @param {function} fn sessionStorage function to call
  10. * @param {string?} key Key passed to the sessionStorage function (if any)
  11. * @param {any?} value Value passed to the sessionStorage function (if any)
  12. */
  13. const callSafe = function (fn, key, value) {
  14. try {
  15. return fn(key, value)
  16. } catch (e) {
  17. debugConsole.error('sessionStorage exception', e)
  18. return null
  19. }
  20. }
  21. const getItem = function (key) {
  22. return JSON.parse(sessionStorage.getItem(key))
  23. }
  24. const setItem = function (key, value) {
  25. sessionStorage.setItem(key, JSON.stringify(value))
  26. }
  27. const clear = function () {
  28. sessionStorage.clear()
  29. }
  30. const removeItem = function (key) {
  31. return sessionStorage.removeItem(key)
  32. }
  33. const customSessionStorage = {
  34. getItem: key => callSafe(getItem, key),
  35. setItem: (key, value) => callSafe(setItem, key, value),
  36. clear: () => callSafe(clear),
  37. removeItem: key => callSafe(removeItem, key),
  38. }
  39. export default customSessionStorage