DEV Community

HarmonyOS
HarmonyOS

Posted on

How does ArkWeb load the real URL page based on the data returned by the asynchronous request?

Read the original article:How does ArkWeb load the real URL page based on the data returned by the asynchronous request?

Requirement Description

When using ArkWeb, the initial URL is an empty string. The actual URL to be loaded is obtained from an API request. After the API returns the real URL, the goal is to reload the already created ArkWeb component with this new URL.

Background Knowledge

  • loadUrl: Loads the specified URL into the Web component.
  • onControllerAttached: Triggered when the controller successfully attaches to the Web component.
    • The controller must be an instance of WebviewController.
    • Web-related APIs should not be called before this callback; otherwise, a js-error exception will occur.

Implementation Steps

  1. Initialize the WebviewController and bind it to the Web component.
  2. Use the onControllerAttached callback to ensure the controller is ready.
  3. Send an HTTP request to fetch the actual URL from the backend API.
  4. Once the real URL is retrieved, call controller.loadUrl() to load the web page dynamically.
  5. Handle potential network or controller errors gracefully.

Code Snippet / Configuration

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

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

  build() {
    Column() {
      Web({ src: '', controller: this.controller })
        .onControllerAttached(() => {
          let httpRequest = http.createHttp();
          httpRequest.request("EXAMPLE_URL", (err: Error, data: http.HttpResponse) => {  // Replace with actual API URL
            if (!err) {
              // Replace with the real URL returned by the API
              this.controller.loadUrl('REAL_URL_FROM_API');  
            } else {
              console.error(`Error: ${JSON.stringify(err)}`);
            }
          });
        })
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

Test Results

  • The Web component successfully loads the real URL after the API returns the link.
  • No JavaScript errors occur before the controller is attached.
  • The web page updates dynamically without recreating the component.

Limitations or Considerations

  • Supported from API Version 19 Release and above.
  • Requires HarmonyOS 5.1.1 Release SDK or later.
  • Must be compiled and executed using DevEco Studio 5.1.1 Release or higher.
  • Ensure the actual API returns a valid and accessible URL.

Related Documents or Links

https://developer.huawei.com/consumer/en/doc/harmonyos-references/arkts-apis-webview-webviewcontroller#loadurl

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

Written by Emine Inan

Top comments (0)