通用:项目搭建之session设置过期时间

1. session设置过期时间

 1 const webStorage = {
 2     getItem(storageType, key) {
 3         if (!['sessionStorage', 'localStorage'].includes(storageType)) {
 4             return null;
 5         }
 6 
 7         const storeData = window[storageType].getItem(key);
 8         if (!storeData) {
 9             return null;
10         }
11 
12         const parsedData = JSON.parse(storeData);
13         const currentTimestamp = new Date().getTime();
14 
15         if (currentTimestamp - parsedData.timestamp <= parsedData.expire) {
16             return parsedData.value;
17         } else {
18             window[storageType].removeItem(key);
19         }
20 
21         return null;
22     },
23 
24     /**
25      * @param {*} key 保存数据的key
26      * @param {*} value 保存的数据
27      * @param {*} expire 过期时间,默认为1分钟
28      */
29     setItem(storageType, key, value, expire = 60000) {
30         if (!['sessionStorage', 'localStorage'].includes(storageType)) {
31             return;
32         }
33 
34         const obj = {
35             value: value,
36             expire: expire,
37             timestamp: new Date().getTime()
38         }
39 
40         const stringfiedData = JSON.stringify(obj);
41         window[storageType].setItem(key, stringfiedData);
42     }
43 }
View Code

粘贴自:https://blog.csdn.net/qq_26822029/article/details/125107941

posted @ 2022-09-08 13:55  lxq3280  阅读(38)  评论(0)    收藏  举报