Session Storage

Session Storage

An overview on Session Storage.

Β·

2 min read

Table of contents

The SessionStorage is used less often than the LocalStorage and all the properties and methods are the same as that of LocalStorage.

Session Storage Capacity is 5 MB

The difference is that while data in localStorage doesn't expire, data in sessionStorage is cleared when the page session ends.

When the webpage or document is loaded in the tab in the browser a unique page session gets created and assigned to a particular tab. That page session is valid only for a particular tab.

A page session lasts as long as the tab or the browser is open and survives over page reloads and restores.

Closing a tab/window ends the session and clears objects in sessionStorage.

setItem("Key", "Value")

Methods in SessionStorage setItem("πŸ—", value) this method will set the add the data to LocalStorage.

getItem("πŸ—")

The method will help to retrieve the value with the help of keyπŸ—.

removeItem("πŸ—")

The method will remove the value which has the mentioned key and for the key which does not exist the output should be undefined.

clear()

The method will delete everything from the session storage.

sessionStorage.setItem("nameSession", "testSession");
sessionStorage.setItem("nameSession1", "testSession1");
console.log(sessionStorage.getItem("nameSession"));
console.log(sessionStorage.getItem("nameSession1"));

document.onstorage = (e) => {
  alert("updated");
  console.log(e);
};

console.log(sessionStorage.key(0));
console.log(sessionStorage.key(1));
console.log(sessionStorage.key(2));
console.log(sessionStorage.key(5));

console.log(`Removing the Session Storage with key name ${nameSession1} removed`);

sessionStorage.removeItem("nameSession1");
sessionStorage.clear();

Storage Event

Whenever the data is updated in LocalStorage and SessionStorage, storage events trigger with these properties:

  1. Key πŸ—

  2. Old Value -> Previous Value

  3. new Value -> New Value

  4. URL -> Page URL

  5. StorageArea -> Local or SessionStorage

Did you find this article valuable?

Support Moreshwar's Blogs by becoming a sponsor. Any amount is appreciated!

Β