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

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

TypeScript 复制代码
/*公共方法类*/
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 '浏览器缓存清除失败: 无效的组件';
    }
  }
}
TypeScript 复制代码
import { PublicUtils } from '../utils/PublicUtils'

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

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

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

相关推荐
TT_Close2 小时前
【Flutter×鸿蒙】debug 包也要签名,这点和 Android 差远了
android·flutter·harmonyos
TT_Close18 小时前
【Flutter×鸿蒙】FVM 不认鸿蒙 SDK?4步手动塞进去
flutter·swift·harmonyos
hqk19 小时前
鸿蒙项目实战:手把手带你实现 WanAndroid 布局与交互
android·前端·harmonyos
TT_Close20 小时前
【Flutter×鸿蒙】一个"插队"技巧,解决90%的 command not found
flutter·harmonyos
Hcourage2 天前
鸿蒙工程获取C/C++代码覆盖
harmonyos
二流小码农2 天前
鸿蒙开发:上传一张参考图片便可实现页面功能
android·ios·harmonyos
万少3 天前
HarmonyOS 开发必会 5 种 Builder 详解
前端·harmonyos
Huang兄3 天前
鸿蒙-List和Grid拖拽排序:仿微信小程序删除效果
harmonyos·arkts·arkui
anyup4 天前
🔥2026最推荐的跨平台方案:H5/小程序/App/鸿蒙,一套代码搞定
前端·uni-app·harmonyos
Ranger09294 天前
鸿蒙开发新范式:Gpui
rust·harmonyos