JS--localStorage设置过期时间的方案(有示例)

原文网址:JS--localStorage设置过期时间的方案(有示例)_IT利刃出鞘的博客-CSDN博客

简介

说明

本文介绍如何使用localStorage设置数据的过期时间。

问题描述

localStorage是不支持设置过期时间的,cookie虽然支持设置过期时间但它存的数据量很小。所以在需要存一些带过期时间的数据时,就要手写工具来实现。

思路

存数据时:将value封装到一个对象里,这个对象里额外加一个过期时间。

读数据时:如果当前时间超过了过期时间,则返回null或者空对象;否则返回value。

测试结果

如下几种方案的测试结果都是一样的:

第一次获取时获取到了数据;4秒后数据过期了,再获取时成了null。

方案1:封装为函数

js

javascript 复制代码
/**
 * 写入localStorage
 * @param key    key
 * @param value  value
 * @param expire 超时时间(以秒为单位)
 */
function writeExpire(key, value, expire) {
    let obj = {
        time: new Date().getTime(),
        data: value,
        expire: expire,
    };
    let objStr = JSON.stringify(obj);
    localStorage.setItem(key, objStr);
}

/**
 * 读出localStorage
 */
function readExpire(key) {
    let value = localStorage.getItem(key);
    if (!value || value === "null") {
        return value;
    }

    value = JSON.parse(value);
    if (Date.now() - value.time > value.expire * 1000) {
        localStorage.removeItem(key);
        return null;
    }

    return value.data;
}

html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <script src="LocalStorageUtil.js"></script>
</head>
<body>
<script>
    writeExpire("key1", "value1", 2)
    console.log(readExpire("key1"));
    sleep(4000).then(() => {
        console.log(readExpire("key1"));
    })

    function sleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }
</script>
</body>
</html>

方案2:封装为对象

js

javascript 复制代码
export let localStorageUtil = {
    /**
     * 写入localStorage
     * @param key    key
     * @param value  value
     * @param expire 超时时间(以秒为单位)
     */
    writeExpire: function (key, value, expire) {
        let obj = {
            time: new Date().getTime(),
            data: value,
            expire: expire,
        };
        let objStr = JSON.stringify(obj);
        localStorage.setItem(key, objStr);
    },

    /**
     * 读出localStorage
     */
    readExpire: function (key) {
        let value = localStorage.getItem(key);
        if (!value || value === "null") {
            return value;
        }

        value = JSON.parse(value);
        if (Date.now() - value.time > value.expire * 1000) {
            localStorage.removeItem(key);
            return null;
        }

        return value.data;
    }
}

// export default localStorageUtil;

html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="module">
    import {localStorageUtil} from "./LocalStorageUtil.js";

    localStorageUtil.writeExpire("key1", "value1", 2)
    console.log(localStorageUtil.readExpire("key1"));
    sleep(4000).then(() => {
        console.log(localStorageUtil.readExpire("key1"));
    })

    function sleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }
</script>
</body>
</html>

方案3:ES5扩展localStorage

js

javascript 复制代码
/**
 * 写入localStorage
 * @param key    key
 * @param value  value
 * @param expire 超时时间(以秒为单位)
 */
Storage.prototype.writeExpire = (key, value, expire) => {
    let obj = {
        data: value,
        time: Date.now(),
        expire: expire
    };
    //localStorage 设置的值不能是对象,转为json字符串
    localStorage.setItem(key, JSON.stringify(obj));
}

/**
 * 读出localStorage
 */
Storage.prototype.readExpire = key => {
    let value = localStorage.getItem(key);
    if (!value || value === "null") {
        return null;
    }

    val = JSON.parse(value);
    if (Date.now() - val.time > val.expire * 1000) {
        localStorage.removeItem(key);
        return null;
    }
    return val.data;
}

html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="module">
    import './LocalStorageUtil.js';

    localStorage.writeExpire("key1", "value1", 2)

    console.log(localStorage.readExpire("key1"));
    sleep(4000).then(() => {
        console.log(localStorage.readExpire("key1"));
    })

    function sleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }
</script>
</body>
</html>

方案4:ES6扩展localStorage

js

javascript 复制代码
class LocalStorageUtil {
    constructor() {
        this.storage = window.localStorage;
    }

    /**
     * 写入localStorage
     * @param key    key
     * @param value  value
     * @param expire 超时时间(以秒为单位)
     */
    writeExpire(key, value, expire) {
        let tempObj = {};
        tempObj.key = key;
        tempObj.value = value;
        tempObj.expire = Date.now() + expire * 1000;
        this.storage[key] = JSON.stringify(tempObj);
        return tempObj;
    }

    /**
     * 读出localStorage
     */
    readExpire(key) {
        let value = localStorage.getItem(key);
        if (!value || value === "null") {
            return null;
        }

        let valueObject = JSON.parse(value);
        let expire = valueObject["expire"];
        if (!expire) {
            return valueObject.value;
        }

        if (Date.now() >= expire) {
            this.remove(key);
            return null;
        }

        return valueObject.value
    }

    remove(key) {
        this.storage.removeItem(key);
    }
}

export default LocalStorageUtil;

html

html 复制代码
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<script type="module">
    import LocalStorageUtil from "./LocalStorageUtil.js";

    let localStorageUtil = new LocalStorageUtil();

    localStorageUtil.writeExpire("key1", "value1", 2)

    console.log(localStorageUtil.readExpire("key1"));
    sleep(4000).then(() => {
        console.log(localStorageUtil.readExpire("key1"));
    })

    function sleep(time) {
        return new Promise((resolve) => setTimeout(resolve, time));
    }
</script>
</body>
</html>
相关推荐
_AaronWong16 小时前
Electron 实现仿豆包划词取词功能:从 AI 生成到落地踩坑记
前端·javascript·vue.js
cxxcode16 小时前
I/O 多路复用:从浏览器到 Linux 内核
前端
用户54330814419416 小时前
AI 时代,前端逆向的门槛已经低到离谱 — 以 Upwork 为例
前端
JarvanMo16 小时前
Flutter 版本的 material_ui 已经上架 pub.dev 啦!快来抢先体验吧。
前端
JohnYan16 小时前
工作笔记-CodeBuddy应用探索
javascript·ai编程·aiops
恋猫de小郭17 小时前
AI 可以让 WIFI 实现监控室内人体位置和姿态,无需摄像头?
前端·人工智能·ai编程
哀木17 小时前
给自己整一个 claude code,解锁编程新姿势
前端
程序员鱼皮17 小时前
GitHub 关注突破 2w,我总结了 10 个涨星涨粉技巧!
前端·后端·github
UrbanJazzerati17 小时前
Vue3 父子组件通信完全指南
前端·面试
是一碗螺丝粉17 小时前
5分钟上手LangChain.js:用DeepSeek给你的App加上AI能力
前端·人工智能·langchain