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-errorexception will occur.
- The controller must be an instance of
Implementation Steps
- Initialize the
WebviewControllerand bind it to the Web component. - Use the
onControllerAttachedcallback to ensure the controller is ready. - Send an HTTP request to fetch the actual URL from the backend API.
- Once the real URL is retrieved, call
controller.loadUrl()to load the web page dynamically. - 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)}`);
}
});
})
}
}
}
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.
Top comments (0)