ArkWeb的网络协议栈错误列表中当ErrorCode为0时表示正常加载,为其他值时表示异常加载。
可以定义一个successLoad变量,当加载失败后把ErrorCode值赋值给successLoad变量,重新刷新页面的时候设置successLoad的值为0(若不设置为0,则默认页面将持续显示),页面使用Stack布局,一层为默认页面,一层为Web页面,当successLoad为0时展示Web页面,successLoad为其他值展示默认页面。
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct Index {
@State successLoad: number = 0;
webController: webview.WebviewController = new webview.WebviewController();
build() {
Stack() {
Column() {
Button('重新加载')
.onClick(() => {
this.successLoad = 0;
this.webController.refresh();
});
}
.width('100%')
.height('100%')
.justifyContent(FlexAlign.Center)
.backgroundColor('#fff1f1f1')
.visibility(this.successLoad !== 0 ? Visibility.Visible : Visibility.None);
Web({ controller: this.webController, src: 'www.example.com' }) // Web页面
.width('100%')
.height('100%')
.fileAccess(false)
.geolocationAccess(false)
.visibility(this.successLoad === 0 ? Visibility.Visible : Visibility.Hidden)
.onErrorReceive((event) => {
this.successLoad = event.error.getErrorCode();
});
}
.width('100%')
.height('100%');
}
}