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.

JavascriptConfig Management

Code

javascriptsnippet
30 lines
// 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: localStorage are not available in Node.
  • The guard !raw short-circuits the flow with an early return when 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

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.