Lesson 0002 · ~12 minutes

Storage API & events

One skill: use the Storage method map correctly (strings + JSON, feature detection, deletes) and predict when a storage event fires for sessionStorage vs localStorage.

Win for this lesson

You can sketch get/set/remove with JSON, name QuotaExceededError, and correctly say “this will not notify the other tab” for sessionStorage — without re-litigating the spectrum.

1. One interface, two partitions

window.sessionStorage and window.localStorage each return a Storage object. Same methods; different lifetime (lesson 1). Spec surface (WHATWG HTML):

Call Behavior
getItem(key) String, or null if the key is absent
setItem(key, value) Writes a string; may throw QuotaExceededError
removeItem(key) Deletes one key (no-op if missing)
clear() Wipes this Storage area
key(i) / length Enumerate; key order is implementation-defined — don’t rely on sort
sessionStorage.setItem("wizardStep", "2");
const step = sessionStorage.getItem("wizardStep"); // "2" or null
sessionStorage.removeItem("wizardStep");
// sessionStorage.clear(); // nuclear option for this tab's session map
Default rule (steal this)

Always use the method API (setItem/getItem/removeItem), not sessionStorage.foo = … or bracket assignment. MDN warns that property access collides with built-ins and invites prototype pitfalls (Using the Web Storage API).

2. Strings only — serialize on purpose

Keys and values are always strings. Pass an object without JSON.stringify and you get the useless "[object Object]" (MDN):

const draft = { step: 2, email: "a@b.co" };

// WRONG
sessionStorage.setItem("draft", draft);
sessionStorage.getItem("draft"); // "[object Object]"

// RIGHT
sessionStorage.setItem("draft", JSON.stringify(draft));
const restored = JSON.parse(sessionStorage.getItem("draft"));
// restored is a deep copy — mutating it does not update storage

Guard missing keys: getItem returns null. Prefer explicit checks over assuming a shape. Catch setItem failures — full quota or disabled storage both throw.

3. Feature-detect availability

The property can exist while writes still fail (policy, private mode quirks). MDN’s pattern actually tries a write (Using guide):

function storageAvailable(type) {
  let storage;
  try {
    storage = window[type];
    const x = "__storage_test__";
    storage.setItem(x, x);
    storage.removeItem(x);
    return true;
  } catch (e) {
    return (
      e instanceof DOMException &&
      e.name === "QuotaExceededError" &&
      storage &&
      storage.length !== 0
    );
  }
}

if (storageAvailable("sessionStorage")) {
  sessionStorage.setItem("wizardStep", "1");
}

Call with "sessionStorage" or "localStorage". Design reviews: never assume Web Storage is always writable.

4. storage events — who hears what

A StorageEvent is dispatched to other windows that share the same storage area — not to the document that performed the write (MDN, HTML broadcast rules).

localStorage

Area shared by all same-origin tabs. Other tabs get storage when one tab writes.

sessionStorage

Area shared only within the tab (e.g. same-origin iframes). Other tabs do not get the event — they never shared the map.

window.addEventListener("storage", (e) => {
  // e.key, e.oldValue, e.newValue, e.url, e.storageArea
  if (e.storageArea === localStorage) {
    // react to another tab's localStorage change
  }
});
Design-review trap

“We’ll sync tabs with sessionStorage + storage events” does not work. Use localStorage (or BroadcastChannel / server) for multi-tab messaging. sessionStorage’s job is isolation, not broadcast.

Related: opening via window.open copies sessionStorage once, then the maps diverge — not a live sync channel (MDN sessionStorage).

5. Practice

Equal-length options. Pick the best answer; feedback is immediate.

Scenario A

You need to save a small object { step: 2, email } in sessionStorage for reload in this tab.

Scenario B

After getItem("wizardStep"), what should you treat as “this key was never stored”?

Scenario C

Tab A calls sessionStorage.setItem("x","1"). Tab B is same origin, no iframes. Who gets a storage event?

Scenario D

Tab A calls localStorage.setItem("theme","dark"). Same origin Tab B is open. Best expectation?

Scenario E

Before relying on sessionStorage in production, what is the sound availability check?

6. What to remember

Ask your teacher Fuzzy on opener copy, private mode, or a real multi-tab design on your team? Ask in chat — follow-ups are part of the method.

Primary source (read next)

MDN — Using the Web Storage API. Feature detection, set/get/remove, JSON, and StorageEvent with the session-vs-local distinction. Keep the reference sheet open while you code.