JavaScript in the page · Lesson 33 of 45
Saving in the browser (localStorage)
Keep data after the page is closed.
7 minutes2 games
localStorage saves text in the browser that survives closing the page and the browser. Its tools: setItem(key, value), getItem(key), removeItem(key). It stores only strings, so objects go through JSON.
HTML
<p>Visits on this device: <strong id="visits"></strong></p>
<button id="reset">Reset</button>
<script>
let visits = 0
try {
visits = Number(localStorage.getItem("visits") ?? 0) + 1
localStorage.setItem("visits", String(visits))
} catch {
console.log("Storage is blocked in this preview")
}
document.querySelector("#visits").textContent = visits
document.querySelector("#reset").onclick = () => {
try { localStorage.removeItem("visits") } catch {}
document.querySelector("#visits").textContent = 0
}
const settings = { theme: "dark", fontSize: 16 }
const saved = JSON.stringify(settings)
console.log("saved as text:", saved)
console.log("read back:", JSON.parse(saved).theme)
</script>Storage may be blocked in this preview for security, so the code handles it with try/catch.
| localStorage | sessionStorage | Cookies | |
|---|---|---|---|
Lasts until | you clear it | the tab closes | an expiry date |
Sent to server? | no | no | with every request |
Size | ~5MB | ~5MB | ~4KB |
Complete the code
Save the object to localStorage.
const cart = { items: 3 } localStorage.setItem("cart", JSON.(cart))
Quick question
localStorage.setItem("n", 5) then localStorage.getItem("n") returns…?
Learn more from
Played 0 of 2 games
Sign in to save your progress and earn XP.