HTML Window sessionStorage Property


The HTML Window sessionStorage property allow us to store key/value pairs data in a web browser only for one session that means the data is deleted when the browser tab is closed.

Syntax

Following is the syntax −

window.sessionStorage

Let us see an example of HTML Window sessionStorage Property −

Example

 Live Demo

<!DOCTYPE html>
<html>
<style>
   body {
      color: #000;
      height: 100vh;
      background-color: #8BC6EC;
      background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat;
      text-align: center;
   }
   .btn {
      background: #db133a;
      border: none;
      height: 2rem;
      border-radius: 2px;
      width: 30%;
      display: block;
      color: #fff;
      outline: none;
      cursor: pointer;
      margin: 1rem auto;
   }
   .show{
      font-size:1.2rem;
   }
</style>
<body>
<h1>HTML Window sessionStorage Property Demo</h1>
<button onclick="store()" class="btn">Store 'John Smith' Name to sessionStorage</button>
<button onclick="display()" class="btn">Display sessionStorage stored value</button>
<div class="show"></div>
<script>
   function store(){
      sessionStorage.setItem('firstName','John');
      sessionStorage.setItem('lastName','Smith');
      document.querySelector('.show').innerHTML='Name store successfully';
   }
   function display(){
      var firstName=sessionStorage.getItem('firstName');
      var lastName=sessionStorage.getItem('lastName');
      document.querySelector('.show').innerHTML='Name stored in sessionStorage is: '+ firstName +' '+lastName;
   }
</script>
</body>
</html>

Output

Click on “Store ‘John Smith’ Name to sessionStorage” button to store name to sessionStorage:

Now click on “Display sessionStorage stored value” button to display the stored value −

Now you can also open session storage in your dev tools to understand how it works −

Updated on: 01-Oct-2019

221 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements