有时效的LocalStorage

前言

在前端开发中,我们经常需要有a一个能存储全局变量,并且在关闭浏览器之后还能保存着的存储对象。常见的有cookie与localstorage,两者相比,cookie所能存储的容量较小(大小限制在4kb),cookie会被附加到每次http请求中,并且在非https模式下是明文传递,存在很大的安全性问题。且不说安全性问题,在每次请求都带有cookie,无形之中对服务器流量也造成的不小的消耗。然而localstorage可以存储则相较于cookie就比较大了,在chorome(78.0.3904.97)下,可存储上限是在5120KB,这个容量的大小对于缓存而言已经足够使用了。但是localstorage无法直接设置过期时间,只能手动去删除。但是很多需求是需要有时效的临时变量。那么就需要手动实现一个有时效的localstorage。

  • 思路:封装一个LocalStorageUtils来对LocalStorage进行操作。
  • setItem时,多放进一个expires与startTime来设置过期时间与开始时间来实现过期清除。
  • getItem时,如果现在时间减去开始时间小于等于过期时间则清除该key。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
/**
* localStorage的工具
* */
const localStorageUtils = {
/**
* @param name 键
* @param value 值
* @param expires 过期时间(毫秒)
* */
setItem(name, value, expires) {
//首先判断是否为整数
if (typeof expires !== "number" || expires % 1 !== 0) {
expires = 0;
} else if (expires < 0) {//其次判断是否为正数
expires = 0;
}
let obj = {
name: name,
value: value,
expires: expires,
startTime: new Date().getTime()
};
window.localStorage.setItem(obj.name, JSON.stringify(obj));
},
/**
* 通过 name来获取对应的值
* @param name 键
* @return 在localstorage中name对应的值
* */
getItem(name) {
let obj;
try {
obj = JSON.parse(window.localStorage.getItem(name));
if (obj.expires === 0) {
return obj.value;
} else {
//判断是否过期
if ((new Date().getTime() - obj.startTime) > obj.expires) {
// 过期 清除掉该项 并如同window.localStorage.getItem(name)一样返回null
window.localStorage.removeItem(name);
return null;
} else {
return obj.value;
}
}
} catch (e) {
if (e.name === 'SyntaxError') {
return obj;
}
}
},
/**
* 同window.localStorage.removeItem(name);
* */
removeItem(name) {
window.localStorage.removeItem(name);
},
/**
* 同window.localStorage.clear();
* */
clear() {
window.localStorage.clear();
}
};

export default localStorageUtils;
1
2
3
4
5
6
{
  "name": "token",
  "value": "775a5ca44e1a45eda50e01e9cf5de472",
  "expires": 1800000,
  "startTime": 1578992165082
}