Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Share On Stumbleupon
Contact us
Hide Buttons

Getting started with localStorage vs sessionStorage in html5

Before HTML5 appli­ca­tion data for a user has to be stored on a server. It had to be trans­ferred using cook­ies. This mech­a­nism affects the appli­ca­tion per­for­mance and secu­rity as well.

The HTML5 Stor­age API solves this secu­rity and per­for­mance related prob­lems of web appli­ca­tions by

  • Allow­ing the appli­ca­tion to store the data locally on a user’s machine so an appli­ca­tion does not have to trans­fer sen­si­tive data over the network
  • Allow­ing quick access to locally stored data which improves the application’s performance

The HTML5 web stor­age api comes with the fol­low­ing two stor­age options:

Ses­sion­Stor­age

Per­sists a stor­age area for the dura­tion of the page ses­sion.
Use it when you need to store some data tem­porar­ily. A page ses­sion imple­men­ta­tion might be dif­fer­ent based on browser ven­dor and its version.

Ses­sion­Stor­age data is available

  • As long as the browser is open, includ­ing page reloads and restores
  • It gets deleted the time when the tab/window who cre­ated the ses­sion is closed

Local­Stor­age

Per­sists the data until the user explic­itly deletes the data.
Use it when you need to store some data for the long term.

Local­Stor­age data is available

  • Even after the browser is closed and reopened

The fol­low­ing exam­ple shows the native get­ter and set­ter meth­ods for local­Stor­age. Sim­i­lar meth­ods do exist for ses­sion­Stor­age as well.

Chrome dev tools

Both of this stor­age can be found under the Resources in chrome dev tools.

skitch

Scope of local­Stor­age and sessionStorage

  • Scoped to doc­u­ment origin
  • Scoped by browser ven­dors, e.g. Chrome can not access the local­Stor­age or ses­sion­Stor­age of Inter­net Explorer.

Exam­ple 1:

The fol­low­ing video illus­trates the life­time dif­fer­ences of these stor­age APIs on a site!

Exam­ple 2:

The local­Stor­age exam­ple in the link below shows that your choice of font type, back­ground color and image will be remem­bered even after you close and reopen the tab.

local­Stor­age Demo

You may also like...