Accessing local storage can cause exceptions if disabled

This is part of the Semicolon&Sons Code Diary - consisting of lessons learned on the job. You're in the web-development category.

Last Updated: 2024-04-17

Accessing session or local storage in JavaScript may lead to exceptions when the user has disabled either of them.

sessionStorage.setItem("project_s", this.textContent) // can blow up!

This should be transformed into

try {
  sessionStorage.setItem("project_s", this.textContent)
} catch(e) { 
  console.warn("Unable to set preferences in sessionStorage")
}