# @ohos.web.webview (Webview) The **Webview** module provides APIs for web control. It can work with the [Web](ts-basic-components-web.md) component, which is used to display web pages. > **NOTE** > > - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version. > > - You can preview how this component looks on a real device, but not in DevEco Studio Previewer. ## Required Permissions **ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../security/AccessToken/declare-permissions.md). ## Modules to Import ```ts import { webview } from '@kit.ArkWeb'; ``` ## once once(type: string, callback: Callback\): void Registers a one-time callback for web events of the specified type. Currently, only **webInited** is supported. This callback is triggered when the Web engine initialization is complete. When the first **Web** component is loaded in an application, the web engine is initialized. When other **Web** components are loaded in the same application, **once()** is not triggered. When the first **Web** component is loaded after the last **Web** component is destroyed in the application, the web engine will be initialized again. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | -------------------- | | type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. | | callback | Callback\ | Yes | Callback to register.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; webview.once("webInited", () => { console.log("configCookieSync"); webview.WebCookieManager.configCookieSync("https://www.example.com", "a=b"); }) @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ## WebMessagePort Implements a **WebMessagePort** object to send and receive messages. The message of the [WebMessageType](#webmessagetype10)/[WebMessage](#webmessage) type can be sent to the HTML5 side. ### Properties **System capability**: SystemCapability.Web.Webview.Core | Name | Type | Readable| Writable| Description | | ------------ | ------ | ---- | ---- | ------------------------------------------------| | isExtentionType10+ | boolean | Yes | Yes| Whether to use the extended APIs [postMessageEventExt](#postmessageeventext10) and [onMessageEventExt](#onmessageeventext10) when creating a **WebMessagePort**. The default value is **false**, indicating that the extended APIs are not used. | ### postMessageEvent postMessageEvent(message: WebMessage): void Sends a message of the [WebMessage](#webmessage) type to the HTML5 side. The [onMessageEvent](#onmessageevent) API must be invoked first. Otherwise, the message fails to be sent. For the complete sample code, see [postMessage](#postmessage). **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :------------- | | message | [WebMessage](#webmessage) | Yes | Message to send.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------- | | 17100010 | Failed to post messages through the port. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); ports: webview.WebMessagePort[] = []; build() { Column() { Button('postMessageEvent') .onClick(() => { try { this.ports = this.controller.createWebMessagePorts(); this.controller.postMessage('__init_port__', [this.ports[0]], '*'); this.ports[1].postMessageEvent("post message from ets to html5"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### onMessageEvent onMessageEvent(callback: (result: WebMessage) => void): void Registers a callback to receive messages of the [WebMessage](#webmessage) type from the HTML5 side. For the complete sample code, see [postMessage](#postmessage). **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | -------- | ---- | :------------------- | | callback | (result: [WebMessage](#webmessage)) => void | Yes | Message received.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------------------------------- | | 17100006 | Failed to register a message event for the port.| | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); ports: webview.WebMessagePort[] = []; build() { Column() { Button('onMessageEvent') .onClick(() => { try { this.ports = this.controller.createWebMessagePorts(); this.ports[1].onMessageEvent((msg) => { if (typeof (msg) == "string") { console.log("received string message from html5, string is:" + msg); } else if (typeof (msg) == "object") { if (msg instanceof ArrayBuffer) { console.log("received arraybuffer from html5, length is:" + msg.byteLength); } else { console.log("not support"); } } else { console.log("not support"); } }) } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### postMessageEventExt10+ postMessageEventExt(message: WebMessageExt): void Sends a message of the [WebMessageType](#webmessagetype10) type to the HTML5 side. The [onMessageEventExt](#onmessageeventext10) API must be invoked first. Otherwise, the message fails to be sent. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :------------- | | message | [WebMessageExt](#webmessageext10) | Yes | Message to send.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------- | | 17100010 | Failed to post messages through the port. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | ### onMessageEventExt10+ onMessageEventExt(callback: (result: WebMessageExt) => void): void Registers a callback to receive messages of the [WebMessageType](#webmessagetype10) type from the HTML5 side. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | -------- | ---- | :------------------- | | callback | (result: [WebMessageExt](#webmessageext10)) => void | Yes | Message received.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------------------------------- | | 17100006 | Failed to register a message event for the port. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; class TestObj { test(str: string): ArrayBuffer { let buf = new ArrayBuffer(str.length); let buff = new Uint8Array(buf); for (let i = 0; i < str.length; i++) { buff[i] = str.charCodeAt(i); } return buf; } } // Example of sending messages between an application and a web page: Use the init_web_messageport channel to receive messages from the web page on the application side through port 0 and receive messages from the application on the web page side through port 1. @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); ports: webview.WebMessagePort[] = []; nativePort: webview.WebMessagePort | null = null; @State msg1: string = ""; @State msg2: string = ""; message: webview.WebMessageExt = new webview.WebMessageExt(); @State testObjtest: TestObj = new TestObj(); build() { Column() { Text(this.msg1).fontSize(16) Text(this.msg2).fontSize(16) Button('SendToH5 setString').margin({ right: 800, }) .onClick(() => { // Use the local port to send messages to HTML5. try { console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setType(1); this.message.setString("helloFromEts"); this.nativePort.postMessageEventExt(this.message); } } catch (error) { console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('SendToH5 setNumber').margin({ top: 10, right: 800, }) .onClick(() => { // Use the local port to send messages to HTML5. try { console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setType(2); this.message.setNumber(12345); this.nativePort.postMessageEventExt(this.message); } } catch (error) { console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('SendToH5 setBoolean').margin({ top: -90, }) .onClick(() => { // Use the local port to send messages to HTML5. try { console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setType(3); this.message.setBoolean(true); this.nativePort.postMessageEventExt(this.message); } } catch (error) { console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('SendToH5 setArrayBuffer').margin({ top: 10, }) .onClick(() => { // Use the local port to send messages to HTML5. try { console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setType(4); this.message.setArrayBuffer(this.testObjtest.test("Name=test&Password=test")); this.nativePort.postMessageEventExt(this.message); } } catch (error) { console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('SendToH5 setArray').margin({ top: -90, left: 800, }) .onClick(() => { // Use the local port to send messages to HTML5. try { console.log("In ArkTS side send true start"); if (this.nativePort) { this.message.setType(5); this.message.setArray([1, 2, 3]); this.nativePort.postMessageEventExt(this.message); } } catch (error) { console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('SendToH5 setError').margin({ top: 10, left: 800, }) .onClick(() => { // Use the local port to send messages to HTML5. try { console.log("In ArkTS side send true start"); throw new ReferenceError("ReferenceError"); } catch (error) { if (this.nativePort) { this.message.setType(6); this.message.setError(error); this.nativePort.postMessageEventExt(this.message); } console.error(`In ArkTS side send message catch error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .onPageEnd(() => { console.log("In ArkTS side message onPageEnd init message channel"); // 1. Create a message port. this.ports = this.controller.createWebMessagePorts(true); // 2. Send port 1 to HTML5. this.controller.postMessage("init_web_messageport", [this.ports[1]], "*"); // 3. Save port 0 to the local host. this.nativePort = this.ports[0]; // 4. Set the callback. this.nativePort.onMessageEventExt((result) => { console.log("In ArkTS side got message"); try { let type = result.getType(); console.log("In ArkTS side getType:" + type); switch (type) { case webview.WebMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); this.msg2 = "result getString:" + ((result.getString())); break; } case webview.WebMessageType.NUMBER: { this.msg1 = "result type:" + typeof (result.getNumber()); this.msg2 = "result getNumber:" + ((result.getNumber())); break; } case webview.WebMessageType.BOOLEAN: { this.msg1 = "result type:" + typeof (result.getBoolean()); this.msg2 = "result getBoolean:" + ((result.getBoolean())); break; } case webview.WebMessageType.ARRAY_BUFFER: { this.msg1 = "result type:" + typeof (result.getArrayBuffer()); this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); break; } case webview.WebMessageType.ARRAY: { this.msg1 = "result type:" + typeof (result.getArray()); this.msg2 = "result getArray:" + result.getArray(); break; } case webview.WebMessageType.ERROR: { this.msg1 = "result type:" + typeof (result.getError()); this.msg2 = "result getError:" + result.getError(); break; } default: { this.msg1 = "default break, type:" + type; break; } } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }); }) } } } ``` HTML file to be loaded: ```html WebView MessagePort Demo

Html5 Send and Receive Message

Receive string:

Receive arraybuffer:


``` ```js //index.js var h5Port; window.addEventListener('message', function(event) { if (event.data == 'init_web_messageport') { if(event.ports[0] != null) { h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. h5Port.onmessage = function(event) { console.log("hwd In html got message"); // 2. Receive the message sent from the eTS side. var result = event.data; console.log("In html got message, typeof: ", typeof(result)); console.log("In html got message, result: ", (result)); if (typeof(result) == "string") { console.log("In html got message, String: ", result); document.getElementById("msg").innerHTML = "String:" + result; } else if (typeof(result) == "number") { console.log("In html side got message, number: ", result); document.getElementById("msg").innerHTML = "Number:" + result; } else if (typeof(result) == "boolean") { console.log("In html side got message, boolean: ", result); document.getElementById("msg").innerHTML = "Boolean:" + result; } else if (typeof(result) == "object") { if (result instanceof ArrayBuffer) { document.getElementById("msg2").innerHTML = "ArrayBuffer:" + result.byteLength; console.log("In html got message, byteLength: ", result.byteLength); } else if (result instanceof Error) { console.log("In html error message, err:" + (result)); console.log("In html error message, typeof err:" + typeof(result)); document.getElementById("msg2").innerHTML = "Error:" + result.name + ", msg:" + result.message; } else if (result instanceof Array) { console.log("In html got message, Array"); console.log("In html got message, Array length:" + result.length); console.log("In html got message, Array[0]:" + (result[0])); console.log("In html got message, typeof Array[0]:" + typeof(result[0])); document.getElementById("msg2").innerHTML = "Array len:" + result.length + ", value:" + result; } else { console.log("In html got message, not any instance of support type"); document.getElementById("msg").innerHTML = "not any instance of support type"; } } else { console.log("In html got message, not support type"); document.getElementById("msg").innerHTML = "not support type"; } } h5Port.onmessageerror = (event) => { console.error(`hwd In html Error receiving message: ${event}`); }; } } }) // Use h5Port to send a message of the string type to the ets side. function postStringToApp() { if (h5Port) { console.log("In html send string message"); h5Port.postMessage("hello"); console.log("In html send string message end"); } else { console.error("In html h5port is null, please init first"); } } ``` ### close close(): void Closes this message port when messages do not need to be sent. To use this API, a message port must first be created using [createWebMessagePorts](#createwebmessageports). **System capability**: SystemCapability.Web.Webview.Core **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); msgPort: webview.WebMessagePort[] = []; build() { Column() { // Use createWebMessagePorts to create a message port. Button('createWebMessagePorts') .onClick(() => { try { this.msgPort = this.controller.createWebMessagePorts(); console.log("createWebMessagePorts size:" + this.msgPort.length) } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('close') .onClick(() => { try { if (this.msgPort && this.msgPort.length == 2) { this.msgPort[1].close(); } else { console.error("msgPort is null, Please initialize first"); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ## WebviewController Implements a **WebviewController** to control the behavior of the **Web** component. A **WebviewController** can control only one **Web** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **Web** component. ### constructor11+ constructor(webTag?: string) Constructor used to create a **WebviewController** object. > **NOTE** > > When no parameter is passed in **new webview.WebviewController()**, it indicates that the constructor is empty. If the C API is not used, no parameter needs to be passed. > > When a valid string is passed in, **new webview.WebviewController("xxx")** can be used to distinguish multiple instances and invoke the methods of the corresponding instance. > > When an empty parameter is passed in, such as **new webview.WebviewController("")** or **new webview.WebviewController(undefined)**, the parameter is meaningless that multiple instances cannot be distinguished and **undefined** is returned. You need to check whether the return value is normal. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | -------------------------------- | | webTag | string | No | Name of the **Web** component.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; class WebObj { constructor() { } webTest(): string { console.log('Web test'); return "Web test"; } webString(): void { console.log('Web test toString'); } } @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController() @State webTestObj: WebObj = new WebObj(); build() { Column() { Button('refresh') .onClick(() => { try { this.controller.refresh(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('deleteJavaScriptRegister') .onClick(() => { try { this.controller.deleteJavaScriptRegister("objTestName"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: '', controller: this.controller }) .javaScriptAccess(true) .onControllerAttached(() => { this.controller.loadUrl($rawfile("index.html")); this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); }) } } } ``` HTML file to be loaded: ```html

