1# Lifecycle of the Web Component 2 3## Overview 4 5You can use **Web** components to load local or online web pages. 6 7The **Web** components provide various component lifecycle callbacks. Using these callbacks, you can detect the lifecycle changes of **Web** components and process related services. 8 9The states of a **Web** component: binding controller to the **Web** component, the start, progress and end of page loading, and page to be visible. 10 11**Figure 1** Callback events during the normal web page loading of the **Web** component 12 13 14 15## Web Page Loading States of the Web component 16 17- [aboutToAppear](../reference/apis-arkui/arkui-ts/ts-custom-component-lifecycle.md#abouttoappear): When a new instance of a custom component is created, execute this function before its build function is executed. In this case, you are advised to configure [setWebDebuggingAccess](../reference/apis-arkweb/js-apis-webview.md#setwebdebuggingaccess), [customizeSchemes](../reference/apis-arkweb/js-apis-webview.md#customizeschemes), and [configCookie](../reference/apis-arkweb/js-apis-webview.md#configcookie11-1). 18 19- [onControllerAttached](../reference/apis-arkweb/ts-basic-components-web.md#oncontrollerattached10): This callback is triggered when the controller is successfully bound to the **Web** component. Do not call APIs related to the **Web** component before this callback event. Otherwise, a js-error exception will be thrown. You are advised to inject the JS object using [registerJavaScriptProxy](../reference/apis-arkweb/js-apis-webview.md#registerjavascriptproxy) and set the custom user agent using [setCustomUserAgent](../reference/apis-arkweb/js-apis-webview.md#setcustomuseragent10) in this event. You can use APIs irrelevant to web pages, such as [loadUrl](../reference/apis-arkweb/js-apis-webview.md#loadurl) and [getWebId](../reference/apis-arkweb/js-apis-webview.md#getwebid), in the callback. However, the web page is not loaded when the callback function is called. Therefore, APIs for web page operation, such as [zoomIn](../reference/apis-arkweb/js-apis-webview.md#zoomin) and [zoomOut](../reference/apis-arkweb/js-apis-webview.md#zoomout), cannot be used in the callback function. 20 21- [onLoadIntercept](../reference/apis-arkweb/ts-basic-components-web.md#onloadintercept10) : This callback is triggered before the **Web** component loads a URL, which is used to determine whether to block the access. By default, the loading is allowed. 22 23- [onOverrideUrlLoading](../reference/apis-arkweb/ts-basic-components-web.md#onoverrideurlloading12): This callback is triggered when a URL is to be loaded to the web. By using this callback, the host application can obtain the control right. If the callback returns **true**, the web stops loading the URL. If the callback returns **false**, the web continues to load the URL. The behavior of **onLoadIntercept()** is different from that of the **onOverrideUrlLoading()** and they are triggered in different timing. Therefore, the two APIs are used in different scenarios. When **LoadUrl** and **iframe** (HTML tag, indicating the HTML inline framework element, which is used to embed another page into the current page) are loaded, **onLoadIntercept()** is triggered, but **onOverrideUrlLoading()** is not triggered when **LoadUrl** is loaded and when the **iframe** loads the HTTP(s) protocol or **about:blank**. For details, see [onLoadIntercept](../reference/apis-arkweb/ts-basic-components-web.md#onloadintercept10) and [onOverrideUrlLoading](../reference/apis-arkweb/ts-basic-components-web.md#onoverrideurlloading12). 24 25- [onInterceptRequest](../reference/apis-arkweb/ts-basic-components-web.md#oninterceptrequest9): This callback is triggered before the **Web** component loads the URL, which is used to intercept the URL and return response data. 26 27- [onPageBegin](../reference/apis-arkweb/ts-basic-components-web.md#onpagebegin): This callback is triggered when a web page starts to be loaded and is triggered only in the main frame (an HTML element used to display the HTML page). This callback is not triggered when the content of an **iframe** or **frameset** (an HTML tag used to include frames) is loaded. Multi-frame pages may start to be loaded at the same time. Even if the main frame is already loaded, the sub-frames may start to be loaded or continue to be loaded. This callback is not triggered for navigation (such as segment and historical status) on the same page, navigation that fails before submission, or navigation that is canceled. 28 29- [onProgressChange](../reference/apis-arkweb/ts-basic-components-web.md#onprogresschange): This callback is triggered to notify the loading progress of the page. Multi-frame pages or sub-frames may continue to be loaded while the main frame is already loaded. Therefore, this callback event may still be received after [onPageEnd](../reference/apis-arkweb/ts-basic-components-web.md#onpageend) event. 30 31- [onPageEnd](../reference/apis-arkweb/ts-basic-components-web.md#onpageend): This callback is triggered only in the main frame when a web page is already loaded. Multi-frame pages may start to be loaded at the same time. Even if the main frame is already loaded, the sub-frames may start to be loaded or continue to be loaded. This callback is not triggered for navigation (such as segment and historical status) on the same page, navigation that fails before submission, or navigation that is canceled. You are advised to execute the JavaScript script [loadUrl](../reference/apis-arkweb/js-apis-webview.md#loadurl) in this callback. Note that receiving this callback does not guarantee that the next frame of drawn by the **Web** will reflect the current DOM status. 32 33- [onPageVisible](../reference/apis-arkweb/ts-basic-components-web.md#onpagevisible9): Web callback event, which is triggered when the body of an HTTP response starts to be loaded and a new page is about to be visible in the rendering process. In this case, the document loading is still in the early stage, so the linked resources such as online CSS and images may not be available. 34 35- [onRenderExited](../reference/apis-arkweb/ts-basic-components-web.md#onrenderexited9): This callback is triggered when an application rendering process exits abnormally. You can release system resources and save data in this callback. If you want to recover the application, call the [loadUrl](../reference/apis-arkweb/js-apis-webview.md#loadurl) API to reload the page. 36 37- [onDisAppear](../reference/apis-arkui/arkui-ts/ts-universal-events-show-hide.md#ondisappear): This callback is triggered when a component is uninstalled from the component tree, which is a common event. 38 39Codes on the application side: 40 41 ```ts 42 // xxx.ets 43 import { webview } from '@kit.ArkWeb'; 44 import { BusinessError } from '@kit.BasicServicesKit'; 45 import { promptAction } from '@kit.ArkUI'; 46 47 @Entry 48 @Component 49 struct WebComponent { 50 controller: webview.WebviewController = new webview.WebviewController(); 51 responseWeb: WebResourceResponse = new WebResourceResponse(); 52 heads: Header[] = new Array(); 53 @State webData: string = "<!DOCTYPE html>\n" + 54 "<html>\n" + 55 "<head>\n" + 56 "<title>intercept test</title>\n" + 57 "</head>\n" + 58 "<body>\n" + 59 "<h1>intercept test</h1>\n" + 60 "</body>\n" + 61 "</html>"; 62 63 aboutToAppear(): void { 64 try { 65 webview.WebviewController.setWebDebuggingAccess(true); 66 } catch (error) { 67 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 68 } 69 } 70 71 build() { 72 Column() { 73 Web({ src: $rawfile('index.html'), controller: this.controller }) 74 .onControllerAttached(() => { 75 // You are advised to use **loadUrl**, set a custom user agent, and inject a JS object. 76 console.log('onControllerAttached execute') 77 }) 78 .onLoadIntercept((event) => { 79 if (event) { 80 console.log('onLoadIntercept url:' + event.data.getRequestUrl()) 81 console.log('url:' + event.data.getRequestUrl()) 82 console.log('isMainFrame:' + event.data.isMainFrame()) 83 console.log('isRedirect:' + event.data.isRedirect()) 84 console.log('isRequestGesture:' + event.data.isRequestGesture()) 85 } 86 // If true is returned, the loading is blocked. Otherwise, the loading is allowed. 87 return true 88 }) 89 .onOverrideUrlLoading((webResourceRequest: WebResourceRequest) => { 90 if (webResourceRequest && webResourceRequest.getRequestUrl() == "about:blank") { 91 return true; 92 } 93 return false; 94 }) 95 .onInterceptRequest((event) => { 96 if (event) { 97 console.log('url:' + event.request.getRequestUrl()); 98 } 99 let head1: Header = { 100 headerKey: "Connection", 101 headerValue: "keep-alive" 102 } 103 let head2: Header = { 104 headerKey: "Cache-Control", 105 headerValue: "no-cache" 106 } 107 let length = this.heads.push(head1); 108 length = this.heads.push(head2); 109 this.responseWeb.setResponseHeader(this.heads); 110 this.responseWeb.setResponseData(this.webData); 111 this.responseWeb.setResponseEncoding('utf-8'); 112 this.responseWeb.setResponseMimeType('text/html'); 113 this.responseWeb.setResponseCode(200); 114 this.responseWeb.setReasonMessage('OK'); 115 // If response data is returned, the data is loaded based on the response data. If no response data is returned, null is returned, indicating that the data is loaded in the original mode. 116 return this.responseWeb; 117 }) 118 .onPageBegin((event) => { 119 if (event) { 120 console.log('onPageBegin url:' + event.url); 121 } 122 }) 123 .onFirstContentfulPaint(event => { 124 if (event) { 125 console.log("onFirstContentfulPaint:" + "[navigationStartTick]:" + 126 event.navigationStartTick + ", [firstContentfulPaintMs]:" + 127 event.firstContentfulPaintMs); 128 } 129 }) 130 .onProgressChange((event) => { 131 if (event) { 132 console.log('newProgress:' + event.newProgress); 133 } 134 }) 135 .onPageEnd((event) => { 136 // You are advised to execute the JavaScript script in this event. 137 if (event) { 138 console.log('onPageEnd url:' + event.url); 139 } 140 }) 141 .onPageVisible((event) => { 142 console.log('onPageVisible url:' + event.url); 143 }) 144 .onRenderExited((event) => { 145 if (event) { 146 console.log('onRenderExited reason:' + event.renderExitReason); 147 } 148 }) 149 .onDisAppear(() => { 150 promptAction.showToast({ 151 message: 'The web is hidden', 152 duration: 2000 153 }) 154 }) 155 } 156 } 157 } 158 ``` 159 160Frontend index.html: 161 162 ```html 163 <!-- index.html --> 164 <!DOCTYPE html> 165 <html> 166 <head> 167 <meta charset="UTF-8"> 168 </head> 169 <body> 170 <h1>Hello, ArkWeb</h1> 171 </body> 172 </html> 173 ``` 174 175## Performance Indicators of Web Component Page Loading 176 177Pay attention to some important performance indicators during web page loading. Such as First Contentful Paint (FCP), First Meaningful Paint (FMP), and Largest Contentful Paint (LCP). The **Web** component provides the following APIs: 178 179- [onFirstContentfulPaint](../reference/apis-arkweb/ts-basic-components-web.md#onfirstcontentfulpaint10): This callback is triggered to notify the time when the web page content such as a text, non-blank Canvas, an image or SVG is rendered for the first time. 180 181- [onFirstMeaningfulPaint](../reference/apis-arkweb/ts-basic-components-web.md#onfirstmeaningfulpaint12): This callback is triggered to notify the time when the meaningful web page content is rendered for the first time. 182 183- [onLargestContentfulPaint](../reference/apis-arkweb/ts-basic-components-web.md#onlargestcontentfulpaint12) : This callback is triggered to notify the time when the largest web page content is rendered. 184