Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to use HTML5 localStorage and sessionStorage?
HTML5 introduced two powerful mechanisms for storing data on the client side − localStorage and sessionStorage. These storage options overcome the limitations of traditional HTTP cookies by providing larger storage capacity and reducing unnecessary data transmission with every HTTP request.
The key advantages of HTML5 web storage over cookies include −
-
No automatic transmission − Storage data is not sent with every HTTP request, improving web application performance.
-
Larger storage capacity − Web storage can hold approximately 5-10 MB of data per domain, compared to cookies' 4 KB limit.
-
Better performance − Data stays on the client side, reducing server load and network traffic.
Storage Types
HTML5 provides two types of web storage that handle different scenarios −
-
sessionStorage − Data persists only for the duration of the page session (until the browser tab is closed).
-
localStorage − Data persists across browser sessions and remains available until explicitly cleared.
Syntax
Both storage mechanisms use the same methods for storing and retrieving data −
// Storing data
localStorage.setItem("key", "value");
sessionStorage.setItem("key", "value");
// Retrieving data
var value = localStorage.getItem("key");
var value = sessionStorage.getItem("key");
// Removing data
localStorage.removeItem("key");
sessionStorage.removeItem("key");
// Clearing all data
localStorage.clear();
sessionStorage.clear();
You can also use shorthand notation −
localStorage.key = "value"; // Set var value = localStorage.key; // Get delete localStorage.key; // Remove
Session Storage
The sessionStorage is designed for scenarios where the user carries out a single transaction but may have multiple transactions in different windows simultaneously. Data stored in sessionStorage is isolated to the specific browser tab and is automatically cleared when the tab is closed.
Example − Session Storage Counter
Following example demonstrates sessionStorage by creating a hit counter that persists only during the browser session −
<!DOCTYPE html>
<html>
<head>
<title>sessionStorage Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Session Storage Demo</h2>
<p id="result"></p>
<button onclick="incrementHits()">Increment Hits</button>
<button onclick="clearSession()">Clear Session</button>
<script>
function incrementHits() {
if (sessionStorage.hits) {
sessionStorage.hits = Number(sessionStorage.hits) + 1;
} else {
sessionStorage.hits = 1;
}
displayHits();
}
function displayHits() {
document.getElementById("result").innerHTML =
"Total Hits: " + (sessionStorage.hits || 0);
}
function clearSession() {
sessionStorage.clear();
displayHits();
}
// Display current hits on page load
window.onload = displayHits;
</script>
<div style="margin-top: 20px; padding: 10px; background-color: #f0f0f0;">
<p><strong>Instructions:</strong></p>
<p>1. Click "Increment Hits" to increase the counter</p>
<p>2. Refresh the page - the counter persists</p>
<p>3. Close the tab and reopen - the counter resets to 0</p>
</div>
</body>
</html>
The output shows a counter that increments with each click and persists during page refreshes but resets when the browser tab is closed −
Session Storage Demo Total Hits: 0 [Increment Hits] [Clear Session] Instructions: 1. Click "Increment Hits" to increase the counter 2. Refresh the page - the counter persists 3. Close the tab and reopen - the counter resets to 0
Local Storage
The localStorage is designed for storage that spans multiple windows and lasts beyond the current session. Web applications can store megabytes of user data, such as user preferences, application state, or cached content, on the client side for improved performance.
Key characteristics of localStorage −
-
Data persists until explicitly removed by the application or user
-
Data is shared across all tabs and windows of the same domain
-
Storage limit is typically 5-10 MB per domain
-
Data survives browser restarts and system reboots
Example − Local Storage Counter
Following example shows how localStorage maintains data across browser sessions −
<!DOCTYPE html>
<html>
<head>
<title>localStorage Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Local Storage Demo</h2>
<p id="result"></p>
<button onclick="incrementHits()">Increment Hits</button>
<button onclick="clearLocal()">Clear Local Storage</button>
<button onclick="showStorageInfo()">Show Storage Info</button>
<p id="storageInfo"></p>
<script>
function incrementHits() {
if (localStorage.hits) {
localStorage.hits = Number(localStorage.hits) + 1;
} else {
localStorage.hits = 1;
}
displayHits();
}
function displayHits() {
document.getElementById("result").innerHTML =
"Total Hits: " + (localStorage.hits || 0);
}
function clearLocal() {
localStorage.clear();
displayHits();
document.getElementById("storageInfo").innerHTML = "";
}
function showStorageInfo() {
var info = "Storage items: " + localStorage.length + "<br>";
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
info += key + " = " + localStorage.getItem(key) + "<br>";
}
document.getElementById("storageInfo").innerHTML = info;
}
// Display current hits on page load
window.onload = function() {
displayHits();
// Store additional demo data
localStorage.setItem("username", "TutorialsPoint_User");
localStorage.setItem("theme", "dark");
};
</script>
<div style="margin-top: 20px; padding: 10px; background-color: #f0f0f0;">
<p><strong>Instructions:</strong></p>
<p>1. Click "Increment Hits" to increase the counter</p>
<p>2. Refresh the page - the counter persists</p>
<p>3. Close the browser and reopen - the counter still persists</p>
<p>4. Click "Show Storage Info" to see all stored data</p>
</div>
</body>
</html>
The output demonstrates persistent storage that survives browser restarts −
Local Storage Demo Total Hits: 0 [Increment Hits] [Clear Local Storage] [Show Storage Info] Instructions: 1. Click "Increment Hits" to increase the counter 2. Refresh the page - the counter persists 3. Close the browser and reopen - the counter still persists 4. Click "Show Storage Info" to see all stored data
Working with JSON Data
Web storage can only store strings, but you can store complex objects by converting them to JSON −
Example − Storing Objects
<!DOCTYPE html>
<html>
<head>
<title>JSON Storage Example</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>JSON Object Storage</h2>
<button onclick="saveUser()">Save User Data</button>
<button onclick="loadUser()">Load User Data</button>
<button onclick="clearData()">Clear Data</button>
<div id="output" style="margin-top: 20px; padding: 10px; background-color: #f9f9f9;"></div>
<script>
function saveUser() {
var user = {
name: "John Doe",
email: "john@example.com",
preferences: {
theme: "dark",
language: "en"
},
loginCount: 5
};
localStorage.setItem("userData", JSON.stringify(user));
document.getElementById("output").innerHTML =
"<p style='color: green;'>User data saved successfully!</p>";
}
function loadUser() {
var userData = localStorage.getItem("userData");
if (userData) {
var user = JSON.parse(userData);
var output = "<h3>Loaded User Data:</h3>";
output += "<p><strong>Name:</strong> " + user.name + "</p>";
output += "<p><strong>Email:</strong> " + user.email + "</p>";
output += "<p><strong>Theme:</strong> " + user.preferences.theme + "</p>";
output += "<p><strong>Language:</strong> " + user.preferences.language + "</p>";
output += "<p><strong>Login Count:</strong> " + user.loginCount + "</p>";
document.getElementById("output").innerHTML = output;
} else {
document.getElementById("output").innerHTML =
"<p style='color: red;'>No user data found!</p>";
}
}
function clearData() {
localStorage.removeItem("userData");
document.getElementById("output").innerHTML =
"<p style='color: orange;'>User data cleared!</p>";
}
</script>
</body>
</html>
This example shows how to store and retrieve complex JavaScript objects using JSON serialization.
Storage Event Handling
The storage event is fired when localStorage is modified in another tab or window of
