session-storage.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  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. /**
  6. * Catch, log and otherwise ignore errors.
  7. *
  8. * @param {function} fn sessionStorage function to call
  9. * @param {string?} key Key passed to the sessionStorage function (if any)
  10. * @param {any?} value Value passed to the sessionStorage function (if any)
  11. */
  12. const callSafe = function (fn, key, value) {
  13. try {
  14. return fn(key, value)
  15. } catch (e) {
  16. console.error('sessionStorage exception', e)
  17. return null
  18. }
  19. }
  20. const getItem = function (key) {
  21. return JSON.parse(sessionStorage.getItem(key))
  22. }
  23. const setItem = function (key, value) {
  24. sessionStorage.setItem(key, JSON.stringify(value))
  25. }
  26. const clear = function () {
  27. sessionStorage.clear()
  28. }
  29. const removeItem = function (key) {
  30. return sessionStorage.removeItem(key)
  31. }
  32. const customSessionStorage = {
  33. getItem: key => callSafe(getItem, key),
  34. setItem: (key, value) => callSafe(setItem, key, value),
  35. clear: () => callSafe(clear),
  36. removeItem: key => callSafe(removeItem, key),
  37. }
  38. export default customSessionStorage