

新闻资讯
技术学院localStorage操作必须用setItem()/getItem(),存对象需JSON序列化,注意5MB限制、无痕模式兼容性、storage事件仅跨tab触发、无自动过期机制需手动实现TTL。
存取字符串数据必须用 setItem() 和 getItem(),不能直接赋值或读取属性。比如 localStorage.myKey = "value" 虽然看似生效,但实际无法触发 StorageEvent,且在某些浏览器隐私模式下会静默失败。
实操建议:
JSON.stringify() 存对象,用 JSON.parse() 读取,否则得到的是 [object Object]
typeof localStorage !== 'undefined',避免 Safari 无痕模式报 SecurityError
QuotaExceededError
const user = { id: 123, name: 'Alice' };
try {
localStorage.setItem('user', JSON.stringify(user));
const saved = JSON.parse(localStorage.
getItem('user'));
console.log(saved.name); // 'Alice'
} catch (e) {
if (e.name === 'QuotaExceededError') {
console.error('localStorage 已满');
}
}
delete localStorage.key 完全无效,也不会报错 —— 这是常见误操作。真正生效的只有 removeItem()(删单个)和 clear()(清空全部)。
使用场景差异:
removeItem('token'):退出登录时删凭证,保留用户偏好等其他键clear():调试时快速重置,生产环境慎用,可能误删关键配置Object.keys(localStorage) 遍历过滤storage 事件**只在其他同源 tab 或 iframe 中修改 localStorage 时触发**,当前页面调用 setItem() 不会触发自身监听器 —— 这点极易误解。
关键限制:
event.key、event.newValue、event.oldValue 仅提供变更信息,不包含完整 stateclear() 后的具体哪些键被删了,event.key 为 null
window.addEventListener('storage', (e) => {
if (e.key === 'auth_token') {
if (!e.newValue) {
console.log('token 已被其他页面清除');
// 触发登出逻辑
}
}
});
原生 localStorage 不支持 TTL(time-to-live),所谓“自动过期”必须手动实现。常见做法是在存值时附带 expires 时间戳,读取时比对。
容易踩的坑:
Date.now() 存毫秒数,别用 new Date().toString() —— 字符串解析慢且易错removeItem(),否则下次读还是旧值function setWithExpiry(key, value, ttlMs) {
const item = {
value,
expiry: Date.now() + ttlMs
};
localStorage.setItem(key, JSON.stringify(item));
}
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
if (Date.now() > item.expiry) {
localStorage.removeItem(key);
return null;
}
return item.value;
}
实际项目里,缓存是否过期、是否需要强制刷新、是否要 fallback 到 fetch,这些逻辑往往比存取本身更关键。localStorage 只是容器,怎么设计缓存策略,才是难点。