Smal SEO Tool

HTML Web Storage

Web storage is more secure and faster than cookies, allowing web applications to store data locally within the user's browser.

localStorage and sessionStorage

The Web Storage API provides two mechanisms for storing data on the client-side:

  • localStorage: Stores data with no expiration date. The data will not be deleted when the browser is closed and will be available the next day, week, or year.
  • sessionStorage: Stores data for one session only. The data is deleted when the browser tab is closed.

Example: Using localStorage

html
<script>
// Set Item
localStorage.setItem("lastname", "Smith");

// Get Item
document.getElementById("demo").innerHTML = localStorage.getItem("lastname");

// Remove Item
// localStorage.removeItem("lastname");
</script>

Example: Using sessionStorage

This example counts the number of times a user has clicked a button in the current session.

html
<script>
if (sessionStorage.clickcount) {
  sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1;
} else {
  sessionStorage.clickcount = 1;
}
document.getElementById("demo").innerHTML = "You have clicked the button " +
sessionStorage.clickcount + " time(s) in this session.";
</script>

Test Yourself with an Exercise

Which Web Storage object stores data with no expiration date?