``` ### initializeWebEngine static initializeWebEngine(): void Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **Web** component is initialized to improve the startup performance. The frequently visited websites are automatically pre-connected. > **NOTE** > > - **initializeWebEngine** cannot be called in an asynchronous thread. Otherwise, the system breaks down. > - **initializeWebEngine** takes effect globally and needs to be called only once in an application lifecycle. **System capability**: SystemCapability.Web.Webview.Core **Example** The following code snippet exemplifies calling this API after the EntryAbility is created. ```ts // xxx.ets import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { webview } from '@kit.ArkWeb'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("EntryAbility onCreate") webview.WebviewController.initializeWebEngine() console.log("EntryAbility onCreate done") } } ``` ### setHttpDns10+ static setHttpDns(secureDnsMode:SecureDnsMode, secureDnsConfig:string): void Sets how the Web component uses HTTPDNS for DNS resolution. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description| | ------------------ | ------- | ---- | ------------- | | secureDnsMode | [SecureDnsMode](#securednsmode10) | Yes | Mode in which HTTPDNS is used.| | secureDnsConfig | string | Yes| Information about the HTTPDNS server to use, which must use HTTPS. Only one HTTPDNS server can be configured.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | **Example** ```ts // xxx.ets import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("EntryAbility onCreate") try { webview.WebviewController.setHttpDns(webview.SecureDnsMode.AUTO, "https://example1.test") } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } AppStorage.setOrCreate("abilityWant", want); console.log("EntryAbility onCreate done") } } ``` ### setWebDebuggingAccess static setWebDebuggingAccess(webDebuggingAccess: boolean): void Sets whether to enable web debugging. By default, web debugging is disabled. For details, see [Debugging Frontend Pages by Using DevTools](../../web/web-debugging-with-devtools.md). NOTE: Enabling web debugging allows users to check and modify the internal status of the web page, which poses security risks. Therefore, you are advised not to enable this function in the officially released version of the app. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description| | ------------------ | ------- | ---- | ------------- | | webDebuggingAccess | boolean | Yes | Sets whether to enable web debugging.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); aboutToAppear(): void { try { webview.WebviewController.setWebDebuggingAccess(true); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } } build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### loadUrl loadUrl(url: string | Resource, headers?: Array\): void Loads a specified URL. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | :-------------------- | | url | string \| Resource | Yes | URL to load. | | headers | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the URL.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100002 | Invalid url. | | 17100003 | Invalid resource path or file type. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('loadUrl') .onClick(() => { try { // The URL to be loaded is of the string type. this.controller.loadUrl('www.example.com'); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('loadUrl') .onClick(() => { try { // The headers parameter is passed. this.controller.loadUrl('www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }]); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` There are three methods for loading local resource files: 1. Using $rawfile ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('loadUrl') .onClick(() => { try { // Load a local resource file through $rawfile. this.controller.loadUrl($rawfile('index.html')); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` 2. Using the resources protocol, which can be used by WebView to load links with a hash (#). ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('loadUrl') .onClick(() => { try { // Load local resource files through the resource protocol. this.controller.loadUrl("resource://rawfile/index.html"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` 3. Using a sandbox path. For details, see the example of loading local resource files in the sandbox in [Web](ts-basic-components-web.md#web). HTML file to be loaded: ```html

Hello World

