DEV Community

HarmonyOS
HarmonyOS

Posted on

Dynamically display different pages based on whether the web page is loaded successfully

Read the original article:Dynamically display different pages based on whether the web page is loaded successfully

Problem Description

The following functions need to be implemented:

  1. When the web page is loaded normally, the page displays the web page.
  2. When a web page is loaded abnormally, the default page is displayed (the page contains a reload button).

Background Knowledge

  • onErrorReceive : This callback is triggered when a webpage loading error occurs. This callback is called for both main and subresource errors. You can use isMainFrame to determine whether the error is primarily related to the main resource. For performance reasons, it's recommended to keep this callback as simple as possible. This callback is triggered only when there's no network connection.

  • visibility: Controls whether the component is shown or hidden. When visibility is not set, the component defaults to being shown.

    • Hidden: Hidden, but participates in layout and takes up space.
    • Visible: Display.
    • None: Hidden, but does not participate in layout and does not occupy placeholders.

Solution

ArkWeb's network protocol stack error list, when ErrorCode is 0, it indicates a normal load; other values indicate an abnormal load.
You can define a successLoad variable and assign the ErrorCode value to it when a load fails. When refreshing the page, set the successLoad value to 0 (if not set to 0, the default page will always be displayed). The page uses a Stack layout, with one layer for the default page and one layer for the web page. When successLoad is 0, the web page is displayed; other values ​​display the default page.

import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct Index {
  @State successLoad: number = 0
  webController: webview.WebviewController = new webview.WebviewController();

  build() {
    Stack(){
      Column(){
        Button('Reload')
          .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'})
        .width('100%')
        .height('100%')
        .visibility(this.successLoad === 0 ? Visibility.Visible : Visibility.Hidden)
        .onErrorReceive((event) => {
          this.successLoad = event.error.getErrorCode()
        })
    }
    .width('100%')
    .height('100%')
  }
}
Enter fullscreen mode Exit fullscreen mode

Written by Emincan Ozcan

Top comments (0)