learn2kode.in

HTML Web Storage

HTML Web Storage provides a way for websites to store data in the user’s browser securely and efficiently. It is more powerful than cookies because it offers larger storage capacity, is faster, and does not send data to the server with every request.

Web Storage has two main mechanisms:

1. Local Storage

Local Storage stores data permanently in the browser until it’s manually cleared by the user or through code.

Key Features

Common Methods

Method Description
localStorage.setItem(key, value) Stores a value
localStorage.getItem(key) Retrieves a value
localStorage.removeItem(key) Removes a specific item
localStorage.clear() Clears all stored data

Example

<script>
localStorage.setItem("username", "John");
document.write(localStorage.getItem("username"));
</script>

2. Session Storage

Session Storage stores data temporarily for a single browser session.

Key Features

Session Storage Methods

Method Description
sessionStorage.setItem(key, value) Stores a value
sessionStorage.getItem(key) Retrieves a value
sessionStorage.removeItem(key) Removes one item
sessionStorage.clear() Clears all data

Example

<script>
sessionStorage.setItem("color", "blue");
alert(sessionStorage.getItem("color"));
</script>

Local Storage vs Session Storage

Feature Local Storage Session Storage
Lifetime Permanent Until tab is closed
Capacity 5–10 MB 5 MB
Scope All tabs from same origin Only the current tab

Benefits of Web Storage

Use Cases