sessionStorage报异常Failed to execute 'setItem' on 'Storage'...解决办法

本文介绍了一种处理sessionStorage存储容量超限的方法,通过定义前缀筛选特定缓存,并在容量不足时按缓存时间删除最早存储的对象,确保数据正常存储。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用sessionStorage超过大小限制

Failed to execute 'setItem' on 'Storage': Setting the value of 'feature' exceeded the quota.

const addSessionStorage = (key, storeObj) => {
  //定义一个前缀,表示只删除自己定义的缓存
  const cachePrefix = 'SERVICE_QR_';
  // sessionStorage对大小是有限制的,所以要进行try catch
  // 500KB左右的东西保存起来就会令到Resources变卡
  // 2M左右就可以令到Resources卡死,操作不了
  // 5M就到了Chrome的极限
  // 超过之后会抛出如下异常:
  // DOMException: Failed to execute 'setItem' on 'Storage': Setting the value of 'basket-http://file.com/ykq/wap/v3Templates/timeout/timeout/large.js' exceeded the quota
  try {
    sessionStorage.setItem(cachePrefix + key, JSON.stringify(storeObj));
  } catch (e) {
    // sessionStorage容量不够,根据保存的时间删除已缓存到 sessionStorage
    if (e.name.toUpperCase().indexOf('QUOTA') >= 0) {
      let item;
      const tempArr = [];
      // 先把所有的缓存对象来出来,放到 tempArr 里
      
      for (item in sessionStorage) {
        if (item.indexOf(cachePrefix) === 0) {
          tempArr.push(JSON.parse(sessionStorage[item]));
        }
      }
      // 如果有缓存对象
      if (tempArr.length) {
        // 按缓存时间升序排列数组
        tempArr.sort((a, b) => a.stamp - b.stamp);
        // 删除缓存时间最早的
        sessionStorage.removeItem(tempArr[0].key);
        // 删除后在再添加,利用递归完成
        addSessionStorage(key, storeObj);
      }
    }
  }
};

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

张音乐

请我喝杯咖啡吧

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值