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>
相关推荐
临枫541几秒前
Nuxt3封装网络请求 useFetch & $fetch
前端·javascript·vue.js·typescript
酷酷的威朗普1 分钟前
医院绩效考核系统
javascript·css·vue.js·typescript·node.js·echarts·html5
前端每日三省2 分钟前
面试题-TS(八):什么是装饰器(decorators)?如何在 TypeScript 中使用它们?
开发语言·前端·javascript
小刺猬_9852 分钟前
(超详细)数组方法 ——— splice( )
前端·javascript·typescript
契机再现3 分钟前
babel与AST
javascript·webpack·typescript
渊兮兮3 分钟前
Vue3 + TypeScript +动画,实现动态登陆页面
前端·javascript·css·typescript·动画
鑫宝Code4 分钟前
【TS】TypeScript中的接口(Interface):对象类型的强大工具
前端·javascript·typescript
和你一起去月球4 分钟前
TypeScript - 函数(下)
javascript·git·typescript
_Legend_King10 分钟前
vue3 + elementPlus 日期时间选择器禁用未来及过去时间
javascript·vue.js·elementui
爱吃青椒不爱吃西红柿‍️11 分钟前
华为ASP与CSP是什么?
服务器·前端·数据库