统计当前页面的localStorage使用了多少空间

187 阅读1分钟

因为 localStorage 在浏览器中还是经常使用的临时存储数据的一种方式,有时候因为项目可能较为复杂,就需要存储比较多的信息在里面,但是浏览器有限制单个域占用的localStorage是有限制最大5M的,并不是想存多少就存多少的,但是浏览器里面又看不到当前占了多少存储空间,只能看到键值对信息

所以这里就提供一种思路,查看占用了多少空间,还剩多少空间:

function estimateLocalStorageSpace() {
  // 将localStorage中的所有数据转换为字符串并计算长度
  const usedSpaceInBytes = new TextEncoder().encode(JSON.stringify(localStorage)).length;

  // 假设localStorage的最大空间为5MB(5 * 1024 * 1024字节)
  const maxSpaceInBytes = 5 * 1024 * 1024;

  // 计算剩余空间
  const remainingSpaceInBytes = maxSpaceInBytes - usedSpaceInBytes;

  // 将字节转换为更易读的单位(例如KB或MB)
  function formatBytes(bytes) {
    if (bytes < 1024) {
      return `${bytes} B`;
    } else if (bytes < 1024 * 1024) {
      return `${(bytes / 1024).toFixed(2)} KB`;
    } else {
      return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
    }
  }

  // 返回使用空间和剩余空间
  return {
    usedSpace: formatBytes(usedSpaceInBytes),
    remainingSpace: formatBytes(remainingSpaceInBytes),
  };
}

// 使用示例:
const spaceInfo = estimateLocalStorageSpace();
console.log('Used Space:', spaceInfo.usedSpace);
console.log('Remaining Space:', spaceInfo.remainingSpace);

将上述代码复制黏贴到你当前页面的控制台中,回车就可以了: