Local Storage is the browser’s localStorage object from the Web Storage API. From a <script> in your HTML page you save string key-value pairs for the document’s origin. Data is saved across browser sessions—it remains after you close the tab or browser until you remove it or the user clears site data.
How is localStorage different from sessionStorage?
Both use the same Storage methods. localStorage has no expiration and is shared by every tab of that origin. sessionStorage lasts only for one tab’s page session and clears when that tab closes.
How is this useful in HTML pages?
Remember a dark/light theme, remember last visited section, keep a simple shopping cart on the client, or restore form defaults on return visits—without sending that data to the server on every request (unlike cookies).
When should you prefer localStorage?
Use it for small, non-sensitive preferences that should survive reloads and new visits. For large or structured offline data, use IndexedDB. For tab-only drafts, use sessionStorage.
Strings only (UTF-16).
Keys and values are strings. Integer keys are coerced to strings. Store objects with JSON.stringify / JSON.parse.
Not a vault.
Same-origin scripts (including XSS) can read localStorage. Never store passwords, tokens, or payment data there.
HTTP ≠ HTTPS storage.
http://example.com and https://example.com have separate localStorage areas. Private browsing data is cleared when the last private tab closes.
Syntax
HTML / Script Syntax
Call methods on localStorage from a script in your HTML document:
JS
localStorage.setItem("key", "value");
var data = localStorage.getItem("key"); // string or null
localStorage.removeItem("key");
localStorage.clear(); // remove all keys for this origin
localStorage.key(0); // name of key at index
localStorage.length; // number of keys
HTML
<button type="button" id="themeBtn">Toggle theme</button>
<script>
var saved = localStorage.getItem("theme");
if (saved) document.body.setAttribute("data-theme", saved);
document.getElementById("themeBtn").onclick = function () {
var next = document.body.getAttribute("data-theme") === "dark" ? "light" : "dark";
document.body.setAttribute("data-theme", next);
localStorage.setItem("theme", next);
};
</script>
Reference
Core HTML Concepts
How local storage fits into HTML pages and the browser:
Concept
Meaning
localStorage
Per-origin Storage object that persists across sessions
Origin
Scheme + host + port; storage is separate per origin
setItem / getItem
Write and read string values
removeItem / clear
Delete one key or all keys for this origin
key / length
Inspect stored keys for debugging
Shared tabs
All tabs of the origin see the same localStorage
Not in HTTP
Unlike cookies, values are not sent with page requests
sessionStorage
Tab-scoped storage that clears when the tab closes
storage event
Other tabs can react when localStorage changes (see onstorage)
localStorage vs sessionStorage
localStorage
sessionStorage
Scope
All tabs of the origin
One tab (top-level browsing context)
Lifetime
Until cleared by script or user
Until tab/window closes
Survives browser restart?
Yes
No
Best for
Theme, prefs, lasting client data
Drafts, wizards, one-visit state
Approach
How to Use Local Storage in HTML
Wire persistent storage to page load and user actions.
Add HTML controls (buttons, selects, inputs) with ids.
On save or change, call localStorage.setItem(key, value).
On page load, getItem and apply the value to the HTML (classes, attributes, form fields).
Use removeItem for one preference, or clear to wipe the origin’s store.
Serialize objects with JSON; keep payloads small (~5 MB typical limit).
Goal
Pattern
Save a string
localStorage.setItem("greeting", "Hello")
Restore on load
var v = localStorage.getItem("greeting")
Store an object
setItem("cart", JSON.stringify(obj))
Forget one key
localStorage.removeItem("greeting")
Reset all keys
localStorage.clear()
Try it
Live Preview
Save a value into this origin’s localStorage. Close the tab and return—it should still be there until you clear it.
Uses key ctf-ls-demo for this site origin. Try Save, then open another tab of this page—Load should see the same value.
localStorage status
No value saved yet.
localStorage.getItem("ctf-ls-demo") → null
Code
HTML Examples
Five patterns: save/read strings, JSON objects, remove keys, list keys, and a full HTML page demo.
Example 1 — Save and Read a String
JS
localStorage.setItem("myCat", "Tom");
var cat = localStorage.getItem("myCat");
console.log(cat); // Tom
HTML provides the UI; the script talks to localStorage.
Save writes greeting for the whole origin.
Close and reopen the browser—Retrieve still finds the value.
Remove / Clear delete one key or everything for this origin.
Edge Cases & Pitfalls
Most surprises come from origin rules, string-only values, or blocked storage.
protocol
HTTP vs HTTPS
They are different origins for storage. Data saved on http will not appear on https for the same host.
types
Storing objects raw
Non-strings are coerced. Prefer JSON so you do not get "[object Object]".
null
Forgetting null checks
getItem returns null when missing. Guard before writing into HTML inputs or classes.
file
file: URLs
Behavior is undefined across browsers. Do not rely on localStorage when opening HTML files from disk—use a local server.
quota
QuotaExceededError
Large strings can throw. Catch errors around setItem for big payloads.
private
Private / incognito
Data is typically cleared when the last private tab closes. Do not assume permanent storage in private mode.
Compatibility
Browser Support
localStorage is part of the Web Storage API and is supported in all modern browsers.
✓ Baseline · Widely available
localStorage in HTML pages
Persistent Web Storage works across current browsers for same-origin HTML documents.
100%localStorage support
Google ChromeAll versions · Desktop & Mobile
Full support
Mozilla FirefoxAll versions · Desktop & Mobile
Full support
Apple SafariAll versions · macOS & iOS
Full support
Microsoft EdgeAll versions · Chromium & Legacy
Full support
Internet ExplorerIE 6+ · Legacy environments
Full support
OperaAll modern versions
Full support
Web Storage localStorageUniversal
Bottom line: Use localStorage for lasting client preferences—support is widespread; watch privacy settings and file: origins.
Remember
Key Takeaways
Persists across sessions until cleared; shared by all tabs of the origin.
Not cookies — values stay in the browser and are not sent with HTML requests.
API:setItem, getItem, removeItem, clear.
Wire to HTML on load to restore theme, prefs, and form defaults.
One line: From your HTML page’s script, use localStorage for lasting, origin-scoped key-value data that outlives the browser session.
Frequently Asked Questions
localStorage is a Web Storage API on the window object. From a script in your HTML page you store string key-value pairs for the document’s origin. Data survives closing the browser until you remove it or the user clears site data.
localStorage is shared across all tabs of the same origin and has no expiration. sessionStorage is per tab and clears when that tab’s page session ends.
No. Unlike cookies, localStorage stays in the browser and is not attached to HTTP requests. Use it for client-only preferences such as theme or UI layout.
On change, call localStorage.setItem(key, value). On page load, getItem and apply the value to your HTML (for example set a class on body or fill an input).
Only strings are stored. Use JSON.stringify before setItem and JSON.parse after getItem when you need objects.
Invalid origins (for example some file: pages) or privacy settings that block site data can prevent storage. Prefer testing over http(s). Never store secrets—same-origin scripts can read localStorage.