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


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

    简介

    说明

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

    问题描述

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

    思路

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

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

    测试结果

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

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

    方案1:封装为函数

    js

    1. /**
    2. * 写入localStorage
    3. * @param key key
    4. * @param value value
    5. * @param expire 超时时间(以秒为单位)
    6. */
    7. function writeExpire(key, value, expire) {
    8. let obj = {
    9. time: new Date().getTime(),
    10. data: value,
    11. expire: expire,
    12. };
    13. let objStr = JSON.stringify(obj);
    14. localStorage.setItem(key, objStr);
    15. }
    16. /**
    17. * 读出localStorage
    18. */
    19. function readExpire(key) {
    20. let value = localStorage.getItem(key);
    21. if (!value || value === "null") {
    22. return value;
    23. }
    24. value = JSON.parse(value);
    25. if (Date.now() - value.time > value.expire * 1000) {
    26. localStorage.removeItem(key);
    27. return null;
    28. }
    29. return value.data;
    30. }

    html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. <script src="LocalStorageUtil.js">script>
    7. head>
    8. <body>
    9. <script>
    10. writeExpire("key1", "value1", 2)
    11. console.log(readExpire("key1"));
    12. sleep(4000).then(() => {
    13. console.log(readExpire("key1"));
    14. })
    15. function sleep(time) {
    16. return new Promise((resolve) => setTimeout(resolve, time));
    17. }
    18. script>
    19. body>
    20. html>

    方案2:封装为对象

    js

    1. export let localStorageUtil = {
    2. /**
    3. * 写入localStorage
    4. * @param key key
    5. * @param value value
    6. * @param expire 超时时间(以秒为单位)
    7. */
    8. writeExpire: function (key, value, expire) {
    9. let obj = {
    10. time: new Date().getTime(),
    11. data: value,
    12. expire: expire,
    13. };
    14. let objStr = JSON.stringify(obj);
    15. localStorage.setItem(key, objStr);
    16. },
    17. /**
    18. * 读出localStorage
    19. */
    20. readExpire: function (key) {
    21. let value = localStorage.getItem(key);
    22. if (!value || value === "null") {
    23. return value;
    24. }
    25. value = JSON.parse(value);
    26. if (Date.now() - value.time > value.expire * 1000) {
    27. localStorage.removeItem(key);
    28. return null;
    29. }
    30. return value.data;
    31. }
    32. }
    33. // export default localStorageUtil;

    html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. head>
    7. <body>
    8. <script type="module">
    9. import {localStorageUtil} from "./LocalStorageUtil.js";
    10. localStorageUtil.writeExpire("key1", "value1", 2)
    11. console.log(localStorageUtil.readExpire("key1"));
    12. sleep(4000).then(() => {
    13. console.log(localStorageUtil.readExpire("key1"));
    14. })
    15. function sleep(time) {
    16. return new Promise((resolve) => setTimeout(resolve, time));
    17. }
    18. script>
    19. body>
    20. html>

    方案3:ES5扩展localStorage

    js

    1. /**
    2. * 写入localStorage
    3. * @param key key
    4. * @param value value
    5. * @param expire 超时时间(以秒为单位)
    6. */
    7. Storage.prototype.writeExpire = (key, value, expire) => {
    8. let obj = {
    9. data: value,
    10. time: Date.now(),
    11. expire: expire
    12. };
    13. //localStorage 设置的值不能是对象,转为json字符串
    14. localStorage.setItem(key, JSON.stringify(obj));
    15. }
    16. /**
    17. * 读出localStorage
    18. */
    19. Storage.prototype.readExpire = key => {
    20. let value = localStorage.getItem(key);
    21. if (!value || value === "null") {
    22. return null;
    23. }
    24. val = JSON.parse(value);
    25. if (Date.now() - val.time > val.expire * 1000) {
    26. localStorage.removeItem(key);
    27. return null;
    28. }
    29. return val.data;
    30. }

    html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. head>
    7. <body>
    8. <script type="module">
    9. import './LocalStorageUtil.js';
    10. localStorage.writeExpire("key1", "value1", 2)
    11. console.log(localStorage.readExpire("key1"));
    12. sleep(4000).then(() => {
    13. console.log(localStorage.readExpire("key1"));
    14. })
    15. function sleep(time) {
    16. return new Promise((resolve) => setTimeout(resolve, time));
    17. }
    18. script>
    19. body>
    20. html>

    方案4:ES6扩展localStorage

    js

    1. class LocalStorageUtil {
    2. constructor() {
    3. this.storage = window.localStorage;
    4. }
    5. /**
    6. * 写入localStorage
    7. * @param key key
    8. * @param value value
    9. * @param expire 超时时间(以秒为单位)
    10. */
    11. writeExpire(key, value, expire) {
    12. let tempObj = {};
    13. tempObj.key = key;
    14. tempObj.value = value;
    15. tempObj.expire = Date.now() + expire * 1000;
    16. this.storage[key] = JSON.stringify(tempObj);
    17. return tempObj;
    18. }
    19. /**
    20. * 读出localStorage
    21. */
    22. readExpire(key) {
    23. let value = localStorage.getItem(key);
    24. if (!value || value === "null") {
    25. return null;
    26. }
    27. let valueObject = JSON.parse(value);
    28. let expire = valueObject["expire"];
    29. if (!expire) {
    30. return valueObject.value;
    31. }
    32. if (Date.now() >= expire) {
    33. this.remove(key);
    34. return null;
    35. }
    36. return valueObject.value
    37. }
    38. remove(key) {
    39. this.storage.removeItem(key);
    40. }
    41. }
    42. export default LocalStorageUtil;

    html

    1. html>
    2. <html lang="en">
    3. <head>
    4. <meta charset="UTF-8">
    5. <title>Titletitle>
    6. head>
    7. <body>
    8. <script type="module">
    9. import LocalStorageUtil from "./LocalStorageUtil.js";
    10. let localStorageUtil = new LocalStorageUtil();
    11. localStorageUtil.writeExpire("key1", "value1", 2)
    12. console.log(localStorageUtil.readExpire("key1"));
    13. sleep(4000).then(() => {
    14. console.log(localStorageUtil.readExpire("key1"));
    15. })
    16. function sleep(time) {
    17. return new Promise((resolve) => setTimeout(resolve, time));
    18. }
    19. script>
    20. body>
    21. html>

  • 相关阅读:
    MAC终端美化
    TensorFlow学习笔记--(2)张量的常用运算函数
    Leetcode21:合并两个有效链表
    SAP ABAP 基本运算(加减乘除取余 四舍五入 向上下取整) 问题:在使用`DIV`和 `/` 出现的差异以及错误
    Docker基本配置及使用
    nlp之加载电商评论集
    fatal: protocol ‘“https‘ is not supported
    Qt6 mathgl数学函数绘图
    Java项目:SSM农产品朔源管理系统
    智慧工地安全施工实时监测系统解决方案
  • 原文地址:https://blog.csdn.net/feiying0canglang/article/details/128420838