在鸿蒙应用开发中,嵌入网页内容是常见需求。ArkWeb(方舟Web)提供了强大的Webview组件,方便开发者在应用内集成网页浏览、H5页面交互等功能。本文结合实际开发经验,介绍Webview的核心用法和常见问题,帮助大家快速上手。
Webview组件主要功能如下:
API version 12起,Webview支持前进后退页面缓存。通过BackForwardCacheOptions类可设置缓存页面数量和存活时间,提升页面切换流畅度。
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 })
}
}
}实际开发中,缓存设置建议结合内存和业务需求,缓存过多可能影响性能。
Webview支持网页地理位置权限管理,需在真机测试,并申请ohos.permission.LOCATION等权限。
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,未授权时页面无法获取定位。
Webview支持将当前网页内容导出为PDF文件。通过WebviewController的createPdf方法,异步获取网页的PDF数据流。
常见问题:
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文件建议存储到沙箱目录,避免权限问题。
Webview组件为鸿蒙应用提供了强大的网页集成能力。开发过程中建议多关注生命周期、事件订阅和参数校验,遇到问题多查官方文档和社区经验。随着API不断完善,Webview的体验也会越来越好。
如果你也在开发鸿蒙应用,欢迎使用Webview组件,希望能帮到你!
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。
原创声明:本文系作者授权腾讯云开发者社区发表,未经许可,不得转载。
如有侵权,请联系 cloudcommunity@tencent.com 删除。