HTML Web Storage
Web Storage lets a page save small pieces of data in the user's browser — a chosen theme, a half-written note, the contents of a shopping cart — so they are still there after a reload. It is simpler and roomier than cookies, and the data is never sent to the server automatically.
Two storage areas
| Object | Lifetime | Shared between |
|---|---|---|
localStorage |
Until it is deleted (by your code or the user) | All tabs and windows of the same site |
sessionStorage |
Until the tab is closed | Only the current tab |
Both have exactly the same methods, and each site (origin) gets its own separate storage — usually around 5 MB.
The methods
| Method / property | What it does |
|---|---|
setItem(key, value) |
Save a value under a key |
getItem(key) |
Read a value (returns null if missing) |
removeItem(key) |
Delete one key |
clear() |
Delete everything for this site |
key(i) |
Name of the key at position i |
length |
Number of stored keys |
localStorage.setItem('theme', 'dark');
const theme = localStorage.getItem('theme'); // "dark"
localStorage.removeItem('theme');Storage can be unavailable
localStorage is not guaranteed. Private browsing modes, browser settings, full storage and sandboxed iframes can all make it throw an error the moment you touch it.
Note: ExcelTAD playgrounds run in a sandboxed iframe without same-origin access, so
localStorageusually throws aSecurityErrorhere. The examples below detect this and fall back to an in-memory object — the page still works, it just forgets everything on reload. Run the same code in a normal page and it will remember.
A safe helper looks like this:
<!DOCTYPE html>
<html>
<body>
<p id="info"></p>
<script>
function getStorage() {
try {
const s = window.localStorage;
s.setItem('__test', '1');
s.removeItem('__test');
return { store: s, real: true };
} catch (e) {
const mem = {};
return {
real: false,
store: {
getItem: function (k) { return k in mem ? mem[k] : null; },
setItem: function (k, v) { mem[k] = String(v); },
removeItem: function (k) { delete mem[k]; },
clear: function () { for (const k in mem) delete mem[k]; }
}
};
}
}
const result = getStorage();
document.getElementById('info').textContent = result.real
? 'localStorage is available — data will survive a reload.'
: 'localStorage is blocked here — using an in-memory fallback.';
</script>
</body>
</html>A visit counter
<!DOCTYPE html>
<html>
<body>
<h3 id="msg"></h3>
<button id="again">Visit again</button>
<button id="reset">Reset</button>
<script>
let store;
try { store = window.localStorage; store.getItem('x'); }
catch (e) { const m = {}; store = { getItem: k => m[k] ?? null, setItem: (k, v) => { m[k] = String(v); }, removeItem: k => { delete m[k]; } }; }
function visit() {
const count = Number(store.getItem('visits') || 0) + 1;
store.setItem('visits', count);
document.getElementById('msg').textContent = 'You have visited ' + count + ' time(s).';
}
document.getElementById('again').onclick = visit;
document.getElementById('reset').onclick = function () {
store.removeItem('visits');
document.getElementById('msg').textContent = 'Counter reset.';
};
visit();
</script>
</body>
</html>Values are always strings
Web Storage only stores strings. Numbers come back as text (that is why the example uses Number(...)), and saving an object directly gives you the useless string "[object Object]". To store objects and arrays, convert them with JSON:
<!DOCTYPE html>
<html>
<body>
<input id="item" placeholder="Add a to-do">
<button id="add">Add</button>
<ul id="list"></ul>
<script>
let store;
try { store = window.localStorage; store.getItem('x'); }
catch (e) { const m = {}; store = { getItem: k => m[k] ?? null, setItem: (k, v) => { m[k] = String(v); } }; }
function load() {
try { return JSON.parse(store.getItem('todos')) || []; }
catch (e) { return []; }
}
function render() {
const list = document.getElementById('list');
list.innerHTML = '';
load().forEach(function (text) {
const li = document.createElement('li');
li.textContent = text;
list.appendChild(li);
});
}
document.getElementById('add').onclick = function () {
const input = document.getElementById('item');
if (!input.value.trim()) return;
const todos = load();
todos.push(input.value.trim());
store.setItem('todos', JSON.stringify(todos));
input.value = '';
render();
};
render();
</script>
</body>
</html>JSON.stringify turns the array into text for saving; JSON.parse turns it back. Wrapping JSON.parse in try/catch protects you if the stored value is ever corrupted.
The storage event
When one tab changes localStorage, other open tabs of the same site receive a storage event. This lets you keep several tabs in sync (for example logging out everywhere at once).
window.addEventListener('storage', function (e) {
console.log(e.key, 'changed from', e.oldValue, 'to', e.newValue);
});What not to store
- Passwords, tokens or personal data — any script running on the page can read Web Storage, so a single injected script could steal it.
- Large data — use IndexedDB for megabytes of structured data.
- Anything critical — users can clear storage at any time.
Tip: Prefix your keys (
myapp:theme) so that different parts of a site do not accidentally overwrite each other's data.
Test yourself
What is the main difference between localStorage and sessionStorage?
sessionStorageis biggerlocalStoragepersists after the tab closes;sessionStorageis cleared when the tab closeslocalStorageis sent to the server- There is no difference
How should you store an array in localStorage?
setItem('a', myArray)setItem('a', JSON.stringify(myArray))setItem('a', myArray.length)- Arrays cannot be stored
Why wrap access to localStorage in try/catch?
- It is always slow
- It can throw when storage is blocked, e.g. in private mode or sandboxed iframes
- It returns promises
- It only works in Chrome