localStorage Persists UI State Safely
Persist preferences with localStorage: JSON serialize before setItem, degrade gracefully on quota or privacy errors, and repair or remove corrupt entries.
Code
// localStorage:同源字符串键值存储——存对象必须先 JSON 序列化
const KEY = 'theme-preferences';
function save(prefs) {
try {
localStorage.setItem(KEY, JSON.stringify(prefs));
} catch (err) {
// 隐私模式、禁用存储、超出约 5MB 配额都会抛异常——只记录不崩
console.log('save failed:', err.name);
}
}
function load() {
const raw = localStorage.getItem(KEY);
if (!raw) return null;
try {
return JSON.parse(raw);
} catch {
localStorage.removeItem(KEY); // 坏数据直接清掉,别让页面挂掉
return null;
}
}
save({ density: 'compact', sidebar: true });
console.log('loaded:', load());
console.log('stored bytes:', localStorage.getItem(KEY).length);
// 注销等场景用完即删:不留痕迹
localStorage.removeItem(KEY);
console.log('after remove:', localStorage.getItem(KEY));How the snippet works
Count the functions save and load as the entire surface area of localStorage Persists UI State Safely.
What to watch for
- A browser is the runtime here:
localStorageare not available in Node. - The guard
!rawshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The main signature reads function save(prefs)
Running the file prints labeled results such as save failed:, loaded:, stored bytes: — each operation’s effect is visible in the output.
Key statements
localStorage.setItem(KEY, JSON.stringify(prefs));
return JSON.parse(raw);
if (!raw) return null;
Interactive Tools for This Topic
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
FAQ
- Does localStorage Persists UI State Safely run in plain Node.js?
- No — it touches `localStorage`, which exist only in the browser. Run it in a page (or the DevTools console) instead of a bare Node process.
Report a problem with this exampleOpens a pre-filled issue on GitHub.