Development
세션스토리지 만료시간 설정 방법
유후(yufu)
2023. 2. 16. 01:09
반응형
1. 세션스토리지에 정보와 만료시간 저장
function setWithExpiry(key, value, ttl) {
const now = new Date()
// `item` is an object which contains the original value
// as well as the time when it's supposed to expire
const item = {
value: value,
expiry: now.getTime() + ttl,
}
localStorage.setItem(key, JSON.stringify(item))
}
또는 다음과 같이 개별적으로 저장할 수 있다.
window.sessionStorage.setItem(key, value);
window.sessionStorage.setItem(key, expiry);
2. 스토리지에 저장된 정보 가져오기
스토리지에 저장된 정보를 조회하여 현재시간과 만료시간을 비교한다.
function getWithExpiry(key) {
const itemStr = localStorage.getItem(key)
// if the item doesn't exist, return null
if (!itemStr) {
return null
}
const item = JSON.parse(itemStr)
const now = new Date()
// compare the expiry time of the item with the current time
if (now.getTime() > item.expiry) {
// If the item is expired, delete the item from storage
// and return null
localStorage.removeItem(key)
return null
}
return item.value
}
반응형