``` ### loadData loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void Loads specified data. When both **baseUrl** and **historyUrl** are empty, if **encoding** is not base64 (including null values), ASCII encoding is used for octets within the secure URL character range, and the standard %xx hexadecimal encoding of the URL is used for octets outside the secure URL character range. **data** must be encoded using Base64 or any hash (#) in the content must be encoded as %23. Otherwise, hash (#) is considered as the end of the content, and the remaining text is used as the document fragment identifier. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ---------- | ------ | ---- | ------------------------------------------------------------ | | data | string | Yes | String obtained after being base64 or URL encoded. | | mimeType | string | Yes | Media type (MIME). | | encoding | string | Yes | Encoding type, which can be base64 or URL. | | baseUrl | string | No | URL (HTTP/HTTPS/data compliant), which is assigned by the **Web** component to **window.origin**. If a large number of HTML files need to be loaded, set this parameter to **data**.| | historyUrl | string | No | URL used for historical records. If this parameter is not empty, historical records are managed based on this URL. This parameter is invalid when **baseUrl** is left empty.| > **NOTE** > > To load a local image, you can assign a space to either **baseUrl** or **historyUrl**. For details, see the sample code. > In the scenario of loading a local image, **baseUrl** and **historyUrl** cannot be both empty. Otherwise, the image cannot be loaded. > If the rich text in HTML contains special characters such as hash (#), you are advised to set the values of **baseUrl** and **historyUrl** to spaces. **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** When both **baseUrl** and **historyUrl** are empty: ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('loadData') .onClick(() => { try { this.controller.loadData( "Source:
source
", "text/html", // UTF-8 is charset. "UTF-8" ); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('loadData') .onClick(() => { try { this.controller.loadData( // Coding tests: string encoded using base64. "Q29kaW5nIHRlc3Rz", "text/html", "base64" ); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` Example of loading local resource: ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); updataContent: string = '
image -- end
' build() { Column() { Button('loadData') .onClick(() => { try { // UTF-8 is charset. this.controller.loadData(this.updataContent, "text/html", "UTF-8", " ", " "); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### accessForward accessForward(): boolean Checks whether going to the next page can be performed on the current page. You can use [getBackForwardEntries](#getbackforwardentries) to obtain the historical information list of the current WebView and use [accessStep](#accessstep) to determine whether to move forward or backward based on the specified number of steps. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------- | --------------------------------- | | boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('accessForward') .onClick(() => { try { let result = this.controller.accessForward(); console.log('result:' + result); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### forward forward(): void Moves to the next page based on the history stack. This API is generally used together with **accessForward**. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('forward') .onClick(() => { try { this.controller.forward(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### accessBackward accessBackward(): boolean Checks whether going to the previous page can be performed on the current page. You can use [getBackForwardEntries](#getbackforwardentries) to obtain the historical information list of the current WebView and use [accessStep](#accessstep) to determine whether to move forward or backward based on the specified number of steps. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------- | -------------------------------- | | boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('accessBackward') .onClick(() => { try { let result = this.controller.accessBackward(); console.log('result:' + result); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### backward backward(): void Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('backward') .onClick(() => { try { this.controller.backward(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### onActive onActive(): void Called when the **Web** component enters the active state.
The application can interact with the user while in the active foreground state, and it remains in this state until the focus is moved away from it due to some event (for example, an incoming call is received or the device screen is turned off). **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('onActive') .onClick(() => { try { this.controller.onActive(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### onInactive onInactive(): void Called when the **Web** component enters the inactive state. You can implement the behavior to perform after the application loses focus. When this API is called, any content that can be safely paused, such as animations and geographical locations, is paused as much as possible. However, the JavaScript is not paused. To pause the JavaScript globally, use [pauseAllTimers](#pausealltimers12). To reactivate the **Web** component, use [onActive](#onactive). **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('onInactive') .onClick(() => { try { this.controller.onInactive(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### refresh refresh(): void Called when the **Web** component refreshes the web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('refresh') .onClick(() => { try { this.controller.refresh(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### accessStep accessStep(step: number): boolean Checks whether a specific number of steps forward or backward can be performed on the current page. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ------------------------------------------ | | step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.| **Return value** | Type | Description | | ------- | ------------------ | | boolean | Whether moving forward or backward is performed on the current page.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State steps: number = 2; build() { Column() { Button('accessStep') .onClick(() => { try { let result = this.controller.accessStep(this.steps); console.log('result:' + result); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### clearHistory clearHistory(): void Clears the browsing history. You are not advised to call **clearHistory()** in **onErrorReceive()** and **onPageBegin()**. Otherwise, abnormal exit occurs. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearHistory') .onClick(() => { try { this.controller.clearHistory(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getHitTest getHitTest(): WebHitTestType Obtains the element type of the area being clicked. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------------------------------------------------------------ | ---------------------- | | [WebHitTestType](#webhittesttype)| Element type of the area being clicked.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getHitTest') .onClick(() => { try { let hitTestType = this.controller.getHitTest(); console.log("hitTestType: " + hitTestType); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### registerJavaScriptProxy registerJavaScriptProxy(object: object, name: string, methodList: Array\, asyncMethodList?: Array\, permission?: string): void Registers a proxy for interaction between the application and web pages loaded by the **Web** component.
Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. After this API is called, call [refresh](#refresh) for the registration to take effect. > **NOTE** > > - The **registerJavaScriptProxy** API must be used together with the **deleteJavaScriptRegister** API to prevent memory leak. > - It is recommended that **registerJavaScriptProxy** be used only with trusted URLs and over secure HTTPS connections. Injecting JavaScript objects into untrusted web components can expose your application to malicious attacks. > - After **registerJavaScriptProxy** is called, the application exposes the registered JavaScript object to all page frames. > - If a **registerJavaScriptProxy** is both registered in the synchronous and asynchronous lists, it is called asynchronously by default. > - You should register **registerJavaScriptProxy** either in synchronous list or in asynchronous list. Otherwise, this API fails to be registered. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ---------- | -------------- | ---- | ------------------------------------------------------------ | | object | object | Yes | Application-side JavaScript object to be registered. Methods and attributes can be declared separately, but cannot be registered and used at the same time. If an object contains only attributes, HTML5 can access the attributes in the object. If an object contains only methods, HTML5 can access the methods in the object.
The parameter and return value can be any of the following types:
string, number, boolean.
Dictionary or Array, with a maximum of 10 nested layers and 10,000 data records per layer.
Object, which must contain the **methodNameListForJsProxy:[fun1, fun2]** attribute, where **fun1** and **fun2** are methods that can be called.
The parameter also supports Function and Promise. Their callback cannot have return values.
The return value supports Promise. Its callback cannot have a return value.
For the example, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md).| | name | string | Yes | Name of the object to be registered, which is the same as that invoked in the window. After registration, the window can use this name to access the JavaScript object at the application side.| | methodList | Array\ | Yes | Synchronous methods of the JavaScript object to be registered at the application side. | | asyncMethodList12+ | Array\ | No | Asynchronous methods of the JavaScript object to be registered at the application side. The default value is null. Asynchronous methods cannot obtain return values. | | permission12+ | string | No | JSON string, which is empty by default. This string is used to configure JSBridge permission control and define the URL trustlist at the object and method levels.
For the example, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md).| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; class TestObj { constructor() { } test(testStr:string): string { console.log('Web Component str' + testStr); return testStr; } toString(): void { console.log('Web Component toString'); } testNumber(testNum:number): number { console.log('Web Component number' + testNum); return testNum; } asyncTestBool(testBol:boolean): void { console.log('Web Component boolean' + testBol); } } class WebObj { constructor() { } webTest(): string { console.log('Web test'); return "Web test"; } webString(): void { console.log('Web test toString'); } } class AsyncObj { constructor() { } asyncTest(): void { console.log('Async test'); } asyncString(testStr:string): void { console.log('Web async string' + testStr); } } @Entry @Component struct Index { controller: webview.WebviewController = new webview.WebviewController(); @State testObjtest: TestObj = new TestObj(); @State webTestObj: WebObj = new WebObj(); @State asyncTestObj: AsyncObj = new AsyncObj(); build() { Column() { Button('refresh') .onClick(() => { try { this.controller.refresh(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('Register JavaScript To Window') .onClick(() => { try { this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber"], ["asyncTestBool"]); this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); this.controller.registerJavaScriptProxy(this.asyncTestObj, "objAsyncName", [], ["asyncTest", "asyncString"]); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('deleteJavaScriptRegister') .onClick(() => { try { this.controller.deleteJavaScriptRegister("objName"); this.controller.deleteJavaScriptRegister("objTestName"); this.controller.deleteJavaScriptRegister("objAsyncName"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) } } } ``` HTML file to be loaded: ```html

``` For more examples, see [Invoking Application Functions on the Frontend Page](../../web/web-in-page-app-function-invoking.md). ### runJavaScript runJavaScript(script: string, callback : AsyncCallback\): void Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. > **NOTE** > > The offscreen component does not trigger **runJavaScript()**. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | script | string | Yes | JavaScript script. | | callback | AsyncCallback\ | Yes | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State webResult: string = ''; build() { Column() { Text(this.webResult).fontSize(20) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(e => { try { this.controller.runJavaScript( 'test()', (error, result) => { if (error) { console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); return; } if (result) { this.webResult = result; console.info(`The test() return value is: ${result}`); } }); if (e) { console.info('url: ', e.url); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } } } ``` HTML file to be loaded: ```html Hello world! ``` ### runJavaScript runJavaScript(script: string): Promise\ Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------- | | script | string | Yes | JavaScript script.| **Return value** | Type | Description | | --------------- | --------------------------------------------------- | | Promise\ | Promise used to return the result if the operation is successful and null otherwise.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(e => { try { this.controller.runJavaScript('test()') .then((result) => { console.log('result: ' + result); }) .catch((error: BusinessError) => { console.error("error: " + error); }) if (e) { console.info('url: ', e.url); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } } } ``` HTML file to be loaded: ```html Hello world! ``` ### runJavaScriptExt10+ runJavaScriptExt(script: string | ArrayBuffer, callback : AsyncCallback\): void Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScriptExt** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | -------------------- | ---- | ---------------------------- | | script | string \| ArrayBuffer12+ | Yes | JavaScript script.| | callback | AsyncCallback\<[JsMessageExt](#jsmessageext10)\> | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State msg1: string = ''; @State msg2: string = ''; build() { Column() { Text(this.msg1).fontSize(20) Text(this.msg2).fontSize(20) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(e => { try { this.controller.runJavaScriptExt( 'test()', (error, result) => { if (error) { console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) return; } if (result) { try { let type = result.getType(); switch (type) { case webview.JsMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); this.msg2 = "result getString:" + ((result.getString())); break; } case webview.JsMessageType.NUMBER: { this.msg1 = "result type:" + typeof (result.getNumber()); this.msg2 = "result getNumber:" + ((result.getNumber())); break; } case webview.JsMessageType.BOOLEAN: { this.msg1 = "result type:" + typeof (result.getBoolean()); this.msg2 = "result getBoolean:" + ((result.getBoolean())); break; } case webview.JsMessageType.ARRAY_BUFFER: { this.msg1 = "result type:" + typeof (result.getArrayBuffer()); this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); break; } case webview.JsMessageType.ARRAY: { this.msg1 = "result type:" + typeof (result.getArray()); this.msg2 = "result getArray:" + result.getArray(); break; } default: { this.msg1 = "default break, type:" + type; break; } } } catch (resError) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } } }); if (e) { console.info('url: ', e.url); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } } } ``` ```ts // Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { fileIo } from '@kit.CoreFileKit'; import { common } from '@kit.AbilityKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State msg1: string = '' @State msg2: string = '' build() { Column() { Text(this.msg1).fontSize(20) Text(this.msg2).fontSize(20) Button('runJavaScriptExt') .onClick(() => { try { let context = getContext(this) as common.UIAbilityContext; let filePath = context.filesDir + 'test.txt'; // Create a file and open it. let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); // Write data to the file. fileIo.writeSync(file.fd, "test()"); // Read data from the file. let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); // Close the file. fileIo.closeSync(file); this.controller.runJavaScriptExt( arrayBuffer, (error, result) => { if (error) { console.error(`run JavaScript error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`) return; } if (result) { try { let type = result.getType(); switch (type) { case webview.JsMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); this.msg2 = "result getString:" + ((result.getString())); break; } case webview.JsMessageType.NUMBER: { this.msg1 = "result type:" + typeof (result.getNumber()); this.msg2 = "result getNumber:" + ((result.getNumber())); break; } case webview.JsMessageType.BOOLEAN: { this.msg1 = "result type:" + typeof (result.getBoolean()); this.msg2 = "result getBoolean:" + ((result.getBoolean())); break; } case webview.JsMessageType.ARRAY_BUFFER: { this.msg1 = "result type:" + typeof (result.getArrayBuffer()); this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); break; } case webview.JsMessageType.ARRAY: { this.msg1 = "result type:" + typeof (result.getArray()); this.msg2 = "result getArray:" + result.getArray(); break; } default: { this.msg1 = "default break, type:" + type; break; } } } catch (resError) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } } }); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) } } } ``` HTML file to be loaded: ```html

run JavaScript Ext demo

``` ### runJavaScriptExt10+ runJavaScriptExt(script: string | ArrayBuffer): Promise\ Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScriptExt** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------- | | script | string \| ArrayBuffer12+ | Yes | JavaScript script.| **Return value** | Type | Description | | --------------- | --------------------------------------------------- | | Promise\<[JsMessageExt](#jsmessageext10)> | Promise used to return the script execution result.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State webResult: string = ''; @State msg1: string = ''; @State msg2: string = ''; build() { Column() { Text(this.webResult).fontSize(20) Text(this.msg1).fontSize(20) Text(this.msg2).fontSize(20) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) .onPageEnd(() => { this.controller.runJavaScriptExt('test()') .then((result) => { try { let type = result.getType(); switch (type) { case webview.JsMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); this.msg2 = "result getString:" + ((result.getString())); break; } case webview.JsMessageType.NUMBER: { this.msg1 = "result type:" + typeof (result.getNumber()); this.msg2 = "result getNumber:" + ((result.getNumber())); break; } case webview.JsMessageType.BOOLEAN: { this.msg1 = "result type:" + typeof (result.getBoolean()); this.msg2 = "result getBoolean:" + ((result.getBoolean())); break; } case webview.JsMessageType.ARRAY_BUFFER: { this.msg1 = "result type:" + typeof (result.getArrayBuffer()); this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); break; } case webview.JsMessageType.ARRAY: { this.msg1 = "result type:" + typeof (result.getArray()); this.msg2 = "result getArray:" + result.getArray(); break; } default: { this.msg1 = "default break, type:" + type; break; } } } catch (resError) { console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); } }).catch((error: BusinessError) => { console.error("error: " + error); }) }) } } } ``` ```ts // Use the ArrayBuffer input parameter to obtain the JavaScript script data from the file. import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { fileIo } from '@kit.CoreFileKit'; import { common } from '@kit.AbilityKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State msg1: string = ''; @State msg2: string = ''; build() { Column() { Text(this.msg1).fontSize(20) Text(this.msg2).fontSize(20) Button('runJavaScriptExt') .onClick(() => { try { let context = getContext(this) as common.UIAbilityContext; let filePath = context.filesDir + 'test.txt'; // Create a file and open it. let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); // Write data to the file. fileIo.writeSync(file.fd, "test()"); // Read data from the file. let arrayBuffer: ArrayBuffer = new ArrayBuffer(6); fileIo.readSync(file.fd, arrayBuffer, { offset: 0, length: arrayBuffer.byteLength }); // Close the file. fileIo.closeSync(file); this.controller.runJavaScriptExt(arrayBuffer) .then((result) => { try { let type = result.getType(); switch (type) { case webview.JsMessageType.STRING: { this.msg1 = "result type:" + typeof (result.getString()); this.msg2 = "result getString:" + ((result.getString())); break; } case webview.JsMessageType.NUMBER: { this.msg1 = "result type:" + typeof (result.getNumber()); this.msg2 = "result getNumber:" + ((result.getNumber())); break; } case webview.JsMessageType.BOOLEAN: { this.msg1 = "result type:" + typeof (result.getBoolean()); this.msg2 = "result getBoolean:" + ((result.getBoolean())); break; } case webview.JsMessageType.ARRAY_BUFFER: { this.msg1 = "result type:" + typeof (result.getArrayBuffer()); this.msg2 = "result getArrayBuffer byteLength:" + ((result.getArrayBuffer().byteLength)); break; } case webview.JsMessageType.ARRAY: { this.msg1 = "result type:" + typeof (result.getArray()); this.msg2 = "result getArray:" + result.getArray(); break; } default: { this.msg1 = "default break, type:" + type; break; } } } catch (resError) { console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`); } }) .catch((error: BusinessError) => { console.error("error: " + error); }) } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) } } } ``` HTML file to be loaded: ```html

run JavaScript Ext demo

``` ### deleteJavaScriptRegister deleteJavaScriptRegister(name: string): void Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. After the deletion, the [refresh](#refresh) API must be called. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---- | | name | string | Yes | Name of the registered JavaScript object, which can be used to invoke the corresponding object on the application side from the web side.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100008 | Failed to delete JavaScriptProxy because it does not exist. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; class TestObj { constructor() { } test(): string { return "ArkUI Web Component"; } toString(): void { console.log('Web Component toString'); } } @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State testObjtest: TestObj = new TestObj(); @State name: string = 'objName'; build() { Column() { Button('refresh') .onClick(() => { try { this.controller.refresh(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('Register JavaScript To Window') .onClick(() => { try { this.controller.registerJavaScriptProxy(this.testObjtest, this.name, ["test", "toString"]); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('deleteJavaScriptRegister') .onClick(() => { try { this.controller.deleteJavaScriptRegister(this.name); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) } } } ``` HTML file to be loaded: ```html

``` ### zoom zoom(factor: number): void Zooms in or out of this web page. This API is effective only when [zoomAccess](ts-basic-components-web.md#zoomaccess) is **true**. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description| | ------ | -------- | ---- | ------------------------------------------------------------ | | factor | number | Yes | Relative zoom ratio. The value must be greater than 0. The value **1** indicates that the page is not zoomed. A value smaller than **1** indicates zoom-out, and a value greater than **1** indicates zoom-in.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100004 | Function not enabled. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State factor: number = 1; build() { Column() { Button('zoom') .onClick(() => { try { this.controller.zoom(this.factor); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) .zoomAccess(true) } } } ``` ### searchAllAsync searchAllAsync(searchString: string): void Searches the web page for content that matches the keyword specified by **'searchString'** and highlights the matches on the page. This API returns the result asynchronously through [onSearchResultReceive](ts-basic-components-web.md#onsearchresultreceive9). **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type| Mandatory| Description | | ------------ | -------- | ---- | -------------- | | searchString | string | Yes | Search keyword.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State searchString: string = "Hello World"; build() { Column() { Button('searchString') .onClick(() => { try { this.controller.searchAllAsync(this.searchString); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .onSearchResultReceive(ret => { if (ret) { console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + "[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting); } }) } } } ``` HTML file to be loaded: ```html

Hello World Highlight Hello World

``` ### clearMatches clearMatches(): void Clears the matches found through [searchAllAsync](#searchallasync). **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearMatches') .onClick(() => { try { this.controller.clearMatches(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). ### searchNext searchNext(forward: boolean): void Searches for and highlights the next match. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type| Mandatory| Description | | ------- | -------- | ---- | ---------------------- | | forward | boolean | Yes | Whether to search forward.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('searchNext') .onClick(() => { try { this.controller.searchNext(true); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` For details about the HTML file loaded, see the HMTL file loaded using [searchAllAsync](#searchallasync). ### clearSslCache clearSslCache(): void Clears the user operation corresponding to the SSL certificate error event recorded by the **Web** component. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearSslCache') .onClick(() => { try { this.controller.clearSslCache(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### clearClientAuthenticationCache clearClientAuthenticationCache(): void Clears the user operation corresponding to the client certificate request event recorded by the **Web** component. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearClientAuthenticationCache') .onClick(() => { try { this.controller.clearClientAuthenticationCache(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### createWebMessagePorts createWebMessagePorts(isExtentionType?: boolean): Array\ Creates web message ports. For the complete sample code, see [onMessageEventExt](#onmessageeventext10). **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------- | ---- | :------------------------------| | isExtentionType10+ | boolean | No | Whether to use the extended interface. The default value is **false**, indicating that the extended interface is not used.| **Return value** | Type | Description | | ---------------------- | ----------------- | | Array\<[WebMessagePort](#webmessageport)> | List of web message ports.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); ports: webview.WebMessagePort[] = []; build() { Column() { Button('createWebMessagePorts') .onClick(() => { try { this.ports = this.controller.createWebMessagePorts(); console.log("createWebMessagePorts size:" + this.ports.length); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### postMessage postMessage(name: string, ports: Array\, uri: string): void Sends a web message to an HTML window. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------------------- | ---- | :------------------------------- | | name | string | Yes | Name of the message to send. | | ports | Array\<[WebMessagePort](#webmessageport)> | Yes | Message ports for sending the message. | | uri | string | Yes | URI for receiving the message. | **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); ports: webview.WebMessagePort[] = []; @State sendFromEts: string = 'Send this message from ets to HTML'; @State receivedFromHtml: string = 'Display received message send from HTML'; build() { Column() { // Display the received HTML content. Text(this.receivedFromHtml) // Send the content in the text box to an HTML window. TextInput({ placeholder: 'Send this message from ets to HTML' }) .onChange((value: string) => { this.sendFromEts = value; }) Button('postMessage') .onClick(() => { try { // 1. Create two message ports. this.ports = this.controller.createWebMessagePorts(); // 2. Register a callback on a message port (for example, port 1) on the application side. this.ports[1].onMessageEvent((result: webview.WebMessage) => { let msg = 'Got msg from HTML:'; if (typeof (result) == "string") { console.log("received string message from html5, string is:" + result); msg = msg + result; } else if (typeof (result) == "object") { if (result instanceof ArrayBuffer) { console.log("received arraybuffer from html5, length is:" + result.byteLength); msg = msg + "length is " + result.byteLength; } else { console.log("not support"); } } else { console.log("not support"); } this.receivedFromHtml = msg; }) // 3. Send another message port (for example, port 0) to the HTML side, which can then save the port for future use. this.controller.postMessage('__init_port__', [this.ports[0]], '*'); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) // 4. Use the port on the application side to send messages to the port that has been sent to the HTML side. Button('SendDataToHTML') .onClick(() => { try { if (this.ports && this.ports[1]) { this.ports[1].postMessageEvent(this.sendFromEts); } else { console.error(`ports is null, Please initialize first`); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` HTML file to be loaded: ```html WebView Message Port Demo

WebView Message Port Demo



display received message send from ets

``` ```js //xxx.js var h5Port; var output = document.querySelector('.output'); window.addEventListener('message', function (event) { if (event.data == '__init_port__') { if (event.ports[0] != null) { h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side. h5Port.onmessage = function (event) { // 2. Receive the message sent from the eTS side. var msg = 'Got message from ets:'; var result = event.data; if (typeof(result) == "string") { console.log("received string message from html5, string is:" + result); msg = msg + result; } else if (typeof(result) == "object") { if (result instanceof ArrayBuffer) { console.log("received arraybuffer from html5, length is:" + result.byteLength); msg = msg + "length is " + result.byteLength; } else { console.log("not support"); } } else { console.log("not support"); } output.innerHTML = msg; } } } }) // 3. Use h5Port to send messages to the eTS side. function PostMsgToEts(data) { if (h5Port) { h5Port.postMessage(data); } else { console.error("h5Port is null, Please initialize first"); } } ``` ### requestFocus requestFocus(): void Requests focus for this web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('requestFocus') .onClick(() => { try { this.controller.requestFocus(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }); Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### zoomIn zoomIn(): void Zooms in on this web page by 20%. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100004 | Function not enabled. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('zoomIn') .onClick(() => { try { this.controller.zoomIn(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### zoomOut zoomOut(): void Zooms out of this web page by 20%. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100004 | Function not enabled. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('zoomOut') .onClick(() => { try { this.controller.zoomOut(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getHitTestValue getHitTestValue(): HitTestValue Obtains the element information of the area being clicked. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------------ | -------------------- | | [HitTestValue](#hittestvalue) | Element information of the area being clicked.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getHitTestValue') .onClick(() => { try { let hitValue = this.controller.getHitTestValue(); console.log("hitType: " + hitValue.type); console.log("extra: " + hitValue.extra); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getWebId getWebId(): number Obtains the index value of this **Web** component, which can be used for **Web** component management. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | --------------------- | | number | Index value of the current **Web** component.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getWebId') .onClick(() => { try { let id = this.controller.getWebId(); console.log("id: " + id); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getUserAgent getUserAgent(): string Obtains the default user agent of this web page. For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | -------------- | | string | Default user agent.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getUserAgent') .onClick(() => { try { let userAgent = this.controller.getUserAgent(); console.log("userAgent: " + userAgent); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` You can define a custom user agent based on the default user agent. ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State ua: string = ""; aboutToAppear(): void { webview.once('webInited', () => { try { // Define a custom user agent on the application side. this.ua = this.controller.getUserAgent() + 'xxx'; this.controller.setCustomUserAgent(this.ua); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getTitle getTitle(): string Obtains the title of the current web page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | -------------------- | | string | Title of the current web page.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getTitle') .onClick(() => { try { let title = this.controller.getTitle(); console.log("title: " + title); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getPageHeight getPageHeight(): number Obtains the height of this web page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | -------------------- | | number | Height of the current web page. Unit: vp| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getPageHeight') .onClick(() => { try { let pageHeight = this.controller.getPageHeight(); console.log("pageHeight : " + pageHeight); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### storeWebArchive storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\): void Stores this web page. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ------------------------------------------------------------ | | baseName | string | Yes | Save path of the web page. The value cannot be null. | | autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value.| | callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise. | **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100003 | Invalid resource path or file type. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('storeWebArchive') .onClick(() => { try { this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => { if (error) { console.error(`save web archive error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); return; } if (filename != null) { console.info(`save web archive success: ${filename}`); } }); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### storeWebArchive storeWebArchive(baseName: string, autoName: boolean): Promise\ Stores this web page. This API uses a promise to return the result. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type| Mandatory| Description | | -------- | -------- | ---- | ------------------------------------------------------------ | | baseName | string | Yes | Save path of the web page. The value cannot be null. | | autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of the current page and the **baseName** value.| **Return value** | Type | Description | | --------------- | ----------------------------------------------------- | | Promise\ | Promise used to return the save path if the operation is successful and null otherwise.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100003 | Invalid resource path or file type. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('storeWebArchive') .onClick(() => { try { this.controller.storeWebArchive("/data/storage/el2/base/", true) .then(filename => { if (filename != null) { console.info(`save web archive success: ${filename}`) } }) .catch((error: BusinessError) => { console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); }) } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getUrl getUrl(): string Obtains the URL of this page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | ------------------- | | string | URL of the current page.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getUrl') .onClick(() => { try { let url = this.controller.getUrl(); console.log("url: " + url); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### stop stop(): void Stops page loading. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('stop') .onClick(() => { try { this.controller.stop(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }); Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### backOrForward backOrForward(step: number): void Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack. Because the previously loaded web pages are used for the operation, no page reloading is involved. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------------- | | step | number | Yes | Number of the steps to take.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State step: number = -2; build() { Column() { Button('backOrForward') .onClick(() => { try { this.controller.backOrForward(this.step); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### scrollTo scrollTo(x:number, y:number, duration?:number): void Scrolls the page to the specified absolute position within a specified period. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------------- | | x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| | y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used. Unit: vp| | duration14+ | number | No| Scrolling animation duration,
in milliseconds.
If no value is input or the input value is a negative number or 0, the animation is disabled.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('scrollTo') .onClick(() => { try { this.controller.scrollTo(50, 50, 500); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('stopScroll') .onClick(() => { try { this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1ms animation to interrupt the animation. } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` HTML file to be loaded: ```html Demo Scroll Test ``` ### scrollBy scrollBy(deltaX:number, deltaY:number,duration?:number): void Scrolls the page by the specified amount within a specified period. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------------- | | deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward. Unit: vp| | deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward. Unit: vp| | duration14+ | number | No| Scrolling animation duration,
in milliseconds.
If no value is input or the input value is a negative number or 0, the animation is disabled.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | > **NOTE** > > Calling **scrollBy** does not trigger the nested scrolling of the parent component. **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('scrollBy') .onClick(() => { try { this.controller.scrollBy(50, 50, 500); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('stopScroll') .onClick(() => { try { this.controller.scrollBy(0, 0, 1); // If you want to stop the animation generated by the current scroll, you can generate another 1ms animation to interrupt the animation. } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` HTML file to be loaded: ```html Demo Scroll Test ``` ### scrollByWithResult12+ scrollByWithResult(deltaX: number, deltaY: number): boolean Scrolls the page by the specified amount and returns value to indicate whether the scrolling is successful. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------------- | | deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.| | deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.| **Return value** | Type | Description | | ------- | --------------------------------------- | | boolean | Whether the current web page can be scrolled. The default value is **false**.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | > **NOTE** > > - If the web page is being touched, **false** is returned. Otherwise, **true** is returned. > - If the rendering area at the same layer of the web page is being touched, **true** is returned. > - Calling **scrollByWithResult** does not trigger the nested scrolling of the parent component. > - This API does not support the high frame rate of scrolling performance. **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('scrollByWithResult') .onClick(() => { try { let result = this.controller.scrollByWithResult(50, 50); console.log("original result: " + result); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` HTML file to be loaded: ```html Demo Scroll Test ``` ### slideScroll slideScroll(vx:number, vy:number): void Simulates a slide-to-scroll action on the page at the specified velocity. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------------- | | vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward. Unit: vp/ms.| | vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward. Unit: vp/ms.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('slideScroll') .onClick(() => { try { this.controller.slideScroll(500, 500); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` HTML file to be loaded: ```html Demo Scroll Test ``` ### getOriginalUrl getOriginalUrl(): string Obtains the original URL of this page. Risk warning: If you want to obtain the URL for JavaScriptProxy communication API authentication, use [getLastJavascriptProxyCallingFrameUrl12+](#getlastjavascriptproxycallingframeurl12). **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | ----------------------- | | string | Original URL of the current page.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getOrgUrl') .onClick(() => { try { let url = this.controller.getOriginalUrl(); console.log("original url: " + url); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getFavicon getFavicon(): image.PixelMap Obtains the favicon of this page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | -------------------------------------- | ------------------------------- | | [PixelMap](../apis-image-kit/js-apis-image.md#pixelmap7) | **PixelMap** object of the favicon of the page.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { image } from '@kit.ImageKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State pixelmap: image.PixelMap | undefined = undefined; build() { Column() { Button('getFavicon') .onClick(() => { try { this.pixelmap = this.controller.getFavicon(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### setNetworkAvailable setNetworkAvailable(enable: boolean): void Sets the **window.navigator.onLine** attribute in JavaScript. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | --------------------------------- | | enable | boolean | Yes | Whether to enable **window.navigator.onLine**.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('setNetworkAvailable') .onClick(() => { try { this.controller.setNetworkAvailable(true); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) } } } ``` HTML file to be loaded: ```html

online attribute

``` ### hasImage hasImage(callback: AsyncCallback\): void Checks whether this page contains images. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ----------------------- | ---- | -------------------------- | | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('hasImageCb') .onClick(() => { try { this.controller.hasImage((error, data) => { if (error) { console.error(`hasImage error, ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); return; } console.info("hasImage: " + data); }); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### hasImage hasImage(): Promise\ Checks whether this page contains images. This API uses a promise to return the result. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ----------------- | --------------------------------------- | | Promise\ | Promise used to return the result.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('hasImagePm') .onClick(() => { try { this.controller.hasImage().then((data) => { console.info('hasImage: ' + data); }).catch((error: BusinessError) => { console.error("error: " + error); }) } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### removeCache removeCache(clearRom: boolean): void Clears the cache in the application. This API will clear the cache for all webviews in the same application. > **NOTE** > > You can view the Webview cache in the **data/storage/el2/base/cache/web/Cache** directory. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------------------------- | | clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('removeCache') .onClick(() => { try { this.controller.removeCache(false); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### pageUp pageUp(top: boolean): void Scrolls the page up by half the viewport or jumps to the top of the page. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | | top | boolean | Yes | Whether to jump to the top of the page. The value **true** means to jump to the top of the page; and **false** means to scroll the page up by half the viewport.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('pageUp') .onClick(() => { try { this.controller.pageUp(false); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### pageDown pageDown(bottom: boolean): void Scrolls the page down by half the viewport or jumps to the bottom of the page. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ------- | ---- | ------------------------------------------------------------ | | bottom | boolean | Yes | Whether to jump to the bottom of the page. The value **true** means to jump to the bottom of the page; and **false** means to scroll the page down by half the viewport.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('pageDown') .onClick(() => { try { this.controller.pageDown(false); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getBackForwardEntries getBackForwardEntries(): BackForwardList Obtains the historical information list of the current webview. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ----------------------------------- | --------------------------- | | [BackForwardList](#backforwardlist) | The historical information list of the current webview.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getBackForwardEntries') .onClick(() => { try { let list = this.controller.getBackForwardEntries() } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### serializeWebState serializeWebState(): Uint8Array Serializes the page status history of the current Webview. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ---------- | --------------------------------------------- | | Uint8Array | Serialized data of the page status history of the current WebView.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** 1. To perform operations on files, you must first import the **fs** module. For details, see [File Management](../apis-core-file-kit/js-apis-file-fs.md). ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { fileIo } from '@kit.CoreFileKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('serializeWebState') .onClick(() => { try { let state = this.controller.serializeWebState(); let path:string | undefined = AppStorage.get("cacheDir"); if (path) { path += '/WebState'; // Synchronously open a file. let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE); fileIo.writeSync(file.fd, state.buffer); fileIo.closeSync(file.fd); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` 2. Modify the **EntryAbility.ets** file. Obtain the path of the application cache file. ```ts // xxx.ets import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. AppStorage.setOrCreate("cacheDir", this.context.cacheDir); } } ``` ### restoreWebState restoreWebState(state: Uint8Array): void Restores the page status history from the serialized data of the current WebView. If the value of **state** is too large, exceptions may occur. It is recommended that the page status history be not restored when the **state** value is greater than 512 KB. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ---------- | ---- | ---------------------------- | | state | Uint8Array | Yes | Serialized data of the page status history.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** 1. To perform operations on files, you must first import the **fs** module. For details, see [File Management](../apis-core-file-kit/js-apis-file-fs.md). ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { fileIo } from '@kit.CoreFileKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('RestoreWebState') .onClick(() => { try { let path: string | undefined = AppStorage.get("cacheDir"); if (path) { path += '/WebState'; // Synchronously open a file. let file = fileIo.openSync(path, fileIo.OpenMode.READ_WRITE); let stat = fileIo.statSync(path); let size = stat.size; let buf = new ArrayBuffer(size); fileIo.read(file.fd, buf, (err, readLen) => { if (err) { console.info("mkdir failed with error message: " + err.message + ", error code: " + err.code); } else { console.info("read file data succeed"); this.controller.restoreWebState(new Uint8Array(buf.slice(0, readLen))); fileIo.closeSync(file); } }); } } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` 2. Modify the **EntryAbility.ets** file. Obtain the path of the application cache file. ```ts // xxx.ets import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { // Data synchronization between the UIAbility component and the page can be implemented by binding cacheDir to the AppStorage object. AppStorage.setOrCreate("cacheDir", this.context.cacheDir); } } ``` ### customizeSchemes static customizeSchemes(schemes: Array\): void Grants the cross-domain request and fetch request permissions for the specified URL schemes (also known as protocols) to the web kernel. A cross-domain fetch request for any of the specified URL schemes can be intercepted by the **onInterceptRequest** API, so that you can further process the request. It is recommended that this API be called before any **Web** component is initialized. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------- | | schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 17100020 | Failed to register custom schemes. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); responseWeb: WebResourceResponse = new WebResourceResponse(); scheme1: webview.WebCustomScheme = { schemeName: "name1", isSupportCORS: true, isSupportFetch: true }; scheme2: webview.WebCustomScheme = { schemeName: "name2", isSupportCORS: true, isSupportFetch: true }; scheme3: webview.WebCustomScheme = { schemeName: "name3", isSupportCORS: true, isSupportFetch: true }; aboutToAppear(): void { try { webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3]); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } } build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onInterceptRequest((event) => { if (event) { console.log('url:' + event.request.getRequestUrl()); } return this.responseWeb; }) } } } ``` ### getCertificate10+ getCertificate(): Promise> Obtains the certificate information of this website. When the **Web** component is used to load an HTTPS website, SSL certificate verification is performed. This API uses a promise to return the [X.509 certificate](../apis-device-certificate-kit/js-apis-cert.md#x509cert) of the current website. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ---------- | --------------------------------------------- | | Promise> | Promise used to obtain the X.509 certificate array of the current HTTPS website.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { cert } from '@kit.DeviceCertificateKit'; function Uint8ArrayToString(dataArray: Uint8Array) { let dataString = ''; for (let i = 0; i < dataArray.length; i++) { dataString += String.fromCharCode(dataArray[i]); } return dataString; } function ParseX509CertInfo(x509CertArray: Array) { let res: string = 'getCertificate success: len = ' + x509CertArray.length; for (let i = 0; i < x509CertArray.length; i++) { res += ', index = ' + i + ', issuer name = ' + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' + x509CertArray[i].getNotBeforeTime() + ', valid end = ' + x509CertArray[i].getNotAfterTime(); } return res; } @Entry @Component struct Index { // outputStr displays debug information on the UI. @State outputStr: string = ''; webviewCtl: webview.WebviewController = new webview.WebviewController(); build() { Row() { Column() { List({ space: 20, initialIndex: 0 }) { ListItem() { Button() { Text('load bad ssl') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { // Load an expired certificate website and view the obtained certificate information. this.webviewCtl.loadUrl('https://expired.badssl.com'); }) .height(50) } ListItem() { Button() { Text('load example') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { // Load an HTTPS website and view the certificate information of the website. this.webviewCtl.loadUrl('https://www.example.com'); }) .height(50) } ListItem() { Button() { Text('getCertificate Promise') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { try { this.webviewCtl.getCertificate().then((x509CertArray: Array) => { this.outputStr = ParseX509CertInfo(x509CertArray); }) } catch (error) { this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; } }) .height(50) } ListItem() { Button() { Text('getCertificate AsyncCallback') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { try { this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array) => { if (error) { this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; } else { this.outputStr = ParseX509CertInfo(x509CertArray); } }) } catch (error) { this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; } }) .height(50) } } .listDirection(Axis.Horizontal) .height('10%') Text(this.outputStr) .width('100%') .fontSize(10) Web({ src: 'https://www.example.com', controller: this.webviewCtl }) .fileAccess(true) .javaScriptAccess(true) .domStorageAccess(true) .onlineImageAccess(true) .onPageEnd((e) => { if (e) { this.outputStr = 'onPageEnd : url = ' + e.url; } }) .onSslErrorEventReceive((e) => { // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. e.handler.handleConfirm(); }) .width('100%') .height('70%') } .height('100%') } } } ``` ### getCertificate10+ getCertificate(callback: AsyncCallback>): void Obtains the certificate information of this website. When the **Web** component is used to load an HTTPS website, SSL certificate verification is performed. This API uses an asynchronous callback to return the [X.509 certificate](../apis-device-certificate-kit/js-apis-cert.md#x509cert) of the current website. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ---------------------------- | ---- | ---------------------------------------- | | callback | AsyncCallback> | Yes | Callback used to obtain the X.509 certificate array of the current website.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { cert } from '@kit.DeviceCertificateKit'; function Uint8ArrayToString(dataArray: Uint8Array) { let dataString = ''; for (let i = 0; i < dataArray.length; i++) { dataString += String.fromCharCode(dataArray[i]); } return dataString; } function ParseX509CertInfo(x509CertArray: Array) { let res: string = 'getCertificate success: len = ' + x509CertArray.length; for (let i = 0; i < x509CertArray.length; i++) { res += ', index = ' + i + ', issuer name = ' + Uint8ArrayToString(x509CertArray[i].getIssuerName().data) + ', subject name = ' + Uint8ArrayToString(x509CertArray[i].getSubjectName().data) + ', valid start = ' + x509CertArray[i].getNotBeforeTime() + ', valid end = ' + x509CertArray[i].getNotAfterTime(); } return res; } @Entry @Component struct Index { // outputStr displays debug information on the UI. @State outputStr: string = ''; webviewCtl: webview.WebviewController = new webview.WebviewController(); build() { Row() { Column() { List({ space: 20, initialIndex: 0 }) { ListItem() { Button() { Text('load bad ssl') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { // Load an expired certificate website and view the obtained certificate information. this.webviewCtl.loadUrl('https://expired.badssl.com'); }) .height(50) } ListItem() { Button() { Text('load example') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { // Load an HTTPS website and view the certificate information of the website. this.webviewCtl.loadUrl('https://www.example.com'); }) .height(50) } ListItem() { Button() { Text('getCertificate Promise') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { try { this.webviewCtl.getCertificate().then((x509CertArray: Array) => { this.outputStr = ParseX509CertInfo(x509CertArray); }) } catch (error) { this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; } }) .height(50) } ListItem() { Button() { Text('getCertificate AsyncCallback') .fontSize(10) .fontWeight(FontWeight.Bold) } .type(ButtonType.Capsule) .onClick(() => { try { this.webviewCtl.getCertificate((error: BusinessError, x509CertArray: Array) => { if (error) { this.outputStr = 'getCertificate failed: ' + error.code + ", errMsg: " + error.message; } else { this.outputStr = ParseX509CertInfo(x509CertArray); } }) } catch (error) { this.outputStr = 'getCertificate failed: ' + (error as BusinessError).code + ", errMsg: " + (error as BusinessError).message; } }) .height(50) } } .listDirection(Axis.Horizontal) .height('10%') Text(this.outputStr) .width('100%') .fontSize(10) Web({ src: 'https://www.example.com', controller: this.webviewCtl }) .fileAccess(true) .javaScriptAccess(true) .domStorageAccess(true) .onlineImageAccess(true) .onPageEnd((e) => { if (e) { this.outputStr = 'onPageEnd : url = ' + e.url; } }) .onSslErrorEventReceive((e) => { // Ignore SSL certificate errors to test websites whose certificates have expired, for example, https://expired.badssl.com. e.handler.handleConfirm(); }) .width('100%') .height('70%') } .height('100%') } } } ``` ### setAudioMuted10+ setAudioMuted(mute: boolean): void Mutes this web page. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------- | | mute | boolean | Yes | Whether to mute the web page. The value **true** means to mute the web page, and **false** means the opposite.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State muted: boolean = false; build() { Column() { Button("Toggle Mute") .onClick(event => { if (event) { this.muted = !this.muted; this.controller.setAudioMuted(this.muted); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### prefetchPage10+ prefetchPage(url: string, additionalHeaders?: Array\): void Prefetches resources in the background for a page that is likely to be accessed in the near future, without executing the page JavaScript code or presenting the page. This can significantly reduce the load time for the prefetched page. > **NOTE** > > The downloaded page resources are cached for about 5 minutes. After this period, the **Web** component automatically releases the resources. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ------------------| --------------------------------| ---- | ------------- | | url | string | Yes | URL to be preloaded.| | additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP headers of the URL.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100002 | Invalid url. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('prefetchPopularPage') .onClick(() => { try { // Replace 'https://www.example.com' with a real URL for the API to work. this.controller.prefetchPage('https://www.example.com'); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) // Replace ''www.example1.com' with a real URL for the API to work. Web({ src: 'www.example1.com', controller: this.controller }) } } } ``` ### prefetchResource12+ static prefetchResource(request: RequestInfo, additionalHeaders?: Array\, cacheKey?: string, cacheValidTime?: number): void Prefetches resource requests based on specified request information and additional HTTP request headers, saves the requests to the memory cache, and specifies the cache key and validity period to accelerate loading. Currently, only POST requests whose Content-Type is application/x-www-form-urlencoded are supported. A maximum of six POST requests can be pre-obtained. To prefetch the seventh post request, call [clearPrefetchedResource](#clearprefetchedresource12) to clear the cache of unnecessary post requests. Otherwise, the cache of the earliest prefetched POST request will be automatically cleared. To use the prefetched resource cache, you need to add the key value **ArkWebPostCacheKey** to the header of the POST request. The content of the key value is the cacheKey of the corresponding cache. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ------------------| ------------------------------- | ---- | ------------------------------------------------------------------ | | request | [RequestInfo](#requestinfo12) | Yes | Information about the prefetched request. | | additionalHeaders | Array\<[WebHeader](#webheader)> | No | Additional HTTP request header of the prefetched request. | | cacheKey | string | No | Key used to query the cache of prefetched resources. The value can contain only letters and digits. If this parameter is not passed or is left empty, **url** is used by default.| | cacheValidTime | number | No | Validity period for caching prefetched resources. Value range: (0, 2147483647] Unit: second. Default value: **300s** | **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | | 17100002 | Invalid url. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("EntryAbility onCreate"); webview.WebviewController.initializeWebEngine(); // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. webview.WebviewController.prefetchResource( {url:"https://www.example1.com/post?e=f&g=h", method:"POST", formData:"a=x&b=y",}, [{headerKey:"c", headerValue:"z",},], "KeyX", 500); AppStorage.setOrCreate("abilityWant", want); console.log("EntryAbility onCreate done"); } } ``` ### clearPrefetchedResource12+ static clearPrefetchedResource(cacheKeyList: Array\): void Clears the cache of prefetched resources based on the specified cache key list. The cache key in the input parameter must be the prefetched resource cache key specified by [prefetchResource](#prefetchresource12). **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ------------------| ----------- | ---- | ------------------------------------------------------------------------- | | cacheKeyList | Array\ | Yes | Key used to query the cache of prefetched resources. The value can contain only letters and digits. If this parameter is not passed or is left empty, **url** is used by default.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Web({ src: "https://www.example.com/", controller: this.controller}) .onAppear(() => { // Replace "https://www.example1.com/post?e=f&g=h" with the actual website address to visit. webview.WebviewController.prefetchResource( {url:"https://www.example1.com/post?e=f&g=h", method:"POST", formData:"a=x&b=y",}, [{headerKey:"c", headerValue:"z",},], "KeyX", 500); }) .onPageEnd(() => { // Clear the prefetch cache that is no longer used. webview.WebviewController.clearPrefetchedResource(["KeyX",]); }) } } } ``` ### prepareForPageLoad10+ static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void Preconnects to a URL. This API can be called before the URL is loaded, to resolve the DNS and establish a socket connection, without obtaining the resources. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ---------------| ------- | ---- | ------------- | | url | string | Yes | URL to be preconnected.| | preconnectable | boolean | Yes | Whether to perform preconnection, which involves DNS resolution and socket connection establishment. The value **true** means to perform preconnection, and **false** means the opposite.| | numSockets | number | Yes | Number of sockets to be preconnected. The value must be greater than 0. A maximum of six socket connections are allowed.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100002 | Invalid url. | | 171000013| The number of preconnect sockets is invalid. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("EntryAbility onCreate"); webview.WebviewController.initializeWebEngine(); // Replace 'https://www.example.com' with a real URL for the API to work. webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2); AppStorage.setOrCreate("abilityWant", want); console.log("EntryAbility onCreate done"); } } ``` ### setCustomUserAgent10+ setCustomUserAgent(userAgent: string): void Sets a custom user agent, which will overwrite the default user agent. When a URL is set for the **Web** component **src**, you are advised to set UserAgent in the onControllerAttached callback event. For details, see the example. You are not advised to set **UserAgent** in the **onLoadIntercept** callback event. Otherwise, the setting may fail occasionally. When **src** of the **Web** component is set to an empty string, you are advised to call the **setCustomUserAgent** method to set **UserAgent** and then use **loadUrl** to load a specific page. For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). > **NOTE** > >If a URL is set for the **Web** component **src**, and **UserAgent** is not set in the **onControllerAttached** callback event, calling **setCustomUserAgent** again may result in the loaded page being inconsistent with the actual user agent. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ---------------| ------- | ---- | ------------- | | userAgent | string | Yes | Information about the custom user agent. It is recommended that you obtain the current default user agent through [getUserAgent](#getuseragent) and then customize the obtained user agent.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State customUserAgent: string = ' DemoApp'; build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onControllerAttached(() => { console.log("onControllerAttached"); try { let userAgent = this.controller.getUserAgent() + this.customUserAgent; this.controller.setCustomUserAgent(userAgent); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } } } ``` ### setDownloadDelegate11+ setDownloadDelegate(delegate: WebDownloadDelegate): void Sets a **WebDownloadDelegate** object to receive downloads and download progress triggered from a page. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ---------------| ------- | ---- | ------------- | | delegate | [WebDownloadDelegate](#webdownloaddelegate11) | Yes | Delegate used to receive the download progress.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); build() { Column() { Button('setDownloadDelegate') .onClick(() => { try { this.controller.setDownloadDelegate(this.delegate); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### startDownload11+ startDownload(url: string): void Downloads a file, such as an image, from the specified URL. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ---------------| ------- | ---- | ------------- | | url | string | Yes | Download URL.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100002 | Invalid url. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); delegate: webview.WebDownloadDelegate = new webview.WebDownloadDelegate(); build() { Column() { Button('setDownloadDelegate') .onClick(() => { try { this.controller.setDownloadDelegate(this.delegate); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('startDownload') .onClick(() => { try { this.controller.startDownload('https://www.example.com'); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getCustomUserAgent10+ getCustomUserAgent(): string Obtains a custom user agent. For details about the default **UserAgent**, see [Default User Agent String](../../web/web-default-userAgent.md). **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | ------------------------- | | string | Information about the custom user agent.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State userAgent: string = ''; build() { Column() { Button('getCustomUserAgent') .onClick(() => { try { this.userAgent = this.controller.getCustomUserAgent(); console.log("userAgent: " + this.userAgent); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### setConnectionTimeout11+ static setConnectionTimeout(timeout: number): void Sets the network connection timeout. You can use the **onErrorReceive** method in the **Web** component to obtain the timeout error code. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ---------------| ------- | ---- | ------------- | | timeout | number | Yes | Socket connection timeout interval, in seconds. The value of socket must be an integer greater than 0.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('setConnectionTimeout') .onClick(() => { try { webview.WebviewController.setConnectionTimeout(5); console.log("setConnectionTimeout: 5s"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) .onErrorReceive((event) => { if (event) { console.log('getErrorInfo:' + event.error.getErrorInfo()); console.log('getErrorCode:' + event.error.getErrorCode()); } }) } } } ``` ### warmupServiceWorker12+ static warmupServiceWorker(url: string): void Warms up the ServiceWorker to enhance the loading speed of the first screen (only applicable to pages that will use ServiceWorker). This API is called before the URL is loaded. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ---------------| ------- | ---- | ------------- | | url | string | Yes | URL of the ServiceWorker to warm up.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100002 | Invalid url. | **Example** ```ts // xxx.ts import { AbilityConstant, UIAbility, Want } from '@kit.AbilityKit'; import { hilog } from '@kit.PerformanceAnalysisKit'; import { window } from '@kit.ArkUI'; import { webview } from '@kit.ArkWeb'; export default class EntryAbility extends UIAbility { onCreate(want: Want, launchParam: AbilityConstant.LaunchParam) { console.log("EntryAbility onCreate"); webview.WebviewController.initializeWebEngine(); webview.WebviewController.warmupServiceWorker("https://www.example.com"); AppStorage.setOrCreate("abilityWant", want); } } ``` ### enableSafeBrowsing11+ enableSafeBrowsing(enable: boolean): void Enables the safe browsing feature. This feature is forcibly enabled and cannot be disabled for identified untrusted websites. By default, this feature does not take effect. OpenHarmony provides only the malicious website blocking web UI. The website risk detection and web UI display features are implemented by the vendor. You are advised to listen for [DidStartNavigation](https://gitee.com/openharmony-tpc/chromium_src/blob/master/content/public/browser/web_contents_observer.h#:~:text=virtual%20void-,DidStartNavigation) and [DidRedirectNavigation](https://gitee.com/openharmony-tpc/chromium_src/blob/master/content/public/browser/web_contents_observer.h#:~:text=virtual%20void-,DidRedirectNavigation) in **WebContentsObserver** to detect risks. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | --------| ------- | ---- | ---------------------------| | enable | boolean | Yes | Whether to enable the safe browsing feature.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('enableSafeBrowsing') .onClick(() => { try { this.controller.enableSafeBrowsing(true); console.log("enableSafeBrowsing: true"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### isSafeBrowsingEnabled11+ isSafeBrowsingEnabled(): boolean Checks whether the safe browsing feature is enabled for this web page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------- | --------------------------------------- | | boolean | Whether the safe browsing feature is enabled. The default value is **false**.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('isSafeBrowsingEnabled') .onClick(() => { let result = this.controller.isSafeBrowsingEnabled(); console.log("result: " + result); }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### enableIntelligentTrackingPrevention12+ enableIntelligentTrackingPrevention(enable: boolean): void Enables intelligent tracking prevention. By default, this feature is disabled. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | --------| ------- | ---- | ---------------------------| | enable | boolean | Yes | Whether to enable intelligent tracking prevention.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------- | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('enableIntelligentTrackingPrevention') .onClick(() => { try { this.controller.enableIntelligentTrackingPrevention(true); console.log("enableIntelligentTrackingPrevention: true"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### isIntelligentTrackingPreventionEnabled12+ isIntelligentTrackingPreventionEnabled(): boolean Obtains whether intelligent tracking prevention is enabled on this web page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------- | --------------------------------------- | | boolean | Whether intelligent tracking prevention is enabled on the current web page. The default value is **false**.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------- | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('isIntelligentTrackingPreventionEnabled') .onClick(() => { try { let result = this.controller.isIntelligentTrackingPreventionEnabled(); console.log("result: " + result); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### addIntelligentTrackingPreventionBypassingList12+ static addIntelligentTrackingPreventionBypassingList(hostList: Array\): void Adds a list of domain names that bypass intelligent tracking prevention. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | ------------------------ | | hostList | Array\ | Yes | List of domain names that bypass intelligent tracking prevention.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('addIntelligentTrackingPreventionBypassingList') .onClick(() => { try { let hostList = ["www.test1.com", "www.test2.com", "www.test3.com"]; webview.WebviewController.addIntelligentTrackingPreventionBypassingList(hostList); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### removeIntelligentTrackingPreventionBypassingList12+ static removeIntelligentTrackingPreventionBypassingList(hostList: Array\): void Deletes the domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | ------------------------ | | hostList | Array\ | Yes | List of domain names that bypass intelligent tracking prevention.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('removeIntelligentTrackingPreventionBypassingList') .onClick(() => { try { let hostList = ["www.test1.com", "www.test2.com"]; webview.WebviewController.removeIntelligentTrackingPreventionBypassingList(hostList); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### clearIntelligentTrackingPreventionBypassingList12+ static clearIntelligentTrackingPreventionBypassingList(): void Deletes all domain names from the list of domain names added through the **addIntelligentTrackingPreventionBypassingList** API. **System capability**: SystemCapability.Web.Webview.Core **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearIntelligentTrackingPreventionBypassingList') .onClick(() => { webview.WebviewController.clearIntelligentTrackingPreventionBypassingList(); }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getDefaultUserAgent14+ static getDefaultUserAgent(): string Obtains the default user agent. This API can be called only in the UI thread. **System capability**: SystemCapability.Web.Webview.Core **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getDefaultUserAgent') .onClick(() => { let defaultUserAgent = webview.WebviewController.getDefaultUserAgent(); console.log("defaultUserAgent: " + defaultUserAgent); }) } } } ``` ### enableAdsBlock12+ enableAdsBlock(enable: boolean): void Enables ad blocking. By default, this feature is disabled. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | --------| ------- | ---- | ---------------------------| | enable | boolean | Yes | Whether to enable ad blocking.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ----------------------- | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('enableAdsBlock') .onClick(() => { try { this.controller.enableAdsBlock(true); console.log("enableAdsBlock: true") } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### isAdsBlockEnabled12+ isAdsBlockEnabled() : boolean Checks whether ad blocking is enabled. By default, this feature is disabled. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------------------------------------------------------------ | ---------------------- | | boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('isAdsBlockEnabled') .onClick(() => { try { let isAdsBlockEnabled: boolean = this.controller.isAdsBlockEnabled(); console.log("isAdsBlockEnabled:", isAdsBlockEnabled); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### isAdsBlockEnabledForCurPage12+ isAdsBlockEnabledForCurPage() : boolean Checks whether ad blocking is enabled on this web page. After ads blocking is enabled for the **Web** component, this feature is enabled for all web pages by default. You can call [addAdsBlockDisallowedList](#addadsblockdisallowedlist12) to disable the feature for specific domains. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------------------------------------------------------------ | ---------------------- | | boolean | Returns **true** if ad blocking is enabled; returns **false** otherwise.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('isAdsBlockEnabledForCurPage') .onClick(() => { try { let isAdsBlockEnabledForCurPage: boolean = this.controller.isAdsBlockEnabledForCurPage(); console.log("isAdsBlockEnabledForCurPage:", isAdsBlockEnabledForCurPage); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### setRenderProcessMode12+ static setRenderProcessMode(mode: RenderProcessMode): void Sets the ArkWeb render subprocess mode. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory | Description | | ----------- | ------------- | ---- | ------------------------ | | mode | [RenderProcessMode](#renderprocessmode12)| Yes | Render subprocess mode. You can call [getRenderProcessMode()](#getrenderprocessmode12) to view the ArkWeb rendering subprocess mode of the current device. The enumerated value **0** indicates the single render subprocess mode, and **1** indicates the multi-render subprocess mode. If an invalid number other than the enumerated value of **RenderProcessMode** is passed, the multi-render subprocess mode is used by default.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('setRenderProcessMode') .onClick(() => { try { webview.WebviewController.setRenderProcessMode(webview.RenderProcessMode.MULTIPLE); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getRenderProcessMode12+ static getRenderProcessMode(): RenderProcessMode Obtains the ArkWeb render subprocess mode. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ----------------------------------------- | ------------------------------------------------------------ | | [RenderProcessMode](#renderprocessmode12) | Render subprocess mode. You can call [getRenderProcessMode()](#getrenderprocessmode12) to obtain the ArkWeb render subprocess mode of the current device. The enumerated value **0** indicates the single render subprocess mode, and **1** indicates the multi-render subprocess mode. If the obtained value is not an enumerated value of **RenderProcessMode**, the multi-render subprocess mode is used by default.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getRenderProcessMode') .onClick(() => { let mode = webview.WebviewController.getRenderProcessMode(); console.log("getRenderProcessMode: " + mode); }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### terminateRenderProcess12+ terminateRenderProcess(): boolean Terminates this render process. Calling this API will destroy the associated render process. If the render process has not been started or has been destroyed, there is no impact. In addition, destroying the render process affects all other instances associated with the render process. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------------------------------------------------------------ | ---------------------- | | boolean | Result of destroying the render process. If the render process can be destroyed, **true** is returned. Otherwise, **false** is returned. If the rendering process is destroyed, **true** is returned.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID | Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('terminateRenderProcess') .onClick(() => { let result = this.controller.terminateRenderProcess(); console.log("terminateRenderProcess result: " + result); }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### postUrl11+ postUrl(url: string, postData: ArrayBuffer): void Loads the specified URL with **postData** using the POST method. If **url** is not a network URL, it will be loaded with [loadUrl](#loadurl) instead, and the **postData** parameter will be ignored. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ---------------- | ---- | :-------------------- | | url | string | Yes | URL to load. | | postData | ArrayBuffer | Yes | Data to transfer using the POST method. The request must be encoded in "application/x-www-form-urlencoded" format.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | | 17100002 | Invalid url. | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; class TestObj { constructor() { } test(str: string): ArrayBuffer { let buf = new ArrayBuffer(str.length); let buff = new Uint8Array(buf); for (let i = 0; i < str.length; i++) { buff[i] = str.charCodeAt(i); } return buf; } } @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); @State testObjtest: TestObj = new TestObj(); build() { Column() { Button('postUrl') .onClick(() => { try { // Convert data to the ArrayBuffer type. let postData = this.testObjtest.test("Name=test&Password=test"); this.controller.postUrl('www.example.com', postData); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: '', controller: this.controller }) } } } ``` ### createWebPrintDocumentAdapter11+ createWebPrintDocumentAdapter(jobName: string): print.PrintDocumentAdapter Creates a **PrintDocumentAdapter** instance to provide content for printing. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :-------------------- | | jobName | string | Yes | Name of the file to print. | **Return value** | Type | Description | | -------------------- | ------------------------- | | print.printDocumentAdapter | **PrintDocumentAdapter** instance created.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | -------------------------------------------------------------------------- | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError, print } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('createWebPrintDocumentAdapter') .onClick(() => { try { let webPrintDocadapter = this.controller.createWebPrintDocumentAdapter('example.pdf'); print.print('example_jobid', webPrintDocadapter, null, getContext()); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### isIncognitoMode11+ isIncognitoMode(): boolean Checks whether this Webview is in incognito mode. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | -------------------- | ------------------------- | | boolean | Whether the Webview is in incognito mode.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | -------------------------------------------------------------------------- | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('isIncognitoMode') .onClick(() => { try { let result = this.controller.isIncognitoMode(); console.log('isIncognitoMode' + result); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getSecurityLevel11+ getSecurityLevel(): SecurityLevel Obtains the security level of this web page. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ----------------------------------- | --------------------------- | | [SecurityLevel](#securitylevel11) | Security level of the web page. The value can be **NONE**, **SECURE**, **WARNING**, or **DANGEROUS**.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Web({ src: 'www.example.com', controller: this.controller }) .onPageEnd((event) => { if (event) { let securityLevel = this.controller.getSecurityLevel(); console.info('securityLevel: ', securityLevel); } }) } } } ``` ### setScrollable12+ setScrollable(enable: boolean, type?: ScrollType): void Sets whether this web page is scrollable. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description | | ------ | -------- | ---- | ---------------------- | | enable | boolean | Yes | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| | type | [ScrollType](#scrolltype12) | No| Scrolling type supported by the web page. The default value is supported.
- If the value of **enable** is set to **false**, the specified **ScrollType** is disabled. If **ScrollType** is set to the default value, all scrolling types are disabled.
- If the value of **enable** is set to **true**, all scrolling types are enabled regardless of the value of **ScrollType**.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('setScrollable') .onClick(() => { try { this.controller.setScrollable(true); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getScrollable12+ getScrollable(): boolean Obtains whether this web page is scrollable. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------ | -------------- | | boolean | Whether the web page is scrollable. The value **true** means the web page is scrollable, and **false** means the opposite.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getScrollable') .onClick(() => { try { let scrollEnabled = this.controller.getScrollable(); console.log("scrollEnabled: " + scrollEnabled); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### setPrintBackground12+ setPrintBackground(enable: boolean): void Sets whether to print the web page background. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | -------- | ------- | ---- | -------------------------------------- | | enable | boolean | Yes | Whether to print the web page background. The value **true** means to print the web page background, and **false** means the opposite.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('setPrintBackground') .onClick(() => { try { this.controller.setPrintBackground(false); } catch (error) { console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getPrintBackground12+ getPrintBackground(): boolean Obtains whether the web page background is printed. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | -------------------- | ------------------------- | | boolean | Whether the web page background is printed.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('setPrintBackground') .onClick(() => { try { let enable = this.controller.getPrintBackground(); console.log("getPrintBackground: " + enable); } catch (error) { console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getLastJavascriptProxyCallingFrameUrl12+ getLastJavascriptProxyCallingFrameUrl(): string Obtains the URL of the frame from which the last JavaScript proxy object was called. You can inject a JavaScript object into the window object using APIs like [registerJavaScriptProxy](#registerjavascriptproxy) or [javaScriptProxy](ts-basic-components-web.md#javascriptproxy). This API can be used to obtain the URL of the frame of the object that is injected last time. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; class TestObj { mycontroller: webview.WebviewController; constructor(controller: webview.WebviewController) { this.mycontroller = controller; } test(testStr: string): string { console.log('Web Component str' + testStr + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); return testStr; } toString(): void { console.log('Web Component toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); } testNumber(testNum: number): number { console.log('Web Component number' + testNum + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); return testNum; } testBool(testBol: boolean): boolean { console.log('Web Component boolean' + testBol + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); return testBol; } } class WebObj { mycontroller: webview.WebviewController; constructor(controller: webview.WebviewController) { this.mycontroller = controller; } webTest(): string { console.log('Web test ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); return "Web test"; } webString(): void { console.log('Web test toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl()); } } @Entry @Component struct Index { controller: webview.WebviewController = new webview.WebviewController(); @State testObjtest: TestObj = new TestObj(this.controller); @State webTestObj: WebObj = new WebObj(this.controller); build() { Column() { Button('refresh') .onClick(() => { try { this.controller.refresh(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('Register JavaScript To Window') .onClick(() => { try { this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber", "testBool"]); this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('deleteJavaScriptRegister') .onClick(() => { try { this.controller.deleteJavaScriptRegister("objName"); this.controller.deleteJavaScriptRegister("objTestName"); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .javaScriptAccess(true) } } } ``` HTML file to be loaded: ```html

``` ### pauseAllTimers12+ pauseAllTimers(): void Pauses all WebView timers. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Row() { Button('PauseAllTimers') .onClick(() => { try { webview.WebviewController.pauseAllTimers(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } Web({ src: $rawfile("index.html"), controller: this.controller }) } } } ``` HTML file to be loaded: ```html ``` ### resumeAllTimers12+ resumeAllTimers(): void Resumes all timers that are paused from the **pauseAllTimers()** API. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Row() { Button('ResumeAllTimers') .onClick(() => { try { webview.WebviewController.resumeAllTimers(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button('PauseAllTimers') .onClick(() => { try { webview.WebviewController.pauseAllTimers(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) } Web({ src: $rawfile("index.html"), controller: this.controller }) } } } ``` HTML file to be loaded: ```html ``` ### stopAllMedia12+ stopAllMedia(): void Stops all audio and video on a web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('stopAllMedia') .onClick(() => { try { this.controller.stopAllMedia(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### pauseAllMedia12+ pauseAllMedia(): void Pauses all audio and video on a web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('pauseAllMedia') .onClick(() => { try { this.controller.pauseAllMedia(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### resumeAllMedia12+ resumeAllMedia(): void Resumes the playback of the audio and video that are paused by the pauseAllMedia interface. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('resumeAllMedia') .onClick(() => { try { this.controller.resumeAllMedia(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### closeAllMediaPresentations12+ closeAllMediaPresentations(): void Closes all full-screen videos on a web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('closeAllMediaPresentations') .onClick(() => { try { this.controller.closeAllMediaPresentations(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### getMediaPlaybackState12+ getMediaPlaybackState(): MediaPlaybackState Queries the current audio and video playback control status. **System capability**: SystemCapability.Web.Webview.Core **Return value** | Type | Description | | ------------------------------------------- | --------------------------------------------------------- | | [MediaPlaybackState](#mediaplaybackstate12) | Playback control status of the current web page. The options are **NONE**, **PLAYING**, **PAUSED**, and **STOPPED**.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('getMediaPlaybackState') .onClick(() => { try { console.log("MediaPlaybackState : " + this.controller.getMediaPlaybackState()); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### setWebSchemeHandler12+ setWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void Sets the [WebSchemeHandler](#webschemehandler12), [WebSchemeHandler](#webschemehandler12) class for the current Web component to intercept requests of a specified scheme. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | :------------------------ | | scheme | string | Yes | Protocol to be intercepted.| | handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); build() { Column() { Button('setWebSchemeHandler') .onClick(() => { try { this.controller.setWebSchemeHandler('http', this.schemeHandler); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### clearWebSchemeHandler12+ clearWebSchemeHandler(): void Clears all WebSchemeHandlers set for the current Web component. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearWebSchemeHandler') .onClick(() => { try { this.controller.clearWebSchemeHandler(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### setServiceWorkerWebSchemeHandler12+ setServiceWorkerWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void Sets the WebSchemeHandler used to intercept ServiceWorker for all Web components of the current application. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type | Mandatory| Description | | ------ | ------ | ---- | :------------------------ | | scheme | string | Yes | Protocol to be intercepted.| | handler | [WebSchemeHandler](#webschemehandler12) | Yes | Interceptor that intercepts this protocol.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Parameter error. Possible causes: 1. Incorrect parameter types. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); schemeHandler: webview.WebSchemeHandler = new webview.WebSchemeHandler(); build() { Column() { Button('setWebSchemeHandler') .onClick(() => { try { webview.WebviewController.setServiceWorkerWebSchemeHandler('http', this.schemeHandler); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### clearServiceWorkerWebSchemeHandler12+ clearServiceWorkerWebSchemeHandler(): void Clears all WebSchemeHandlers that are set in the application and used to intercept ServiceWorker. **System capability**: SystemCapability.Web.Webview.Core **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button('clearServiceWorkerWebSchemeHandler') .onClick(() => { webview.WebviewController.clearServiceWorkerWebSchemeHandler(); }) Web({ src: 'www.example.com', controller: this.controller }) } } } ``` ### startCamera12+ startCamera(): void Enables the camera capture of the current web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; import { BusinessError } from '@kit.BasicServicesKit'; import { abilityAccessCtrl, PermissionRequestResult, common } from '@kit.AbilityKit'; let atManager: abilityAccessCtrl.AtManager = abilityAccessCtrl.createAtManager(); try { let context: Context = getContext(this) as common.UIAbilityContext; atManager.requestPermissionsFromUser(context, ['ohos.permission.CAMERA'], (err: BusinessError, data: PermissionRequestResult) => { console.info('data:' + JSON.stringify(data)); console.info('data permissions:' + data.permissions); console.info('data authResults:' + data.authResults); }) } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } @Entry @Component struct WebComponent { controller: webview.WebviewController = new webview.WebviewController(); build() { Column() { Button("startCamera").onClick(() => { try { this.controller.startCamera(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button("stopCamera").onClick(() => { try { this.controller.stopCamera(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Button("closeCamera").onClick(() => { try { this.controller.closeCamera(); } catch (error) { console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); } }) Web({ src: $rawfile('index.html'), controller: this.controller }) .onPermissionRequest((event) => { if (event) { AlertDialog.show({ title: 'title', message: 'text', primaryButton: { value: 'deny', action: () => { event.request.deny(); } }, secondaryButton: { value: 'onConfirm', action: () => { event.request.grant(event.request.getAccessibleResource()); } }, cancel: () => { event.request.deny(); } }) } }) } } } ``` HTML file to be loaded: ```html ``` ### stopCamera12+ stopCamera(): void Stops the camera capture of the current web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** For the complete sample code, see [startCamera](#startcamera12). ### closeCamera12+ closeCamera(): void Disables the camera capture of the current web page. **System capability**: SystemCapability.Web.Webview.Core **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** For the complete sample code, see [startCamera](#startcamera12). ### precompileJavaScript12+ precompileJavaScript(url: string, script: string | Uint8Array, cacheOptions: CacheOptions): Promise\ Precompiles JavaScript to generate the bytecode cache or update the existing bytecode cache based on the provided parameters. The API determines whether to update the existing bytecode cache based on the provided file information, E-Tag response header, and Last-Modified response header. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name | Type | Mandatory| Description | | ------- | ------ | ---- | :-------------------- | | url | string | Yes | Network address corresponding to the local JavaScript file, that is, the network address used when the service web page requests the server version of the file. The network address supports only the HTTP and HTTPS protocols and contains a maximum of 2048 characters. If the cache corresponding to the network address is invalid, the service web page requests the corresponding resource through the network. | | script | string \| Uint8Array | Yes | Text content of the local JavaScript. The content cannot be empty. | | cacheOptions | [CacheOptions](#cacheoptions12) | Yes | Whether to update the bytecode cache. | **Return value** | Type | Description | | ----------------------------------- | --------------------------- | | Promise\ | Promise used to return the error code for generating the bytecode cache. The value **0** indicates no error, and the value **-1** indicates an internal error.| **Error codes** For details about the error codes, see [Webview Error Codes](errorcode-webview.md). | ID| Error Message | | -------- | ------------------------------------------------------------ | | 401 | Invalid input parameter.Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. | | 17100001 | Init error. The WebviewController must be associated with a Web component. | **Example** The API is recommended for use in conjunction with dynamic components. Employ offline **Web** components to generate bytecode caches, and at the appropriate time, load service **Web** components to utilize these bytecode caches. The following is a code example: 1. Save **UIContext** to localStorage in **EntryAbility**. ```ts // EntryAbility.ets import { UIAbility } from '@kit.AbilityKit'; import { window } from '@kit.ArkUI'; const localStorage: LocalStorage = new LocalStorage('uiContext'); export default class EntryAbility extends UIAbility { storage: LocalStorage = localStorage; onWindowStageCreate(windowStage: window.WindowStage) { windowStage.loadContent('pages/Index', this.storage, (err, data) => { if (err.code) { return; } this.storage.setOrCreate("uiContext", windowStage.getMainWindowSync().getUIContext()); }); } } ``` 2. Write the basic code required by the dynamic component. ```ts // DynamicComponent.ets import { NodeController, BuilderNode, FrameNode, UIContext } from '@kit.ArkUI'; export interface BuilderData { url: string; controller: WebviewController; } const storage = LocalStorage.getShared(); export class NodeControllerImpl extends NodeController { private rootNode: BuilderNode | null = null; private wrappedBuilder: WrappedBuilder | null = null; constructor(wrappedBuilder: WrappedBuilder) { super(); this.wrappedBuilder = wrappedBuilder; } makeNode(): FrameNode | null { if (this.rootNode != null) { return this.rootNode.getFrameNode(); } return null; } initWeb(url: string, controller: WebviewController) { if(this.rootNode != null) { return; } const uiContext: UIContext = storage.get("uiContext") as UIContext; if (!uiContext) { return; } this.rootNode = new BuilderNode(uiContext); this.rootNode.build(this.wrappedBuilder, { url: url, controller: controller }); } } export const createNode = (wrappedBuilder: WrappedBuilder, data: BuilderData) => { const baseNode = new NodeControllerImpl(wrappedBuilder); baseNode.initWeb(data.url, data.controller); return baseNode; } ``` 3. Write a component for generating bytecode caches. In this example, the local JavaScript resource content is read through the file reading API from a local file in the **rawfile** directory. ```ts // PrecompileWebview.ets import { BuilderData } from "./DynamicComponent"; import { Config, configs } from "./PrecompileConfig"; @Builder function WebBuilder(data: BuilderData) { Web({ src: data.url, controller: data.controller }) .onControllerAttached(() => { precompile(data.controller, configs); }) .fileAccess(true) } export const precompileWebview = wrapBuilder(WebBuilder); export const precompile = async (controller: WebviewController, configs: Array) => { for (const config of configs) { let content = await readRawFile(config.localPath); try { controller.precompileJavaScript(config.url, content, config.options) .then(errCode => { console.error("precompile successfully! " + errCode); }).catch((errCode: number) => { console.error("precompile failed. " + errCode); }); } catch (err) { console.error("precompile failed. " + err.code + " " + err.message); } } } async function readRawFile(path: string) { try { return await getContext().resourceManager.getRawFileContent(path);; } catch (err) { return new Uint8Array(0); } } ``` JavaScript resources can also be obtained through [network requests](../apis-network-kit/js-apis-http.md). However, the HTTP response header obtained using this method is not in the standard HTTP response header format. Additional steps are required to convert the response header into the standard HTTP response header format before use. If the response header obtained through a network request is e-tag, convert it to E-Tag before using it. 4. Compile the code of the service component. ```ts // BusinessWebview.ets import { BuilderData } from "./DynamicComponent"; @Builder function WebBuilder(data: BuilderData) { // The component can be extended based on service requirements. Web({ src: data.url, controller: data.controller }) .cacheMode(CacheMode.Default) } export const businessWebview = wrapBuilder(WebBuilder); ``` 5. Write the resource configuration information. ```ts // PrecompileConfig.ets import { webview } from '@kit.ArkWeb' export interface Config { url: string, localPath: string, // Local resource path options: webview.CacheOptions } export let configs: Array = [ { url: "https://www.example.com/example.js", localPath: "example.js", options: { responseHeaders: [ { headerKey: "E-Tag", headerValue: "aWO42N9P9dG/5xqYQCxsx+vDOoU="}, { headerKey: "Last-Modified", headerValue: "Wed, 21 Mar 2024 10:38:41 GMT"} ] } } ] ``` 6. Use the component on the page. ```ts // Index.ets import { webview } from '@kit.ArkWeb'; import { NodeController } from '@kit.ArkUI'; import { createNode } from "./DynamicComponent" import { precompileWebview } from "./PrecompileWebview" import { businessWebview } from "./BusinessWebview" @Entry @Component struct Index { @State precompileNode: NodeController | undefined = undefined; precompileController: webview.WebviewController = new webview.WebviewController(); @State businessNode: NodeController | undefined = undefined; businessController: webview.WebviewController = new webview.WebviewController(); aboutToAppear(): void { // Initialize the Web component used to inject local resources. this.precompileNode = createNode(precompileWebview, { url: "https://www.example.com/empty.html", controller: this.precompileController}); } build() { Column() { // Load the Web component used by the service at a proper time. In this example, the button is clicked. Button ("Load Page") .onClick(() => { this.businessNode = createNode(businessWebview, { url: "https://www.example.com/business.html", controller: this.businessController }); }) // The Web component used for the service. NodeContainer(this.businessNode); } } } ``` To update the locally generated compiled bytecode, change the value of E-Tag or Last-Modified in responseHeaders of the cacheOptions parameter and call the API again. ### onCreateNativeMediaPlayer12+ onCreateNativeMediaPlayer(callback: CreateNativeMediaPlayerCallback): void Called when the [application takes over media playback on the web page](ts-basic-components-web.md#enablenativemediaplayer12) and media is played on the web page. If the application does not take over media playback on the web page, this callback is not invoked. **System capability**: SystemCapability.Web.Webview.Core **Parameters** | Name| Type| Mandatory| Description| |--------|------|------|------| | callback | [CreateNativeMediaPlayerCallback](#createnativemediaplayercallback12) | Yes| Callback when the application takes over media playback on the web page.| **Example** ```ts // xxx.ets import { webview } from '@kit.ArkWeb'; class ActualNativeMediaPlayerListener { handler: webview.NativeMediaPlayerHandler; constructor(handler: webview.NativeMediaPlayerHandler) { this.handler = handler; } onPlaying() { // The native media player starts playback. this.handler.handleStatusChanged(webview.PlaybackStatus.PLAYING); } onPaused() { // The native media player pauses the playback. this.handler.handleStatusChanged(webview.PlaybackStatus.PAUSED); } onSeeking() { // The local player starts to jump to the target time point. this.handler.handleSeeking(); } onSeekDone() { // The native media player seeks to the target time point. this.handler.handleSeekFinished(); } onEnded() { // The playback on the native media player is ended. this.handler.handleEnded(); } onVolumeChanged() { // Obtain the volume of the local player. let volume: number = getVolume(); this.handler.handleVolumeChanged(volume); } onCurrentPlayingTimeUpdate() { // Update the playback time. let currentTime: number = getCurrentPlayingTime(); // Convert the time unit to second. let currentTimeInSeconds = convertToSeconds(currentTime); this.handler.handleTimeUpdate(currentTimeInSeconds); } onBufferedChanged() { // The cache is changed. // Obtain the cache duration of the native media player. let bufferedEndTime: number = getCurrentBufferedTime(); // Convert the time unit to second. let bufferedEndTimeInSeconds = convertToSeconds(bufferedEndTime); this.handler.handleBufferedEndTimeChanged(bufferedEndTimeInSeconds); // Check the cache status. // If the cache status changes, notify the ArkWeb engine of the cache status. let lastReadyState: webview.ReadyState = getLastReadyState(); let currentReadyState: webview.ReadyState = getCurrentReadyState(); if (lastReadyState != currentReadyState) { this.handler.handleReadyStateChanged(currentReadyState); } } onEnterFullscreen() { // The native media player enters the full screen mode. let isFullscreen: boolean = true; this.handler.handleFullscreenChanged(isFullscreen); } onExitFullscreen() { // The native media player exits the full screen mode. let isFullscreen: boolean = false; this.handler.handleFullscreenChanged(isFullscreen); } onUpdateVideoSize(width: number, height: number) { // Notify the ArkWeb kernel when the native media player parses the video width and height. this.handler.handleVideoSizeChanged(width, height); } onDurationChanged(duration: number) { // Notify the ArkWeb kernel when the native media player parses the video duration. this.handler.handleDurationChanged(duration); } onError(error: webview.MediaError, errorMessage: string) { // Notify the ArkWeb kernel that an error occurs in the native media player. this.handler.handleError(error, errorMessage); } onNetworkStateChanged(state: webview.NetworkState) { // Notify the ArkWeb kernel that the network state of the native media player changes. this.handler.handleNetworkStateChanged(state); } onPlaybackRateChanged(playbackRate: number) { // Notify the ArkWeb kernel that the playback rate of the native media player changes. this.handler.handlePlaybackRateChanged(playbackRate); } onMutedChanged(muted: boolean) { // Notify the ArkWeb kernel that the native media player is muted. this.handler.handleMutedChanged(muted); } // Listen for other state of the native media player. } class NativeMediaPlayerImpl implements webview.NativeMediaPlayerBridge { constructor(handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) { // 1. Create a listener for the native media player. let listener: ActualNativeMediaPlayerListener = new ActualNativeMediaPlayerListener(handler); // 2. Create a native media player. // 3. Listen for the local player. // ... } updateRect(x: number, y: number, width: number, height: number) { // The position and size of the