Settings & Saving
Players expect a game to remember things: the high score, the volume, whether screen shake is on, which level they reached. A browser game with no server keeps this in localStorage, a small key-value store (a few megabytes of strings per site) that survives reloads and restarts. This lesson builds a save system that is robust: it survives storage being unavailable, corrupt data and old save formats.
localStorage in one minute
localStorage.setItem('best', '1200'); // strings only
const best = Number(localStorage.getItem('best') ?? 0); // null if the key is missing
localStorage.setItem('save', JSON.stringify({ level: 3, coins: 41 }));
const save = JSON.parse(localStorage.getItem('save'));
localStorage.removeItem('save');Everything is a string, so objects go through JSON.stringify / JSON.parse. The calls are synchronous and fast for small data, which is exactly what settings and high scores are.
When storage is not there
localStorage can fail, and a game must not crash when it does:
| Situation | What happens |
|---|---|
Sandboxed iframe without allow-same-origin (like this lesson's playgrounds) |
Even reading window.localStorage throws a SecurityError |
| Storage disabled, some privacy modes, blocked third-party iframes | Access throws, or writes are discarded when the session ends |
| Quota full | setItem throws a QuotaExceededError |
| The player edited or corrupted the data | JSON.parse throws, or you get a value of the wrong type |
| An older version of your game wrote the save | Fields are missing or named differently |
The fix is a small wrapper: try the real storage once, and if anything throws, fall back to an in-memory Map that behaves the same way (it just forgets everything when the page closes). The rest of the game never touches localStorage directly.
Versioned saves with validation
Pure logic first. The storage backend is passed in, so we can test both the "blocked" case and the fallback in Node. Every save carries a version number; migrate upgrades old formats step by step and validate repairs anything out of range:
function memoryBackend() {
const m = new Map();
return { getItem: (k) => (m.has(k) ? m.get(k) : null), setItem: (k, v) => m.set(k, String(v)), removeItem: (k) => m.delete(k) };
}
function openStore(getBackend) {
try {
const b = getBackend(); // may throw (SecurityError)
b.setItem('__probe', '1'); // may throw (quota, disabled)
b.removeItem('__probe');
return { kind: 'persistent', b };
} catch (e) {
return { kind: `memory (${e.name})`, b: memoryBackend() };
}
}
const KEY = 'skyhopper.save';
const DEFAULTS = { version: 2, highScore: 0, settings: { volume: 0.8, shake: true } };
function migrate(d) {
if (d.version === 1) { // v1: { version, best, muted }
d = { version: 2, highScore: d.best, settings: { volume: d.muted ? 0 : 0.8, shake: true } };
}
return d;
}
function validate(d) {
const s = d.settings ?? {};
return {
version: 2,
highScore: Number.isInteger(d.highScore) && d.highScore >= 0 ? d.highScore : 0,
settings: {
volume: typeof s.volume === 'number' ? Math.min(1, Math.max(0, s.volume)) : 0.8,
shake: typeof s.shake === 'boolean' ? s.shake : true,
},
};
}
function load(store) {
const raw = store.b.getItem(KEY);
if (raw === null) return structuredClone(DEFAULTS);
try { return validate(migrate(JSON.parse(raw))); }
catch { return structuredClone(DEFAULTS); } // corrupt JSON: start fresh
}
const save = (store, data) => store.b.setItem(KEY, JSON.stringify(data));
// 1. A backend that throws like a sandboxed iframe does
const store = openStore(() => {
const e = new Error('The operation is insecure.');
e.name = 'SecurityError';
throw e;
});
console.log('backend:', store.kind);
console.log('fresh:', JSON.stringify(load(store)));
// 2. An old v1 save is upgraded
store.b.setItem(KEY, JSON.stringify({ version: 1, best: 4200, muted: true }));
console.log('from v1:', JSON.stringify(load(store)));
// 3. Bad values are repaired, corrupt JSON falls back to defaults
store.b.setItem(KEY, JSON.stringify({ version: 2, highScore: -5, settings: { volume: 7 } }));
console.log('repaired:', JSON.stringify(load(store)));
store.b.setItem(KEY, '{oops');
console.log('corrupt:', JSON.stringify(load(store)));
// 4. A round trip
const data = load(store);
data.highScore = 990;
save(store, data);
console.log('round trip:', load(store).highScore);backend: memory (SecurityError)
fresh: {"version":2,"highScore":0,"settings":{"volume":0.8,"shake":true}}
from v1: {"version":2,"highScore":4200,"settings":{"volume":0,"shake":true}}
repaired: {"version":2,"highScore":0,"settings":{"volume":1,"shake":true}}
corrupt: {"version":2,"highScore":0,"settings":{"volume":0.8,"shake":true}}
round trip: 990
Playable demo
Catch the falling stars with the basket (Left/Right). Missing three ends the round; the best score is saved. S toggles a sound setting and D cycles the difficulty, and both are saved immediately. The top line shows which storage backend the wrapper picked.
<style>
html, body { margin: 0; height: 100%; background: #0e1018; overflow: hidden; }
canvas { display: block; margin: 0 auto; width: min(100vw, 177.78vh); height: auto; outline: none; touch-action: none; }
</style>
<canvas width="480" height="270"></canvas>
<script>
// ---- play kit: click to focus, keep game keys inside the frame, fixed-step loop ----
const cv = document.querySelector('canvas'), ctx = cv.getContext('2d');
const W = cv.width, H = cv.height;
const keys = new Set(), pressed = new Set(); // keys held now / pressed since the last update
let active = false, idleDrawn = false;
cv.tabIndex = 0;
cv.addEventListener('pointerdown', () => cv.focus());
cv.addEventListener('focus', () => { active = true; });
cv.addEventListener('blur', () => { active = false; idleDrawn = false; keys.clear(); pressed.clear(); });
addEventListener('keydown', (e) => {
if (e.code.startsWith('Arrow') || e.code === 'Space') e.preventDefault(); // don't scroll the lesson
if (!e.repeat) pressed.add(e.code);
keys.add(e.code);
});
addEventListener('keyup', (e) => keys.delete(e.code));
function banner(title, sub = '') {
ctx.save();
ctx.fillStyle = 'rgba(0,0,0,0.6)'; ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#fff'; ctx.textAlign = 'center'; ctx.textBaseline = 'middle';
ctx.font = 'bold 22px system-ui, sans-serif'; ctx.fillText(title, W / 2, H / 2 - 10);
ctx.font = '14px system-ui, sans-serif'; ctx.fillText(sub, W / 2, H / 2 + 18);
ctx.restore();
}
function run(update, draw, help = '') {
const STEP = 1 / 60;
let acc = 0, last = performance.now();
requestAnimationFrame(function frame(now) {
const dt = Math.min((now - last) / 1000, 0.1);
last = now;
if (active) {
acc += dt;
while (acc >= STEP) { update(STEP); pressed.clear(); acc -= STEP; }
draw();
} else if (!idleDrawn) {
draw(); banner('Click to play', help); idleDrawn = true;
}
requestAnimationFrame(frame);
});
}
// ---- end of play kit ----
// ---- safe storage: real localStorage when allowed, memory otherwise ----
function openStorage() {
try {
const s = window.localStorage; // throws SecurityError in a sandboxed frame
s.setItem('__probe', '1');
s.removeItem('__probe');
return { kind: 'localStorage', get: (k) => s.getItem(k), set: (k, v) => s.setItem(k, v) };
} catch (e) {
const m = new Map();
return { kind: `memory (${e.name})`, get: (k) => m.get(k) ?? null, set: (k, v) => m.set(k, String(v)) };
}
}
const store = openStorage();
const KEY = 'starcatch.v1';
function loadSave() {
try {
const d = JSON.parse(store.get(KEY));
if (d && d.version === 1) return d;
} catch {}
return { version: 1, best: 0, sound: true, difficulty: 0 };
}
function writeSave() {
try { store.set(KEY, JSON.stringify(data)); }
catch (e) { console.warn('save failed:', e.name); } // e.g. quota exceeded
}
const data = loadSave();
console.log('storage backend:', store.kind);
// ---- the game ----
const DIFFS = ['easy', 'normal', 'hard'];
let basket, stars, score, misses, spawn, over;
function reset() { basket = { x: 220, w: 60 }; stars = []; score = 0; misses = 0; spawn = 0; over = false; }
reset();
function update(dt) {
if (pressed.has('KeyS')) { data.sound = !data.sound; writeSave(); }
if (pressed.has('KeyD')) { data.difficulty = (data.difficulty + 1) % 3; writeSave(); }
if (over) { if (pressed.has('Enter') || pressed.has('Space')) reset(); return; }
if (keys.has('ArrowLeft')) basket.x -= 280 * dt;
if (keys.has('ArrowRight')) basket.x += 280 * dt;
basket.x = Math.max(0, Math.min(W - basket.w, basket.x));
spawn -= dt;
if (spawn <= 0) {
stars.push({ x: 20 + Math.random() * (W - 40), y: 30, vy: 70 + data.difficulty * 45 + score * 2 });
spawn = 0.9 - data.difficulty * 0.2;
}
for (const s of stars) s.y += s.vy * dt;
for (const s of stars) {
if (s.y > H - 30 && s.y < H - 14 && s.x > basket.x && s.x < basket.x + basket.w) { s.dead = true; score++; }
else if (s.y > H) { s.dead = true; misses++; }
}
stars = stars.filter((s) => !s.dead);
if (misses >= 3) {
over = true;
if (score > data.best) { data.best = score; writeSave(); }
}
}
function draw() {
ctx.fillStyle = '#0d1b2a';
ctx.fillRect(0, 0, W, H);
ctx.fillStyle = '#ffd54f';
for (const s of stars) ctx.fillRect(Math.round(s.x - 5), Math.round(s.y - 5), 10, 10);
ctx.fillStyle = '#8d6e63';
ctx.fillRect(Math.round(basket.x), H - 22, basket.w, 12);
ctx.font = '12px monospace';
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = '#9fa8da';
ctx.fillText(`saved in: ${store.kind}`, 8, 16);
ctx.fillStyle = '#fff';
ctx.fillText(`score ${score} best ${data.best} misses ${misses}/3`, 8, 32);
ctx.fillText(`[S] sound ${data.sound ? 'on' : 'off'} [D] ${DIFFS[data.difficulty]}`, 8, 48);
if (over) banner(score >= data.best && score > 0 ? 'NEW BEST!' : 'ROUND OVER', 'Press Enter to play again');
}
run(update, draw, 'Left/Right catch stars, S sound, D difficulty');
</script>Here the top line reads memory (SecurityError): the lesson playground runs in a sandboxed frame that has no storage of its own, so the best score lasts until you press Run again. Copy the same code into your own page (served from a real origin) and the wrapper picks localStorage, and your best score survives reloads. The game code doesn't change at all; only the backend does.
Save system checklist
- One key per game, with a prefix (
skyhopper.save): every game on the same origin shares one storage area. - A version field in every save, and a
migratefunction that upgrades old versions one step at a time. - Validate on load: clamp numbers, check types, fall back to defaults. Never trust stored data.
- Save at safe moments: on a checkpoint, on game over, when a setting changes, and on
visibilitychangetohidden(the last reliable moment on mobile, wherebeforeunloadoften never fires). - Keep it small. For big data (replays, level editors) use IndexedDB instead.
- It's not secure. Anyone can open the dev tools and edit
localStorage, so online leaderboards need a server that checks scores.
Tip: Signing in is not needed for any of this. Games that want cloud saves add a server later; the local save stays as the offline copy.
Test yourself
Why does the demo show memory (SecurityError) in the lesson playground?
- The game has a bug
- The sandboxed frame has no
allow-same-origin, so accessinglocalStoragethrows - localStorage is full
- Browsers removed localStorage
What is the purpose of the version field in a save?
- To show the game version on the title screen
- So the loader knows how to migrate older save formats
- Browsers require it
- To encrypt the save
What should load() do when the stored JSON is corrupt?
- Crash so the player notices
- Catch the error and fall back to defaults
- Delete all other keys
- Retry forever