在HTML5中,加入了一个localStorage特性,这个特性主要是用来作为本地存储来使用的,解决了cookie存储空间不足的问题(cookie中每条cookie的存储空间为4k),localStorage中一般浏览器支持的是5M大小,这个在不同的浏览器中localStorage会有所不同。它只能存储字符串格式的数据,所以最好在每次存储时把数据转换成json格式,取出的时候再转换回来。并且微信小程序不支持cookie,webview中的localStorage数据在小程序进程被杀掉的时候会被清除掉。
<html>
<head>
<title>localStorage</title>
</head>
<body>
<script>
const Storage = {};
Storage.get = function(name) {
return localStorage.getItem(name);
}
Storage.set = function(name, val) {
localStorage.setItem(name, val);
}
Storage.set("status", "OK");
Storage.set("quit", "...");
console.log(Storage.get("status"));
</script>
</body>
</html>
localstorage本身是没有过期机制的,不过我们可以通过其他手段来扩展,使其能够满足我们的数据过期的需求。
Storage.prototype.setStorageWithAge = (key, value, age) => {
if (isNaN(age) || age < 1) throw new Error("age must be a number");
const obj = {
data: value, //存储值
time: Date.now(), //存值时间戳
maxAge: age, //过期时间
};
localStorage.setItem(key, JSON.stringify(obj));
};
Storage.prototype.getStorageWithAge = key => {
const { data, time, maxAge } = JSON.parse(localStorage.getItem(key));
if (time + maxAge < Date.now()) {
localStorage.removeItem(key);
return '';
}
return data;
};
localStorage.setStorageWithAge('amingxiansen', '测试过期时间', 30000);
localStorage.getStorageWithAge('amingxiansen');
设定30s的过期时间,过期之前和过期之后获取到的结果。