HTML Web Storage
Web Storage lets a page save small pieces of data in the browser, so they are still there when the visitor comes back.
What is an API?
An API (Application Programming Interface) is a set of ready-made tools the browser gives to JavaScript. HTML pages use several browser APIs: Web Storage, Geolocation, Drag and Drop, and more. The next chapters show the most useful ones with short scripts.
localStorage and sessionStorage
localStorage | sessionStorage | |
|---|---|---|
| How long data lasts | Until it is deleted, even after the browser is closed | Until the tab is closed |
| Shared between tabs | Yes, for the same website | No, each tab has its own |
| Typical use | Theme choice, saved cart, language | A form being filled in one tab |
Both store data as key and value pairs, and both values are always text (strings). Each website gets its own storage, usually around 5 MB.
The Main Methods
| Code | What it does |
|---|---|
localStorage.setItem("key", "value") | Saves a value |
localStorage.getItem("key") | Reads a value, or null if it is not there |
localStorage.removeItem("key") | Deletes one value |
localStorage.clear() | Deletes everything for this site |
localStorage.length | How many items are stored |
The same methods work on sessionStorage.
Is Storage Available?
Storage can be switched off: in private windows on some browsers, when the user blocks site data, or inside locked-down frames. Our Try it editor is one of these frames, for safety. A careful page checks first with try...catch:
Example
<!DOCTYPE html>
<html>
<body>
<p id="out"></p>
<script>
let message;
try {
localStorage.setItem("test", "1");
localStorage.removeItem("test");
message = "Web Storage works here.";
} catch (error) {
message = "Web Storage is blocked here: " + error.name;
}
document.getElementById("out").innerHTML = message;
</script>
</body>
</html>Try it Yourself »In the Try it editor this example says storage is blocked. To run the examples below, save the code as an .html file and open it in your browser, as shown in the HTML Editors chapter.
Remember the Visitor's Name
Type your name and click Save. Then reload the page: the name is still there.
Example
<!DOCTYPE html>
<html>
<body>
<h2 id="greeting">Hello, guest!</h2>
<input type="text" id="nameBox" placeholder="Your name">
<button onclick="saveName()">Save</button>
<button onclick="forget()">Forget me</button>
<script>
function show() {
const name = localStorage.getItem("visitorName");
document.getElementById("greeting").innerHTML =
name ? "Welcome back, " + name + "!" : "Hello, guest!";
}
function saveName() {
const name = document.getElementById("nameBox").value;
localStorage.setItem("visitorName", name);
show();
}
function forget() {
localStorage.removeItem("visitorName");
show();
}
show();
</script>
</body>
</html>A Visit Counter with sessionStorage
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="count()">Click me</button>
<p id="out">You have not clicked yet.</p>
<script>
function count() {
let clicks = Number(sessionStorage.getItem("clicks")) || 0;
clicks = clicks + 1;
sessionStorage.setItem("clicks", clicks);
document.getElementById("out").innerHTML = "You clicked " + clicks + " times in this tab.";
}
</script>
</body>
</html>Because storage keeps text only, Number(...) turns the saved text back into a number. || 0 uses 0 when nothing is saved yet.
Storing Objects and Lists with JSON
To save an object or an array, turn it into text with JSON.stringify(), and back into an object with JSON.parse().
Example
<!DOCTYPE html>
<html>
<body>
<button onclick="addItem('Keyboard', 1500)">Add keyboard (Rs 1500)</button>
<button onclick="addItem('Mouse', 800)">Add mouse (Rs 800)</button>
<button onclick="emptyCart()">Empty cart</button>
<p id="cart"></p>
<script>
function getCart() {
return JSON.parse(localStorage.getItem("cart")) || [];
}
function addItem(name, price) {
const cart = getCart();
cart.push({ name: name, price: price });
localStorage.setItem("cart", JSON.stringify(cart));
showCart();
}
function emptyCart() {
localStorage.removeItem("cart");
showCart();
}
function showCart() {
const cart = getCart();
let total = 0;
for (const item of cart) total += item.price;
document.getElementById("cart").innerHTML =
cart.length + " items, total Rs " + total;
}
showCart();
</script>
</body>
</html>2 items, total Rs 2300
(The output above is after clicking each button once.)
Seeing Stored Data
Open the browser's developer tools (F12), go to the Application tab (in Chrome or Edge) or Storage tab (in Firefox), and open Local Storage. You can see, edit and delete every saved key there.
Important Rules
- Never store passwords, card numbers or other secrets. Any script on the page can read Web Storage.
- Storage belongs to one browser on one device. If Ali uses his phone and then his laptop, they have different data.
- Users can clear it at any time, so the page must still work when the data is missing.
- Keep it small. For large data, websites use a server database or the browser's IndexedDB.
Web Storage is perfect for preferences such as dark mode or a chosen language. Anything important must also be saved on the server.
Exercise
Exercise
You want a value to stay saved after the visitor closes and reopens the browser. Which should you use?
