在前端开发中,可以通过设置失效时间(TTL)来自动清除本地存储(如 localStorage 或 sessionStorage)中的过期数据。
方法一:存储时附加过期时间戳
在保存数据时,同时存储一个过期时间戳,读取时检查是否过期。
代码示例
javascript
// 存储数据(设置1小时后过期)
function setWithExpiry(key, value, ttlHours) {
const now = new Date();
const item = {
value: value,
expiry: now.getTime() + ttlHours * 60 * 60 * 1000, // 当前时间 + TTL(毫秒)
};
localStorage.setItem(key, JSON.stringify(item));
}
// 获取数据(自动检查过期)
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key);
if (!itemStr) return null;
const item = JSON.parse(itemStr);
const now = new Date();
if (now.getTime() > item.expiry) {
localStorage.removeItem(key); // 数据过期,删除
return null;
}
return item.value;
}
// 使用示例
setWithExpiry("userToken", "abc123", 1); // 1小时后过期
const token = getWithExpiry("userToken"); // 过期后返回null
方法二:使用第三方库
如果不想手动实现,可以使用现成的库,如:
- store.js:支持过期时间的本地存储库。
- localForage:支持过期时间的异步存储库。
示例(store.js)
javascript
import store from 'store';
// 设置数据(1天后过期)
store.set('userData', { name: 'Alice' }, { ttl: 86400 });
// 获取数据(自动处理过期)
const data = store.get('userData'); // 过期后返回undefined
方法三:定时清理过期数据
通过定时任务(如 setInterval)定期扫描并清理过期数据。
代码示例
javascript
function cleanupExpiredItems() {
const now = new Date().getTime();
Object.keys(localStorage).forEach(key => {
try {
const item = JSON.parse(localStorage.getItem(key));
if (item.expiry && now > item.expiry) {
localStorage.removeItem(key);
}
} catch (e) {
// 忽略非JSON数据
}
});
}
// 每天清理一次
setInterval(cleanupExpiredItems, 24 * 60 * 60 * 1000);
注意事项
- localStorage 的限制:
- 同步操作,大量数据可能阻塞主线程。
- 存储容量通常为 5MB 左右。
- sessionStorage:
- 仅在当前会话有效(关闭标签页后清除)。
- 无需手动清理,但无法跨标签页共享。
- 安全性:
- 敏感数据(如 Token)应结合 HttpOnly Cookie 使用,避免 XSS 攻击。
总结
| 方法 | 适用场景 | 优点 | 缺点 |
|---|---|---|---|
| 附加时间戳 | 简单需求 | 灵活控制单个键的过期时间 | 需要手动检查 |
| 第三方库 | 复杂项目 | 功能完善(如自动清理) | 增加依赖 |
| 定时清理 | 大量数据 | 批量处理过期数据 | 可能影响性能 |
根据项目需求选择合适的方法。对于大多数场景,方法一(附加时间戳)是最简单高效的解决方案。