Overview
Developers can use Web components to load local or online web pages. Web components provide a rich set of lifecycle callback interfaces, allowing developers to monitor the state changes of Web components and perform relevant business logic.
The lifecycle states of Web components include: Controller binding to the Web component, web page loading start, web page loading progress, web page loading completion, and page becoming visible.
Web Component Lifecycle Callbacks
-
aboutToAppear: This function is executed after a new instance of a custom component is created and before its
build
function is called. It is recommended to set up Web debugging mode (setWebDebuggingAccess
), customize cross-origin requests andfetch
permissions for Web kernel custom protocol URLs (customizeSchemes
), and configure cookies (configCookie
) here.
aboutToAppear(): void {
try {
webview.WebviewController.setWebDebuggingAccess(true);
} catch (error) {
console.error(`Error Code: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
-
onControllerAttached: This callback is triggered when the Controller is successfully bound to the Web component. It is not recommended to call Web component-related interfaces before this callback, as it will throw a
js-error
exception. It is suggested to inject JS objects (registerJavaScriptProxy
), set custom user agents (setCustomUserAgent
), and use interfaces unrelated to webpage operations (e.g.,loadUrl
,getWebId
) in this callback.
.onControllerAttached(() => {
console.log('Controller attached');
})
- onLoadIntercept: This callback is triggered before the Web component loads a URL, allowing you to determine whether to block the request. By default, loading is permitted.
.onLoadIntercept((event) => {
console.log('Intercepting load request:', event.data.getRequestUrl());
return false; // Allow the load to proceed
})
-
onOverrideUrlLoading: This callback is triggered when a URL is about to be loaded into the current Web component, allowing the host application to take control. Returning
true
will cancel the URL loading, whilefalse
allows it to proceed normally. Note that this callback has different behavior and triggering conditions compared toonLoadIntercept
.
.onOverrideUrlLoading((webResourceRequest) => {
if (webResourceRequest.getRequestUrl() === "about:blank") {
return true; // Cancel the load
}
return false; // Allow the load to proceed
})
- onInterceptRequest: This callback is triggered before the Web component loads a URL, allowing you to intercept the request and return response data.
.onInterceptRequest((event) => {
console.log('Intercepting request:', event.request.getRequestUrl());
// Modify or return a custom response here
})
- onPageBegin: This callback is triggered when the web page starts loading, but only for the main frame. It is not triggered for iframes or frameset content.
.onPageBegin((event) => {
console.log('Page loading started:', event.url);
})
- onProgressChange: This callback informs developers of the current page loading progress.
.onProgressChange((event) => {
console.log('Loading progress:', event.newProgress);
})
- onPageEnd: This callback is triggered when the web page finishes loading, but only for the main frame.
.onPageEnd((event) => {
console.log('Page loading completed:', event.url);
})
- onPageVisible: This callback is triggered when the new page is about to become visible, but resources like online CSS and images may not yet be available.
.onPageVisible((event) => {
console.log('Page is about to become visible:', event.url);
})
- onRenderExited: This callback is triggered when the rendering process exits abnormally. It is recommended to release system resources and save data here.
.onRenderExited((event) => {
console.log('Rendering process exited:', event.renderExitReason);
})
- onDisAppear: This callback is triggered when the component is unloaded.
.onDisAppear(() => {
console.log('Component unloaded');
})
Example Code
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { promptAction } from '@kit.ArkUI';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
responseWeb: WebResourceResponse = new WebResourceResponse();
heads: Header[] = new Array();
@State webData: string = "<!DOCTYPE html>\n" +
"<html>\n" +
"<head>\n" +
"<title>Intercept Test</title>\n" +
"</head>\n" +
"<body>\n" +
"<h1>Intercept Test</h1>\n" +
"</body>\n" +
"</html>";
aboutToAppear(): void {
try {
webview.WebviewController.setWebDebuggingAccess(true);
} catch (error) {
console.error(`Error Code: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
build() {
Column() {
Web({ src: $rawfile('index.html'), controller: this.controller })
.onControllerAttached(() => {
console.log('Controller attached');
})
.onLoadIntercept((event) => {
console.log('Intercepting load request:', event.data.getRequestUrl());
return false; // Allow the load to proceed
})
.onOverrideUrlLoading((webResourceRequest) => {
if (webResourceRequest.getRequestUrl() === "about:blank") {
return true; // Cancel the load
}
return false; // Allow the load to proceed
})
.onInterceptRequest((event) => {
console.log('Intercepting request:', event.request.getRequestUrl());
// Modify or return a custom response here
return this.responseWeb;
})
.onPageBegin((event) => {
console.log('Page loading started:', event.url);
})
.onFirstContentfulPaint(event => {
console.log("First Contentful Paint:", event.firstContentfulPaintMs);
})
.onProgressChange((event) => {
console.log('Loading progress:', event.newProgress);
})
.onPageEnd((event) => {
console.log('Page loading completed:', event.url);
})
.onPageVisible((event) => {
console.log('Page is about to become visible:', event.url);
})
.onRenderExited((event) => {
console.log('Rendering process exited:', event.renderExitReason);
})
.onDisAppear(() => {
promptAction.showToast({
message: 'The web is hidden',
duration: 2000
});
})
}
}
}
Frontend index.html
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<h1>Hello, ArkWeb</h1>
</body>
</html>
Top comments (0)