Breaking News

HTML WEB STORAGE API

The HTML Web Storage API is a browser feature that allows web applications to store data in a user's browser as key-value pairs. Unlike cookies, Web Storage can store much more data and is not sent with every HTTP request.

There are two types of Web Storage:

Feature

 localStorage

 sessionStorage

Lifetime  Permanent (until deleted)  Temporary (until browser tab is closed)
Shared Across Tabs  Yes (same origin)  No (only current tab)
Storage Limit  About 5–10 MB  About 5–10 MB
Accessible By  JavaScript  JavaScript

Common Methods

1. Store Data

localStorage.setItem("username", "Ali");
sessionStorage.setItem("username", "Ali");

2. Retrieve Data

let user = localStorage.getItem("username");
console.log(user);

3. Update Data

localStorage.setItem("username", "Ahmed");

4. Remove Data

localStorage.removeItem("username");

5. Clear All Data

localStorage.clear();

Example

<!DOCTYPE html>
<html>
<head>
    <title>Web Storage Example</title>
</head>
<body>

<button onclick="saveData()">Save</button>
<button onclick="showData()">Show</button>

<script>
function saveData() {
    localStorage.setItem("name", "John");
}

function showData() {
    alert(localStorage.getItem("name"));
}
</script>

</body>
</html>

Storing Objects

Since Web Storage only stores strings, convert objects to JSON.

Store an Object

const student = {
    name: "Ali",
    age: 20,
    city: "Lahore"
};

localStorage.setItem("student", JSON.stringify(student));

Retrieve an Object

const data = JSON.parse(localStorage.getItem("student"));
console.log(data.name);

Advantages

  • Easy to use.
  • Stores more data than cookies.
  • Data is not sent to the server with every request.
  • Useful for saving user preferences, themes, shopping carts, and form data.

Limitations

  • Stores only string data (objects must be converted using JSON.stringify()).
  • Not suitable for sensitive information because JavaScript running on the page can access it.
  • Storage size is limited (typically 5–10 MB depending on the browser).

When to Use

  • Use localStorage for persistent data such as:
    • Dark/light theme preference
    • Language settings
    • Remembering user preferences
  • Use sessionStorage for temporary data such as:
    • Multi-step form data
    • Temporary login session information (non-sensitive)
    • Data needed only while a tab is open

In summary, the HTML Web Storage API provides two storage mechanisms:

  • localStorage: persists until explicitly removed.
  • sessionStorage: lasts only for the current browser tab session. 

No comments