目录

根据Web页面是否成功加载动态展示不同页面

问题现象

需要实现如下功能:

  1. Web正常加载时,页面展示Web页面。
  2. Web异常加载时,展示默认页面(页面包含重新加载按钮)。

背景知识

解决方案

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%');
  }
}

访问在线网页时需添加网络权限:ohos.permission.INTERNET,具体申请方式请参考声明权限。