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 store a name permanently using HTML5 Local Storage?
The Local Storage is designed for storage that spans multiple windows and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user's mailbox, on the client side for performance reasons.
HTML5 localStorage saves string data in the browser and lasts beyond the current session. localStorage stores the data with no expiration, whereas sessionStorage is limited to the session only. When the browser is closed, the session is lost but localStorage data persists.
The data won't get deleted when the browser is closed. Here, we will save and retrieve a name permanently using localStorage.
Syntax
Following is the syntax to store data in localStorage −
localStorage.setItem("key", "value");
Following is the syntax to retrieve data from localStorage −
localStorage.getItem("key");
Following is the syntax to remove a specific item from localStorage −
localStorage.removeItem("key");
Following is the syntax to clear all data from localStorage −
localStorage.clear();
Basic Example − Storing and Retrieving a Name
Following example demonstrates how to store a name permanently using HTML5 local storage −
<!DOCTYPE html>
<html>
<head>
<title>HTML5 LocalStorage - Store Name</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>Store Name Permanently</h2>
<div id="demo"></div>
<script>
if (typeof(Storage) !== "undefined") {
localStorage.setItem("name", "John");
document.getElementById("demo").innerHTML =
"Stored name: " + localStorage.getItem("name");
} else {
document.getElementById("demo").innerHTML =
"The browser does not support Web Storage";
}
</script>
</body>
</html>
The output of the above code is −
Store Name Permanently Stored name: John
Interactive Example − User Input with LocalStorage
Following example shows how to store and retrieve a user-entered name using localStorage −
<!DOCTYPE html>
<html>
<head>
<title>Interactive Name Storage</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>LocalStorage Name Manager</h2>
<input type="text" id="nameInput" placeholder="Enter your name">
<button onclick="storeName()">Store Name</button>
<button onclick="retrieveName()">Retrieve Name</button>
<button onclick="clearName()">Clear Name</button>
<p id="result"></p>
<script>
// Check if localStorage is supported
function checkStorage() {
if (typeof(Storage) === "undefined") {
document.getElementById("result").innerHTML =
"LocalStorage is not supported by this browser.";
return false;
}
return true;
}
function storeName() {
if (!checkStorage()) return;
var name = document.getElementById("nameInput").value;
if (name.trim() === "") {
document.getElementById("result").innerHTML = "Please enter a name!";
return;
}
localStorage.setItem("userName", name);
document.getElementById("result").innerHTML =
"Name '" + name + "' stored successfully!";
}
function retrieveName() {
if (!checkStorage()) return;
var storedName = localStorage.getItem("userName");
if (storedName) {
document.getElementById("result").innerHTML =
"Retrieved name: " + storedName;
} else {
document.getElementById("result").innerHTML =
"No name found in storage.";
}
}
function clearName() {
if (!checkStorage()) return;
localStorage.removeItem("userName");
document.getElementById("result").innerHTML =
"Name cleared from storage.";
}
// Load stored name on page load
window.onload = function() {
if (checkStorage()) {
var storedName = localStorage.getItem("userName");
if (storedName) {
document.getElementById("nameInput").value = storedName;
document.getElementById("result").innerHTML =
"Found stored name: " + storedName;
}
}
}
</script>
</body>
</html>
This example provides a complete interface to store, retrieve, and clear names from localStorage. The stored name persists across browser sessions.
Checking LocalStorage Content
Following example demonstrates how to check what data is stored in localStorage −
<!DOCTYPE html>
<html>
<head>
<title>LocalStorage Content Viewer</title>
</head>
<body style="font-family: Arial, sans-serif; padding: 20px;">
<h2>LocalStorage Content</h2>
<button onclick="showStorageContent()">Show All Storage</button>
<button onclick="addSampleData()">Add Sample Data</button>
<div id="storageList"></div>
<script>
function showStorageContent() {
var output = "<h3>Current LocalStorage Contents:</h3>";
if (localStorage.length === 0) {
output += "<p>No data stored in localStorage.</p>";
} else {
output += "<ul>";
for (var i = 0; i < localStorage.length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
output += "<li><strong>" + key + ":</strong> " + value + "</li>";
}
output += "</ul>";
output += "<p>Total items: " + localStorage.length + "</p>";
}
document.getElementById("storageList").innerHTML = output;
}
function addSampleData() {
localStorage.setItem("firstName", "Alice");
localStorage.setItem("lastName", "Johnson");
localStorage.setItem("email", "alice@example.com");
document.getElementById("storageList").innerHTML =
"<p style='color: green;'>Sample data added! Click 'Show All Storage' to view.</p>";
}
</script>
</body>
</html>
This example shows all key-value pairs currently stored in localStorage and provides functionality to add sample data for testing.
Key Points
Following are the important points about HTML5 localStorage −
-
Persistence − Data stored in localStorage remains available until explicitly removed by the user or application.
-
Storage Limit − Most browsers provide 5-10MB of storage space per domain.
-
String Only − localStorage can only store string data. Use
JSON.stringify()andJSON.parse()for objects. -
Synchronous API − All localStorage operations are synchronous and may block the main thread for large data.
-
Domain Specific − Data stored by one website cannot be accessed by another website.
-
Browser Support − Always check for localStorage support using
typeof(Storage) !== "undefined".
Browser Compatibility
HTML5 localStorage is supported by all modern browsers including Chrome 4+, Firefox 3.5+, Safari 4+, Internet Explorer 8+, and Opera 10.5+. For older browsers that don't support localStorage, consider using a polyfill or fallback to cookies.
Conclusion
HTML5 localStorage provides a simple way to store data permanently in the user's browser. Unlike sessionStorage, data in localStorage persists across browser sessions, making it ideal for storing user preferences, settings, or any data that should remain available between visits. Always check for browser support and handle storage errors appropriately.
