carry forward session storage one page to another page in javascript

Carry Forward Session Storage One Page to Another Page in JavaScript

Sometimes, we need to store some data that we want to use in different pages of a website. One way to do this is by using session storage. Session storage allows us to store key-value pairs in the browser's memory, which can be accessed across different pages of a website.

Setting Session Storage

We can set a value in session storage using the setItem() method. Let's say we want to store the user's name in session storage.


 sessionStorage.setItem('name', 'Raju');

This will set the value of 'name' key as 'Raju' in the session storage.

Getting Session Storage

We can get the value of a key from session storage using the getItem() method. Let's say we want to get the user's name from session storage.


 var name = sessionStorage.getItem('name');
 console.log(name); // Output: Raju

This will retrieve the value of 'name' key from the session storage and store it in the 'name' variable.

Carrying Forward Session Storage

Now, let's say we want to carry forward the user's name from one page to another page. We can do this by setting the value in session storage on the first page, and then getting the value from session storage on the second page.

On the first page, we can set the value of 'name' key in session storage:


 sessionStorage.setItem('name', 'Raju');

On the second page, we can get the value of 'name' key from session storage:


 var name = sessionStorage.getItem('name');
 console.log(name); // Output: Raju

This will retrieve the value of 'name' key from session storage and store it in the 'name' variable on the second page.

We can also clear a specific key from session storage using the removeItem() method:


 sessionStorage.removeItem('name');

This will remove the 'name' key from session storage.

Alternatively, we can clear all keys from session storage using the clear() method:


 sessionStorage.clear();

This will clear all keys from session storage.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe