Kept After a Reload: localStorage
A game that forgets your level every time you close it would be no fun. Good games save: close them, come back tomorrow, and you are where you stopped. A web page forgets everything when it reloads, unless it saves what matters in the browser.
Everything starts again
Variables only live while the page is open. Reload it, and the script runs again from the first line: every variable starts with its first value. The theme a visitor chose a minute ago is gone.
localStorage
localStorage is a small store that the browser keeps for each website, even after the page is closed or the computer is turned off. It holds texts, each one under a name, called a key:
localStorage.setItem("level", "7");
setItem saves the text "7" under the key "level". If something was saved under that key before, it's replaced.
getItem reads it back, on this page or after any reload:
const level = localStorage.getItem("level");
console.log(level);
7
Nothing saved yet
On a first visit, nothing has been saved, and getItem gives null:
console.log(localStorage.getItem("nickname"));
null
So a page reads what was saved, and keeps its usual start when it gets null:
<button type="button" id="up">Next level</button>
<p id="shown"></p>
<script>
let level = 1;
const saved = localStorage.getItem("level");
if (saved !== null) {
level = Number(saved);
}
document.querySelector("#shown").textContent = `Level ${level}`;
document.querySelector("#up").addEventListener("click", () => {
level = level + 1;
localStorage.setItem("level", level);
document.querySelector("#shown").textContent = `Level ${level}`;
});
</script>
Click a few times, then change the code a little so the preview starts again: the level is still there. localStorage only keeps texts. The number becomes a text when it's saved, and Number turns it back.
Only in this browser
What a page saves stays in that browser, on that device. Open the site on your phone, and it knows nothing about your computer's choices. And everyone can see and delete what is in their own browser's store, so never keep a password or anything secret there.
Break it on purpose
Read the saved value without checking for null: level = Number(localStorage.getItem("level")). On a first visit, Number(null) is 0, so the game starts at level 0. With a text, it's worse: a theme of null would show "Theme: null". Always decide what a first visit gets.
Mission: Remember the theme
What you will see: click Dark, then reload the page. It still says Theme: Dark, with the Dark button pressed.
Visitors choose a theme, reload the page, and their choice is gone. The settings page should remember it.
- Each time a theme is chosen, by its button or by bringing settings, it's saved in the browser under the key
theme. - When the page opens, a saved theme wins over the button pressed in the HTML.
- Without a saved theme, the page starts as before.
On a first visit, getItem gives null.