鸿蒙 Webview组件使用说明(ArkWeb)

2025-06-28 13:15:43
106次阅读
0个评论

Webview组件使用说明(ArkWeb)

前言

在鸿蒙应用开发中,嵌入网页内容是常见需求。ArkWeb(方舟Web)提供了强大的Webview组件,方便开发者在应用内集成网页浏览、H5页面交互等功能。本文结合实际开发经验,介绍Webview的核心用法和常见问题,帮助大家快速上手。

功能说明

Webview组件主要功能如下:

  • 支持在应用内嵌入网页内容
  • 提供WebviewController进行页面控制
  • 支持webview.once订阅Web引擎初始化事件
  • 支持Cookie同步、页面跳转、前进/后退等操作
  • 支持将当前网页内容导出为PDF文件

前进后退缓存设置(BackForwardCacheOptions)

API version 12起,Webview支持前进后退页面缓存。通过BackForwardCacheOptions类可设置缓存页面数量和存活时间,提升页面切换流畅度。

  • size:最大缓存页面数,默认1,最大50,0或负数关闭缓存。
  • timeToLive:页面缓存最大秒数,默认600,0或负数关闭缓存。
import { webview } from '@kit.ArkWeb';

const cacheOptions = new webview.BackForwardCacheOptions();
cacheOptions.size = 5; // 最多缓存5个页面
cacheOptions.timeToLive = 300; // 每页最多缓存5分钟

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController({
    backForwardCacheOptions: cacheOptions
  });

  build() {
    Column() {
      Web({ src: 'https://www.example.com', controller: this.controller })
    }
  }
}

实际开发中,缓存设置建议结合内存和业务需求,缓存过多可能影响性能。

地理位置权限管理(GeolocationPermissions)

Webview支持网页地理位置权限管理,需在真机测试,并申请ohos.permission.LOCATION等权限。

  • 允许/删除指定源权限
  • 查询权限状态(支持回调和Promise)
  • 获取/清除所有已存储权限
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  origin: string = "file:///";

  build() {
    Column() {
      Button('允许地理位置')
        .onClick(() => {
          try {
            webview.GeolocationPermissions.allowGeolocation(this.origin);
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
      Button('查询权限')
        .onClick(() => {
          webview.GeolocationPermissions.getAccessibleGeolocation(this.origin)
            .then(result => {
              console.log('权限状态: ' + result);
            }).catch((error: BusinessError) => {
            console.error(`getAccessibleGeolocation error, ErrorCode: ${error.code},  Message: ${error.message}`);
          });
        })
      Button('清除权限')
        .onClick(() => {
          try {
            webview.GeolocationPermissions.deleteGeolocation(this.origin);
          } catch (error) {
            console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
          }
        })
      Web({ src: 'https://www.example.com', controller: this.controller })
    }
  }
}

origin参数需为有效源字符串,参数类型错误会报401,未授权时页面无法获取定位。

网页转PDF(createPdf)

Webview支持将当前网页内容导出为PDF文件。通过WebviewController的createPdf方法,异步获取网页的PDF数据流。

  • configuration:PdfConfiguration对象,设置PDF页面宽高、边距、是否打印背景等。
  • callback:回调函数,返回PDF数据流。

常见问题:

  • 必须WebviewController已关联Web组件,否则会报17100001错误。
  • 参数类型错误会报401。
import { fileIo as fs } from '@kit.CoreFileKit';
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();
  pdfConfig: webview.PdfConfiguration = {
    width: 8.27,
    height: 11.69,
    marginTop: 0,
    marginBottom: 0,
    marginRight: 0,
    marginLeft: 0,
    shouldPrintBackground: true
  }

  build() {
    Column() {
      Button('SavePDF')
        .onClick(() => {
          this.controller.createPdf(
            this.pdfConfig,
            (error, result: webview.PdfData) => {
              try {
                // 获取组件上下文
                let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
                // 获取沙箱路径,设置pdf文件名
                let filePath = context.filesDir + "/test.pdf";
                let file = fs.openSync(filePath, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE);
                fs.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => {
                  console.info("createPDF write data to file succeed and size is:" + writeLen);
                }).catch((err: BusinessError) => {
                  console.error("createPDF write data to file failed with error message: " + err.message +
                    ", error code: " + err.code);
                }).finally(() => {
                  fs.closeSync(file);
                });
              } catch (resError) {
                console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
              }
            });
        })
      Web({ src: "www.example.com", controller: this.controller })
    }
  }
}

实际开发中,建议先判断WebviewController已绑定Web组件,PDF文件建议存储到沙箱目录,避免权限问题。

使用场景

  1. 内嵌H5页面:在App内集成第三方网页、活动页、帮助中心等。
  2. 混合开发:部分功能用Web实现,提升开发效率。
  3. 数据展示:通过网页动态展示数据或图表。

踩坑记录

  1. webview.once只触发一次:只有首次加载Web组件时触发,后续需注意生命周期管理。
  2. DevEco Studio预览器不支持Webview:请务必在真机上测试,避免预览器误判。
  3. 参数校验严格:webview.once参数类型错误会报401错误码,注意传参。
  4. Cookie同步时机:建议在webInited事件后再同步Cookie,否则可能无效。
  5. 页面跳转/刷新控制:建议统一用WebviewController管理,避免状态错乱。

总结

Webview组件为鸿蒙应用提供了强大的网页集成能力。开发过程中建议多关注生命周期、事件订阅和参数校验,遇到问题多查官方文档和社区经验。随着API不断完善,Webview的体验也会越来越好。

参考资料

欢迎体验

如果你也在开发鸿蒙应用,欢迎使用Webview组件,希望能帮到你!

收藏00

登录 后评论。没有帐号? 注册 一个。