目录

How do I change the displayed white screen page to a custom error page when web loading fails?

Symptom

When the network condition is poor or the link is faulty, the Web component fails to be loaded, and a white screen is displayed. In this case, users cannot perceive the page loading status, which results in a poor experience. Therefore, the white screen needs to be replaced with a custom error page.

Solution

An application can listen to page loading exception events, such as onErrorReceive, onHttpErrorReceive, and onSslErrorEventReceive, and implement the service logic as required in the corresponding callback. For example, using loadurl to load a custom error page. This article uses onErrorReceive as an example to describe how to handle the main resource error scenario and load the local error page resource file.

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

@Entry
@Component
struct Index {
  controller: webview.WebviewController = new webview.WebviewController();

  build() {
    Stack() {
      Web({ src: 'www.example.com', controller: this.controller })
        .onErrorReceive((event) => {
          // Only handle loading errors of the main framework to avoid duplicate processing of errors in sub-resources
          if (event && event.request.isMainFrame()) {
            try {
              // Load custom error pages.
              this.controller.loadUrl($rawfile('custom_failure_page.html'));
            } catch (error) {
              console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
            }
          }
        })
    }
  }
}