localStorage设置过期时间

Posted 瑞瑞大人

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了localStorage设置过期时间相关的知识,希望对你有一定的参考价值。

export function getItemKeyList(): Array<string> {
  const keyList = [];
  for (let i = 0; i < localStorage.length; i += 1) {
    const key = localStorage.key(i);
    if (key) {
      keyList.push(`${key}`);
    }
  }
  return keyList;
}

export function clearExpiredKeys() {
  const keyList = getItemKeyList();
  keyList.forEach(key => {
    const match = key.match(/\\|\\|\\|(\\d{13})$/);
    if (match) {
      // const uselessPart = match[0];
      const expiresAt = Number(match[1]);
      if (new Date().getTime() > expiresAt) {
        localStorage.removeItem(key);
      }
    }
  });
}

function clearKeysOf(unwrappedKey: string) {
  const keyList = getItemKeyList();
  const regExp = new RegExp(`${unwrappedKey}\\\\|\\\\|\\\\|`);
  keyList.forEach(fullKey => {
    if (regExp.test(fullKey)) {
      localStorage.removeItem(fullKey);
    }
  });
}

function getTargetFullKey(unwrappedKey: string): string {
  const keyList = getItemKeyList();
  let result = \'\';
  keyList.forEach(fullKey => {
    const regExp = new RegExp(`^${unwrappedKey}\\\\|\\\\|\\\\|`);
    if (
      regExp.test(fullKey)
    ) {
      result = fullKey;
    }
  });
  return result;
}

export function setItem(options: {
  key: string;
  value: string;
  expiresAt?: number;
}): void {
  clearExpiredKeys();
  clearKeysOf(options.key);

  let expiresAtString = \'\';
  if (options.expiresAt) {
    expiresAtString = `${options.expiresAt}`;
    if (expiresAtString.length !== 13) {
      throw new Error(`Invalid expiresAt value: ${expiresAtString}`);
    }
  }

  const fullKey = `${options.key}|||${expiresAtString}`;
  localStorage.setItem(fullKey, options.value);
}

export function getItem(unwrappedKey: string): string|null {
  clearExpiredKeys();
  const targetFullKey = getTargetFullKey(unwrappedKey);
  return localStorage.getItem(targetFullKey);
}

export function removeItem(unwrappedKey: string): void {
  clearExpiredKeys();
  const targetFullKey = getTargetFullKey(unwrappedKey);
  localStorage.removeItem(targetFullKey);
}

  

以上是关于localStorage设置过期时间的主要内容,如果未能解决你的问题,请参考以下文章

localStorage二次封装-----设置过期时间

javascript 可以为sessionStorage的,localStorage的设置过期时间

面试官问:怎么让localStorage像cookie那样有过期时间

localStorage过期策略

javascript本地缓存方案-- 存储对象和设置过期时间

cookiesessionsessionStorage localStorage 区别