如何给 LocalStorage 设置过期时间
wangjing013 opened this issue · comments
wangjing commented
如何给 LocalStorage 设置过期时间
如果熟悉浏览器的 localStorage object ,你知道它没有提供配置过期时间的选项。
现希望给 localStorage
设置过期时间,怎么做 ?
具体思路可借鉴 cookie
实现过期的思路。我们知道通常给 cookie
设置过期时间,是通过 Set-Cookie
响应头给它设置一系列的参数,其中一种实现方式就是指定 Expires
属性,用于指定其过期时间。
对应到 localStorage 中,大概的实现思路:
- 在存储值的时候,指定一个过期时间
- 当取值的时候,拿当前时间与存储时指定的过期时间进行比较
- 如果当前时间大于过期时间,则返回
null
并从localStorage
中移除该选项。否则返回存储的值。
存储项指定过期时间
function setWithExpiry(key, value, ttl) {
const now = new Date()
const item = {
value: value,
expiry: now.getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
上面创建一个新的对象,新的对象中包含两个属性 value
对应原始值,expiry
表示过期时间。
获取存储项
在存储的时候通过新的对象给原始值的进行包裹,并指定过期时间。那么在取值则进行对应拆包操作及过期时间的检查。 具体实现如下:
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
// 如果 item 不存在,返回 null
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
// 比较过期时间和当前时间
if (now.getTime() > item.expiry) {
// 从 localStorage 中移除并返回 null
localStorage.removeItem(key)
return null
}
return item.value
}
完整的案例
通过一个简单的案例来使用上面的两个方法:
Set
按钮存储文本框中值,并指定过期时间为 5 秒。Get
按钮用来获取值,并把值添加页面中并展示。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>LocalStorage Expiry Example</title>
</head>
<body>
<button id="btn-set">Set</button>
<input id="input-set" />
<br /><br />
<button id="btn-get">Get</button>
<div>Value: <span id="value"></span></div>
<script>
const btnSet = document.getElementById("btn-set")
const btnGet = document.getElementById("btn-get")
const inputSet = document.getElementById("input-set")
const valueDisplay = document.getElementById("value")
btnSet.addEventListener("click", () => {
setWithExpiry("myKey", inputSet.value, 5000)
})
btnGet.addEventListener("click", () => {
const value = getWithExpiry("myKey")
valueDisplay.innerHTML = value
})
function setWithExpiry(key, value, ttl) {
const now = new Date()
const item = {
value: value,
expiry: now.getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
if (now.getTime() > item.expiry) {
localStorage.removeItem(key)
return null
}
return item.value
}
</script>
</body>
</html>