HTML Webstorage Tutorial

Web Storage is a feature in HTML5 that allows you to store data locally in a user's web browser.

There are two types of web storage: Local Storage and Session Storage.

Local Storage

  1. Local Storage stores data without an expiration date.
  2. Data will remain even after the browser is closed.

Storing Data in Local Storage

// Store data
localStorage.setItem("username", "John");

// Store numbers or objects as JSON
localStorage.setItem("score", 100);

// Store an array as JSON
const colors = ["red", "green", "blue"];
localStorage.setItem("colors", JSON.stringify(colors));

Retrieving Data from Local Storage

// Retrieve data
const username = localStorage.getItem("username");
const score = localStorage.getItem("score");
const colorsArray = JSON.parse(localStorage.getItem("colors"));

Session Storage

  1. Session Storage stores data only for the duration of a page session. Data is cleared when the page is closed.

Storing Data in Session Storage

// Store data
sessionStorage.setItem("tempData", "This data will be cleared when the page is closed");

Retrieving Data from Session Storage

// Retrieve data
const tempData = sessionStorage.getItem("tempData");

Removing Data

  1. To remove data from either Local Storage or Session Storage, use the removeItem method.
localStorage.removeItem("username");

To clear all data in Local Storage, use.

localStorage.clear();

Checking for Support

  1. Before using web storage, check if it's supported by the browser
if (typeof(Storage) !== "undefined") {
  // Web storage is supported.
} else {
  // Web storage is not supported.
  alert("Web storage is not supported in this browser.");
}

Handling Storage Events

  1. You can listen for storage events, such as when data changes in another tab, using the storage event.
  2. This event is triggered on other windows or tabs from the same origin.
window.addEventListener("storage", function(event) {
  // Handle the storage event here
});