Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
Loading…
Code Lab is in development. New lessons and improvements are on the way. Progress can be deleted.
JAVASCRIPT STORAGE / CHAPTER 06 / Learn / LESSON 10
Theory. setItem can throw — most often QuotaExceededError (storage full), but also when writing is forbidden. If you do not catch it, the script stops; if you catch it and still show "Saved", you lie to the user.
Rule for an honest status: show success ONLY after setItem finished without an error.
try { window.labStorage.setItem("last", value); status.textContent = "saved"; } catch (error) { status.textContent = "save-failed"; }
Order matters: setItem comes FIRST, the text "saved" after it (inside try, not before). On error do not clear the field — the user must not lose what they typed — and do not draw the new record as saved.
In Code Lab the host simulates a full store (the first write, or every write after N successful ones, throws QuotaExceededError).
Common mistake: status = "saved" before setItem; an empty catch; clearing the form before a successful write.
<form id="f"><input id="title" name="title" type="text"><button type="submit">Save</button></form><p id="status"></p>An honest status comes after a successful setItem, inside try; catch shows the failure.
(empty)Press Run — HTML loads in a sandbox iframe; Stop removes the iframe (also kills infinite loops).
›