Web storage (DOM storage)

Objectives

  • Discuss advantages of web storage over use of cookies
  • Discuss and use localStorage
  • Discuss and use sessionStorage

Overview

  • Web storage provides a lot more storage capacity than cookies (5MB-10MB vs. 4K)
  • Web storage is completely client-side - no information is automatically sent via headers to the server
  • Web storage is divided into sessionStorage and localStorage
  • sessionStorage is limited to a particular page in a particular window while the browser is running
  • localStorage is limited to a particular domain and persists even after a browser is shut down

Using sessionStorage and localStorage

  • Values are saved as key:value pairs
  • Saving the value 42 with the key num: sessionStorage.setItem('num', '42');
  • Saving the value 42 with the key num: localStorage.setItem('num', '42');
  • Retrieving the value for key num: sessionStorage.getItem('num');
  • Retrieving the value for key num: localStorage.getItem('num');
  • Objects can be stored using JSON to turn the object into a string: JSON.stringify({'width':5,'height':10})
  • Retrieved JSON strings can be converted back to objects using JSON.parse(JSON_String)
  • SessionStorage and localStorage have a length attribute to tell you how many key:value pairs are stored
  • Retrieving a specific key by index number: sessionStorage.key(2)
  • Retrieving a specific key by index number: localStorage.key(2)
  • Removing the key:value pair where key is num: sessionStorage.removeItem('num')
  • Removing the key:value pair where key is num: localStorage.removeItem('num')
  • Clearing all key:value pairs: sessionStorage.clear()
  • Clearing all key:value pairs: localStorage.clear()

Links to storage examples

See the live storage demonstration. This example allows you to store and display a name value in either local or session storage.

See the additional storage demonstration. This example allows you to store and display multiple key/value pairs of your choosing.