获取缓存大小与清除 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);

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

相关推荐
Mahir0820 小时前
Redis 与 MySQL 数据同步:一致性保证的完整解决方案
数据库·redis·mysql·缓存·面试·数据一致性
leon_teacher20 小时前
HarmonyOS 6 ArkUI 实战:用 Tabs 与 Shape Path 手写凹槽凸起底部导航栏
华为·harmonyos
梦想不只是梦与想21 小时前
鸿蒙与 H5 通信使用的方法及原理
harmonyos·鸿蒙·webview
多加点辣也没关系1 天前
Redis 的安装(详细教程)
数据库·redis·缓存
数据库小学妹1 天前
数据库连接池避坑指南:告别“连接超时”与“资源耗尽”,让系统跑得更快!
数据库·redis·sql·mysql·缓存·dba
坚果派·白晓明1 天前
【鸿蒙PC三方库移植适配框架解读系列】第一篇:Lycium C/C++ 三方库适配 — 概述与环境配置
c语言·开发语言·c++·harmonyos·开源鸿蒙·三方库·c/c++三方库
小雨青年1 天前
鸿蒙 HarmonyOS 6 | Pura X Max 鸿蒙原生适配 04:开合切换后的选中状态保持
华为·harmonyos
阿钱真强道1 天前
22 鸿蒙LiteOS 互斥锁(Mutex)实战教程:多任务共享资源保护
harmonyos·鸿蒙·互斥·rk·liteos·瑞芯微·rk2206
大师兄66681 天前
HarmonyOS 卡片 UI 三种玩法:普通卡片、动效卡片、Canvas 卡片
harmonyos·arkts·formkit·动效卡片·canvas卡片
环流_1 天前
Redis中string类型的应用场景
数据库·redis·缓存