设置localStorage的过期时间

 1 function setLocalStorage(key, value) {
 2     var curtime = new Date().getTime(); // 获取当前时间 ,转换成JSON字符串序列 
 3     var valueDate = JSON.stringify({
 4         val: value,
 5         timer: curtime
 6     });
 7     try {
 8         localStorage.setItem(key, valueDate);
 9     } catch(e) {
10         /*if(e.name === 'QUOTA_EXCEEDED_ERR' || e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
11             console.log("Error: 本地存储超过限制");
12             localStorage.clear();
13         } else {
14             console.log("Error: 保存到本地存储失败");
15         }*/
16         // 兼容性写法
17         if(isQuotaExceeded(e)) {
18             console.log("Error: 本地存储超过限制");
19             localStorage.clear();
20         } else {
21             console.log("Error: 保存到本地存储失败");
22         }
23     }
24 }
25 
26 function isQuotaExceeded(e) {
27     var quotaExceeded = false;
28     if(e) {
29         if(e.code) {
30             switch(e.code) {
31                 case 22:
32                     quotaExceeded = true;
33                     break;
34                 case 1014: // Firefox 
35                     if(e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
36                         quotaExceeded = true;
37                     }
38                     break;
39             }
40         } else if(e.number === -2147024882) { // IE8 
41             quotaExceeded = true;
42         }
43     }
44     return quotaExceeded;
45 }
46 
47 function getLocalStorage(key) {
48     var exp = 60 * 60 * 24; // 一天的秒数
49     if(localStorage.getItem(key)) {
50         var vals = localStorage.getItem(key); // 获取本地存储的值 
51         var dataObj = JSON.parse(vals); // 将字符串转换成JSON对象
52         // 如果(当前时间 - 存储的元素在创建时候设置的时间) > 过期时间 
53         var isTimed = (new Date().getTime() - dataObj.timer) > exp;
54         if(isTimed) {
55             console.log("存储已过期");
56             localStorage.removeItem(key);
57             return null;
58         } else {
59             var newValue = dataObj.val;
60         }
61         return newValue;
62     } else {
63         return null;
64     }
65 }
66 
67 setLocalStorage('name', 'hello, world');
68 var localKey = getLocalStorage('name');
69 console.log(localKey);

 

posted @ 2018-08-27 10:22  幺丸  阅读(...)  评论(...编辑  收藏