问题现象
加载Web页面时,如何实时监听Web页面的加载进度并通过进度条展示出来?
解决方案
- 实现思路如下:
- 加载在线网页时需要在module.json5中配置ohos.permission.INTERNET网络访问权限。具体配置方式请参考:声明权限。
- 在Web控件里添加onProgressChange属性监听当前网页加载进度。
- 使用Progress组件展示当前加载进度。
- 完整示例参考如下:
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
@State currentProgress: number = 0;
private total: number = 100;
@State webLoadingEnd: boolean = false;
build() {
Column() {
Progress({ value: this.currentProgress, total: this.total })
.visibility(this.webLoadingEnd ? Visibility.None : Visibility.Visible)
.width('100%');
Web({ src: 'www.example.com', controller: this.controller })
.geolocationAccess(false)
.fileAccess(false)
.onProgressChange((event) => {
if (event) {
console.info(`newProgress: ${event.newProgress}`);
}
this.currentProgress = event.newProgress;
if (event.newProgress === this.total) {
this.webLoadingEnd = true;
this.currentProgress = 0;
} else {
this.webLoadingEnd = false;
}
});
};
}
}