This post will explain how to implement expiry times for items stored in the browsers localStorage.
If you’re familiar with the browsers localStorage object, you know that there’s no provision for providing an expiry time. However, we can use Javascript to add a TTL (Time to live) to invalidate items in localStorage after a certain period of time elapses.
If you just want to see a working example, you can skip to the last section
Here’s an overview of how we can achieve this:
null
and remove the item from storage, otherwise, return the original information.Let’s see how we can implement this using Javascript.
Let’s create a function that allows you to set a key in localStorage, and store the expiry time along with it:
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 expireconst item = {value: value,expiry: Time() + ttl,}localStorage.setItem(key, JSON.stringify(item))
}
Here, we create a new object with the original value as well as the expiry time, which is calculated by adding the TTL value in milliseconds to the current millisecond time.
We convert the item to a JSON string, since we can only store strings in localStorage.
We can verify the expiry time while retrieving items from the store:
function getWithExpiry(key) {const itemStr = Item(key)// if the item doesn't exist, return nullif (!itemStr) {return null}const item = JSON.parse(itemStr)const now = new Date()// compare the expiry time of the item with the current timeif (Time() > piry) {// If the item is expired, delete the item from storage// and veItem(key)return null}return item.value
}
Here we are expiring the item “lazily” - which is to say we check the expiry condition only when we want to retrieve it from storage. If the item has, in-fact expired, we remove the key from localStorage.
Let’s create a small HTML page which demonstrates how we can use localStorage with expiry:
setWithExpiry
and getWithExpiry
functions defined in the script<!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 = ElementById("btn-set")const btnGet = ElementById("btn-get")const inputSet = ElementById("input-set")const valueDisplay = ElementById("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()// `item` is an object which contains the original value// as well as the time when it's supposed to expireconst item = {value: value,expiry: Time() + ttl,}localStorage.setItem(key, JSON.stringify(item))}function getWithExpiry(key) {const itemStr = Item(key)// if the item doesn't exist, return nullif (!itemStr) {return null}const item = JSON.parse(itemStr)const now = new Date()// compare the expiry time of the item with the current timeif (Time() > piry) {// If the item is expired, delete the item from storage// and veItem(key)return null}return item.value}</script></body>
</html>
本文发布于:2024-02-05 08:02:57,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170727892364767.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |