鸿蒙 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文件建议存储到沙箱目录,避免权限问题。
使用场景
- 内嵌H5页面:在App内集成第三方网页、活动页、帮助中心等。
- 混合开发:部分功能用Web实现,提升开发效率。
- 数据展示:通过网页动态展示数据或图表。
踩坑记录
- webview.once只触发一次:只有首次加载Web组件时触发,后续需注意生命周期管理。
- DevEco Studio预览器不支持Webview:请务必在真机上测试,避免预览器误判。
- 参数校验严格:webview.once参数类型错误会报401错误码,注意传参。
- Cookie同步时机:建议在webInited事件后再同步Cookie,否则可能无效。
- 页面跳转/刷新控制:建议统一用WebviewController管理,避免状态错乱。
总结
Webview组件为鸿蒙应用提供了强大的网页集成能力。开发过程中建议多关注生命周期、事件订阅和参数校验,遇到问题多查官方文档和社区经验。随着API不断完善,Webview的体验也会越来越好。
参考资料
欢迎体验
如果你也在开发鸿蒙应用,欢迎使用Webview组件,希望能帮到你!
00
- 0回答
- 0粉丝
- 0关注
相关话题
- 鸿蒙Flutter实战:04-如何使用DevTools调试Webview
- HarmonyOS Next应用开发实战:ArkWeb使用介绍及使用举例
- 鸿蒙Flutter实战:03-鸿蒙Flutter开发中集成Webview
- 鸿蒙Next轮播组件Swiper使用了解
- 鸿蒙Next进度条组件Progress的使用
- 「Mac畅玩鸿蒙与硬件12」鸿蒙UI组件篇2 - Image组件的使用
- ArkUI-X应用工程结构说明
- ArkUI-X平台桥接Bridge说明
- 鸿蒙开发:Navigation路由组件使用由繁入简
- HarmonyOS Next Tabs组件使用
- 鸿蒙最佳实践之优先使用@Builder方法代替@Component组件
- 鸿蒙5网页开发实战:用 ArkWeb 打造超酷应用的三个绝招
- 「Mac畅玩鸿蒙与硬件23」鸿蒙UI组件篇13 - 自定义组件的创建与使用
- LoadingProgress组件的使用##HarmonyOS应用开发##
- 鸿蒙5网页开发神器 ArkWeb:让 Web 和原生手拉手跳舞