How to Use Session Storage API in JavaScript

In this short tip post, we will learn how to use session storage API in JavaScript.

Objective

We need to store some temporary information in the browser which should be erased when the browser/tab is closed.

Approach

We can use session storage API of the browser to store our information. We can access session storage using JavaScript.

Session storage stores the information in a key and value format. It stores only strings, so the conversion of any other data format is a programmer responsibility.

Code

Here is the code.

HTML

<input type='button' value='click me to save data in session storage' onClick='saveData()'>

JavaScript

function saveData() {
  if (typeof(Storage) !== "undefined") {
    sessionStorage.setItem('name','Shahid');
    sessionStorage.setItem('city','Mumbai');
    sessionStorage.setItem('country','India');
    alert('data added in session storage');
  } else {
    alert('session storage not supported');
  }
}

Check out the codepen for the live demo.

See the Pen
session storage
by Shahid Shaikh (@codeforgeek)
on CodePen.

In order to check the session storage values, open the chrome developer tool and go to the Applications menu to check the value.

how to use session storage api in javascript

Pankaj Kumar
Pankaj Kumar
Articles: 207