LocalStorage will always be stored in the browser unless it is manually cleared. However, in many cases we may need localStorage to have an expiration time. For example, if we save the user authentication token on the client, it will be valid within 1 week, and if it exceeds one week, Log in again, then how to realize this requirement?
You must know that localStorage itself does not provide an expiration mechanism. In this case, we can only implement it ourselves. We can directly add such a method to its prototype.
Storage.prototype.setExpire=(key,value,expire) =>{ };Storage.setExpire(key,value,expire);To expire, the time must be recorded. Our idea is to record the current time when setting the value, and then when obtaining the value, judge whether the difference between the current time and the previous time is within a certain range. If it is outside the range, clear it. the current item and returns null
To add time to a value, a format must be defined
Storage.prototype.setExpire=(key, value, expire) =>{ let obj={ data:value, time:Date.now(), expire:expire }; localStorage.setItem(key,JSON.stringify(obj)) ;}Includes the following 3 fields
Because the value set by localStorage cannot be an object, the JSON.stringify method is used here to convert it into a string, and it must be converted back when used.
Then we add a method to obtain
Storage.prototype.getExpire= key =>{ let val =localStorage.getItem(key); if(!val){ return val; } val =JSON.parse(val); if(Date.now()-val.time >val.expire){ localStorage.removeItem(key); return null; } return val.data;}We can test it first
localStorage.setExpire(token,'xxxxxx',5000);window.setInterval(()=>{ console.log(localStorage.getExpire(token));},1000)Essentially, our idea is not to clean up expired items regularly, but to determine whether they are expired when they are obtained, and then clear the items if they are expired.
The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope everyone will support VeVb Wulin Network.