Be the first user to complete this post

  • 0
Add to List

Getting started with localStorage vs sessionStorage in html5

Before HTML5 application data for a user has to be stored on a server. It had to be transferred using cookies. This mechanism affects the application performance and security as well. The HTML5 Storage API solves this security and performance related problems of web applications by

  • Allowing the application to store the data locally on a user’s machine so an application does not have to transfer sensitive data over the network
  • Allowing quick access to locally stored data which improves the application’s performance
The HTML5 web storage api comes with the following two storage options:

SessionStorage

Persists a storage area for the duration of the page session. Use it when you need to store some data temporarily. A page session implementation might be different based on browser vendor and its version.
SessionStorage data is available
  • As long as the browser is open, including page reloads and restores
  • It gets deleted the time when the tab/window who created the session is closed

LocalStorage

Persists the data until the user explicitly deletes the data. Use it when you need to store some data for the long term.
LocalStorage data is available
  • Even after the browser is closed and reopened
The following example shows the native getter and setter methods for localStorage. Similar methods do exist for sessionStorage as well. [wpgist id="badfae13772f3d5ecf64" file="localStorage.js"]

Chrome dev tools

Both of this storage can be found under the Resources in chrome dev tools. skitch

Scope of localStorage and sessionStorage

  • Scoped to document origin
  • Scoped by browser vendors, e.g. Chrome can not access the localStorage or sessionStorage of Internet Explorer.

Example 1:

The following video illustrates the lifetime differences of these storage APIs on a site!
[youtube https://www.youtube.com/watch?v=klLMeL7I4O0]

Example 2:

The localStorage example in the link below shows that your choice of font type, background color and image will be remembered even after you close and reopen the tab. localStorage Demo



Also Read:

  1. es6 iterators and iterables - creating custom iterators
  2. Two column layout in css
  3. Parse html response with fetch API
  4. Passing arguments from one function to another in javascript
  5. nodejs: generate uuid / guid