DEV Community

HarmonyOS
HarmonyOS

Posted on

Web component monitors page loading progress

Read the original article:Web component monitors page loading progress

Requirement Description

Implement a feature that monitors the real-time loading progress of a web page and displays it using a progress bar.

Background Knowledge

  • onProgressChange: A callback function triggered when the web page loading progress changes.
  • Progress Component: A UI component used to display loading or processing progress visually.

Implementation Steps

  1. Add the onProgressChange property in the Web component to listen for web page loading progress updates.
  2. Use the Progress component to visually represent the current loading progress.
  3. Update the progress bar dynamically as the web page loading state changes.
  4. Hide the progress bar when the loading reaches 100%.

Code Snippet / Configuration

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

@Entry
@Component
struct WebComponent {
  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 })
        .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;
          }
        })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

  • The progress bar updates smoothly according to the web page’s loading progress.
  • The progress bar disappears automatically once the page is fully loaded.

Limitations or Considerations

  • Supported from API Version 19 Release and above.
  • Requires HarmonyOS 5.1.1 Release SDK or higher.
  • Must be compiled and run using DevEco Studio 5.1.1 Release or above.

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-references/arkts-basic-components-web-events#onprogresschange

https://developer.huawei.com/consumer/en/doc/harmonyos-references/ts-basic-components-progress

Written by Emine Inan

Top comments (0)