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>
相关推荐
忧郁的蛋~5 小时前
.NET异步编程中内存泄漏的终极解决方案
开发语言·前端·javascript·.net
水月wwww5 小时前
vue学习之组件与标签
前端·javascript·vue.js·学习·vue
合作小小程序员小小店5 小时前
web网页开发,在线%商城,电商,商品购买%系统demo,基于vscode,apache,html,css,jquery,php,mysql数据库
开发语言·前端·数据库·mysql·html·php·电商
顾安r5 小时前
11.8 脚本网页 塔防游戏
服务器·前端·javascript·游戏·html
草莓熊Lotso5 小时前
C++ 方向 Web 自动化测试实战:以博客系统为例,从用例到报告全流程解析
前端·网络·c++·人工智能·后端·python·功能测试
fruge5 小时前
Canvas/SVG 冷门用法:实现动态背景与简易数据可视化
前端·信息可视化
一 乐6 小时前
旅游|内蒙古景点旅游|基于Springboot+Vue的内蒙古景点旅游管理系统设计与实现(源码+数据库+文档)
开发语言·前端·数据库·vue.js·spring boot·后端·旅游
驯狼小羊羔6 小时前
学习随笔-require和import
前端·学习
excel6 小时前
🚀 从 GPT-5 流式输出看现代前端的流式请求机制(Koa 实现版)
前端
凸头6 小时前
Spring Boot接收前端参数的注解总结
前端·spring boot·后端