Reference
Compressed sheet for sessionStorage /
localStorage method map, string rules, and
StorageEvent. Print-friendly.
const store = sessionStorage; // or localStorage
// both return a Storage object for this origin (session: + this tab)
| Call | Returns / effect |
|---|---|
getItem(key) |
String value, or null if missing |
setItem(key, value) |
Stores strings (coerces). May throw
QuotaExceededError
|
removeItem(key) |
Deletes key; no-op if absent |
clear() |
Removes all keys in this Storage area |
key(index) |
Name of nth key, or null. Order is
implementation-defined
|
length |
Number of keys (read-only) |
Use setItem/getItem/removeItem
— not store.key = value or store["key"] —
to avoid colliding with built-ins and prototype pitfalls
(MDN).
sessionStorage.setItem("user", JSON.stringify({ name: "Alex" }));
const user = JSON.parse(sessionStorage.getItem("user"));
// getItem null → JSON.parse(null) is fine (→ null); guard missing keys anyway
// WRONG: setItem coerces objects via ToString → "[object Object]"
sessionStorage.setItem("user", { name: "Alex" });
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")) {
// safe to use
}
From
MDN Using the Web Storage API. Existence of window.sessionStorage is not enough —
policy / private mode may block writes.
window when a storage area changes in
another document that shares that area — not on the
document that made the change.
localStorage: other same-origin tabs
receive it.
sessionStorage: only other same-origin documents in the
same tab (e.g. iframes) — not other tabs.
key, oldValue,
newValue, url, storageArea
(key/newValue are null on
clear().
window.addEventListener("storage", (e) => {
if (e.storageArea !== sessionStorage) return;
// e.key, e.oldValue, e.newValue, e.url
});
New window via window.open starts with a
copy of the opener’s sessionStorage; then
the two maps diverge
(MDN).