LocalStorage设置过期时间

  • 封装初衷,无非就是想给LocalStorage设置一个过期的时间并且设置值的时候,可以设置任何值
  • 目前这个包放在npm库中,下载npm install happyLocalStorage
  • 想要达到的效果,本方法要完全实现LocalStorage的功能,并且实现类似cookie的过期时间和设置任何值!
  • cookie过期时间特点:cookie的过期时间,无论是否打开浏览器,到了过期的时间节点就会删除过期的cookie
  • cookie的过期时间无非也就是两种情况
    • 第一:一直开着浏览器,没到过期时间点,数据一直有效,到某个时间点自动清除过期的cookie
    • 第二:设置完cookie关闭浏览器,等到第二次打开,没到过期时间点,数据一直有效,到某个时间点自动清除过期的cookie
  • 本函数实现
    • 第一: 一直开着浏览器,没到过期时间点,数据一直有效,到某个时间点自动清除过期的LocalStorage
    • 第二:用户在有效时间内关闭浏览器又打开,那么会在初始化方法中开启一个定时器,到时间就会删除该条数据
    • 第三:本函数在setLocalStorage方法中,setValue可以是任何值,不需要再进行手动JSON.stringify,同样再getLocalStorage方法中,也不需要JSON.parse
    • 注意点:本函数一共支持四个方法
      • setLocalStorage 设置
      • getLocalStorage 获取
      • delLocalStorage 删除
      • delAllLocalStorage 删除全部
      • 其中setLocalStorage/getLocalStorage这两个方法是配套的,我在setLocalStorage中内置了JSON.stringify,在getLocalStorage中内置了JSON.parse,所以,不要使用localStorage.setItem的方法设置,然后用getLocalStorage来获取,虽然我做了错误过滤,但是,很有可能出现的结果和当初设置的不一致就是JSON/parse/stringify的问题。反之亦然
class happyLocalStorage {
  constructor() {}

  introduce(){
    console.log(`
      1.本库提供设置、获取、删除、删除全部四个方法
        1.1-hl.setLocalStorage-使用详情请看hl.setLocalStorageIntroduce()
        1.2-hl.getLocalStorage('字符串类型')
        1.3-hl.delLocalStorage('字符串类型')
        1.4-hl.delAllLocalStorage()
    `);
  }

  judgeDataType(val) {//判断数据类型
    return Object.prototype.toString.call(val).slice(8, -1);
  }

  _delLocalStorage(getName) {//删除已经过期的LocalStorage
    let getLocalStorageValue = localStorage.getItem(getName);

    try {
      getLocalStorageValue = JSON.parse(getLocalStorageValue);
    } catch (error) {
      getLocalStorageValue = getLocalStorageValue;
    };
    
    if (this.judgeDataType(getLocalStorageValue) == "Object" && !!getLocalStorageValue._effectiveTime) {
      let effectiveTime = new Date(getLocalStorageValue._effectiveTime).getTime();
      if (new Date().getTime() - effectiveTime > 0) {//当前时间戳超过了有效时间戳-过期
        localStorage.removeItem(getName);
      }else{
        this[getName]=setTimeout(()=>{//开启定时器
          localStorage.removeItem(getName);
        },effectiveTime-new Date().getTime())
      }
    }
  }

  _initLocalStorage() {//初始化
    let len = localStorage.length;  // 获取长度
    let arr = [];
    if (len > 0) {
      for (let i = 0; i < len; i++) {
        let getKey = localStorage.key(i);
        arr.push(getKey);
      };
      arr.forEach(item => {//这里面存储的一定是有值的LocalStorage
        this._delLocalStorage(item)
      })
    };
  }

