获取缓存大小与清除 Web 缓存 - 鸿蒙 HarmonyOS Next

针对浏览器 Web 组件清除缓存相关,具体实现如下 code 实例所示:

/*公共方法类*/
export class PublicUtils {
  /*获取缓存大小*/
  static async getCacheSize(): Promise<number> {
    try {
      let bundleStats = await storageStatistics.getCurrentBundleStats()
      let size = bundleStats.cacheSize / 1024 / 1024
      return Math.round(size)
    } catch (e) {
      console.error(`[PublicUtils] - 获取缓存大小: ErrorCode: ${e.code},  Message: ${e.message}`);
      return 0
    }
  }


  /*清除 Web 浏览器缓存(单个 Web 组件) Rom & Ram*/
  static clearWebCache(webView: web_webview.WebviewController, state: boolean): string {
    if (webView) {
      if (state) { // Rom & Ram: 本地 loc 和 缓存
        try {
          webView.removeCache(true);
          return '浏览器缓存清除成功';
        } catch (error) {
          let e: business_error.BusinessError = error as business_error.BusinessError;
          console.error(`[PublicUtils] - 清除缓存: ErrorCode: ${e.code},  Message: ${e.message}`);
          return '浏览器缓存清除失败:' + e.message;
        }
      } else { // Ram: 仅缓存
        try {
          webView.removeCache(false);
          return '浏览器缓存清除成功';
        } catch (error) {
          let e: business_error.BusinessError = error as business_error.BusinessError;
          console.error(`[PublicUtils] - 清除缓存: ErrorCode: ${e.code},  Message: ${e.message}`);
          return '浏览器缓存清除失败:' + e.message;
        }
      }
    } else {
      return '浏览器缓存清除失败: 无效的组件';
    }
  }
}
import { PublicUtils } from '../utils/PublicUtils'

// 获取缓存
PublicUtils.getCacheSize().then((res) => {
  console.log('[获取缓存]: ', res)
  this.detail = res.toString()
})

// 清除缓存
PublicUtils.clearWebCache(this.webView, state);

以上便是此次分享的全部内容,希望能对大家有所帮助!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值