  /**
   * setLocalStorage使用说明
   */
  setLocalStorageIntroduce(){
    console.log(
      `
        1.不输入第三个参数或者输入null,就是一个正常的localStorage,支持设置复杂数据类型
        2.第三个参数为{},默认的过期时间就是15分钟
        3.第三个参数为{timeSize:"'年'/'月'/'日'/'时'/'分'/'秒'",timeSize:数字类型}
        4.例子-hl.setLocalStorage(name,{name:'张三},{timeSize:'分',timeSize:20})
      `
    )
  }
  /**
   * 功能:设置LocalStorage的值和过期时间
   * @param {*} setName:设置的名称 string
   * @param {*} setValue:设置的值 any
   * @param {*} expiresObj:过期时间 {}/{timeScale:'秒/分/时 日/月/年',timeSize:number} 
   */
  setLocalStorage(setName, setValue, expiresObj = null) {
    if (expiresObj == null) {//如果用户不输入第三个参数或者输入null,就是一个正常的localStorage
      let JSONStringify = JSON.stringify(setValue);
      localStorage.setItem(setName, JSONStringify);
    } else {//这里面输出的一定是一个已经JSON.stringify好的对象
      if (Object.keys(expiresObj).length == 0) {//输入的是一个空对象 设置默认过期时间:15分钟
        let newDate = new Date();//获取当前的时间对象
        let nowTimeStamp = newDate.getTime();//获取当前时间对象的时间戳
        nowTimeStamp += (1000 * 60 * 15);//将现在的时间戳和设置过期时间期间产生的时间戳 累加
        newDate.setTime(nowTimeStamp);//将累加的时间戳设置到过期时间上
        expiresObj[setName] = setValue;//将传入的名称和值以key/value的形式挂载到expiresObj上
        expiresObj._effectiveTime = newDate;//将累加好的时间挂载到expiresObj
        let stringifyExpiresObj = JSON.stringify(expiresObj);//将expiresObj转成字符串
        localStorage.setItem(setName, stringifyExpiresObj);//设置localStorage
        
        clearTimeout(this[setName])
        this[setName]=setTimeout(() => {//页面一直开着,到了过期时间就删掉
          this.delLocalStorage(setName);
        }, 1000 * 60 * 15);

      } else {//输入的不是空对象
        let newDate = new Date();
        let nowTimeStamp = newDate.getTime();
        let timeout = null;
        switch (expiresObj.timeScale) {//判断时间规格
          case '秒':
            nowTimeStamp += (1000 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * parseFloat(expiresObj.timeSize));
            break;
          case '分':
            nowTimeStamp += (1000 * 60 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * parseFloat(expiresObj.timeSize));
            break;
          case '时':
            nowTimeStamp += (1000 * 60 * 60 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * parseFloat(expiresObj.timeSize));
            break;
          case '日':
            nowTimeStamp += (1000 * 60 * 60 * 24 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * 24 * parseFloat(expiresObj.timeSize));
            break;
          case '月':
            nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * 24 * 30 * parseFloat(expiresObj.timeSize));
            break;
          case '年':
            nowTimeStamp += (1000 * 60 * 60 * 24 * 30 * 12 * parseFloat(expiresObj.timeSize));
            timeout = (1000 * 60 * 60 * 24 * 30 * 12 * parseFloat(expiresObj.timeSize));
            break;

          default:
            break;
        }
        newDate.setTime(nowTimeStamp);//将累加的时间戳设置到过期时间上
        expiresObj[setName] = setValue;
        expiresObj._effectiveTime = newDate;
        let stringifyExpiresObj = JSON.stringify(expiresObj);
        localStorage.setItem(setName, stringifyExpiresObj);

        clearTimeout(this[setName])
        this[setName]=setTimeout(() => {
          this.delLocalStorage(setName);
        }, timeout);
      }
    }
  }

  /**
   * 功能:获取LocalStorage的值
   * @param {*} getName:获取的名称
   */
  getLocalStorage(getName) {
    let getLocalStorageValue = localStorage.getItem(getName);

    try {
      getLocalStorageValue = JSON.parse(getLocalStorageValue);
    } catch (error) {
      getLocalStorageValue = getLocalStorageValue;
    };

    if (this.judgeDataType(getLocalStorageValue) == "Object" && !!getLocalStorageValue._effectiveTime) {
      let effectiveTime = new Date(getLocalStorageValue._effectiveTime).getTime();//获取当初设置的时候的过期时间时间戳
      if (new Date().getTime() - effectiveTime < 0) {//如果当前的时间戳<当初设置的时候的过期时间时间戳 证明:没过期
        return getLocalStorageValue[getName];
      } else {//过期
        localStorage.removeItem(getName);
        return null;
      }
    } else {
      return getLocalStorageValue;
    }
  }

  delLocalStorage(name) {//删除指定的LocalStorage
    if(this.judgeDataType(name) === "String"){
      localStorage.removeItem(name);
    }else{
      console.error(`${name}的类型不是字符串,请输入字符串...`);
    }
  }

  delAllLocalStorage() {//删除全部的LocalStorage
    localStorage.clear();
  }
}

let hl = new happyLocalStorage();
hl._initLocalStorage();

export {
  hl
}
  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值