# Class (WebviewController)
Represents a **WebviewController** object used to control various behaviors of **Web** components, including page navigation, declaration period status, and JavaScript interaction. A **WebviewController** object 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.
> **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.
>
> - The initial APIs of this class are supported since API version 9.
>
> - You can preview how this component looks on a real device, but not in DevEco Studio Previewer.
## Modules to Import
```ts
import { webview } from '@kit.ArkWeb';
```
## constructor11+
constructor(webTag?: string)
Constructs 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.
>
> After the **Web** component is destroyed, the **WebViewController** is unbound, and exception 17100001 will be thrown when the non-static method of **WebViewController** is called. You need to pay attention to the calling time and capture exceptions to prevent abnormal process exit.
**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](./arkts-apis-webview-e.md#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. 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. The value **true** indicates that web debugging is enabled. The value **false** indicates the opposite . Default value: **false**.|
**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](./arkts-apis-webview-i.md#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. |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
| 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. Load the local file through the sandbox path. For details, see the sample code for loading the sandbox path in [Loading Web Pages](../../web/web-page-loading-with-web-components.md#loading-local-pages).
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.
> **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.
>
> - To load texts, you need to set **** to avoid inconsistent font sizes.
**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.|
**Error codes**
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. |
| 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 })
}
}
}
```
Specify **baseURL**.
```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(
"," // Attempt to load the image from "https: // xxx.com/" + "aa/bb.jpg".
"text/html",
"UTF-8",
"https://xxx.com/",
"about:blank"
);
} 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 = '
'
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 | **true** is returned if going to the next page can be performed on the current page; otherwise, **false** is returned.|
**Error codes**
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. |
**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. |
**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.
> **NOTE**
>
> If [setCustomUserAgent](#setcustomuseragent10) is called when the **Web** component is loaded for the first time, the value of **accessBackForward** may be **false** when there are multiple historical entries. That is, there is no backward entry. You are advised to call the **setCustomUserAgent** method to set a user agent before using **loadUrl** to load a specific page.
>
> Causes: When the **Web** component is loaded for the first time, calling [setCustomUserAgent](#setcustomuseragent10) causes the component to reload and retain the initial history entry. Then the new entry replaces the initial history entry and no new history entry is generated. As a result, the value of **accessBackward** is false.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | **true** is returned if going to the previous page can be performed on the current page. Otherwise, **false** is returned.|
**Error codes**
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. |
**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](#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. |
**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. |
**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. |
**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. |
**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 a specific number of steps forward or backward can be performed on the current page. **true** is returned if a specific number of steps forward or backward can be performed on the current page; otherwise, **false** is returned.|
**Error codes**
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. |
| 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 })
}
}
}
```
## 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.
> - After the HTML5 thread submits an asynchronous JavaScript task to the ETS main thread, the HTML5 thread can continue to execute subsequent tasks without waiting for the task execution to complete and return a result. In this way, scenarios where the HTML5 thread is blocked due to long-running JavaScript tasks or a congested ETS thread can be effectively reduced. However, an asynchronous JavaScript task cannot return a value, and a task execution sequence cannot be ensured. Therefore, you should determine whether to use a synchronous or asynchronous function based on a specific scenario.
**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 {
// Register both synchronous and asynchronous functions.
this.controller.registerJavaScriptProxy(this.testObjtest, "objName", ["test", "toString", "testNumber"], ["asyncTestBool"]);
// Register only the synchronous function.
this.controller.registerJavaScriptProxy(this.webTestObj, "objTestName", ["webTest", "webString"]);
// Register only the asynchronous function.
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 asynchronously in the context of the current page. This API uses an asynchronous callback to return the script execution result. This method and its callback must be used on the UI thread.
> **NOTE**
>
> - The JavaScript status is no longer retained during navigation operations (such as **loadUrl**). For example, the global variables and functions defined before **loadUrl** is called do not exist on the loaded page.
> - You are advised to use **registerJavaScriptProxy** to maintain the JavaScript status during page navigation.
> - Currently, objects cannot be transferred, but structs can be transferred.
> - The return value cannot be obtained by executing the asynchronous method. You need to determine whether to use the synchronous or asynchronous method based on the specific scenario.
**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. **null** is returned 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 asynchronously in the context of the current page. This API uses a promise to return the script execution result. This method and its callback must be used on the UI thread.
> **NOTE**
>
> - The JavaScript status is no longer retained during navigation operations (such as **loadUrl**). For example, the global variables and functions defined before **loadUrl** is called do not exist on the loaded page.
> - You are advised to use **registerJavaScriptProxy** to maintain the JavaScript status during page navigation.
> - Currently, objects cannot be transferred, but structs can be transferred.
> - The asynchronous method cannot obtain the return value. You need to determine whether to use the synchronous or asynchronous method based on the specific scenario.
**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](./arkts-apis-webview-JsMessageExt.md)\> | 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 (resError) {
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 uiContext : UIContext = this.getUIContext();
let context : Context | undefined = uiContext.getHostContext() 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 (resError) {
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](./arkts-apis-webview-JsMessageExt.md)> | 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 uiContext : UIContext = this.getUIContext();
let context : Context | undefined = uiContext.getHostContext() 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](arkts-basic-components-web-attributes.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. Value range: (0, 100]|
**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](./arkts-basic-components-web-events.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 or backward. The value **true** indicates a forward search, and the value **false** indicates a backward search.|
**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.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------------------- | ---- | :------------------------------|
| isExtentionType10+ | boolean | No | Whether to use the extended interface. The value **true** means to use the extended interface, and **false** means the opposite. Default value: **false**.|
**Return value**
| Type | Description |
| ---------------------- | ----------------- |
| Array\<[WebMessagePort](./arkts-apis-webview-WebMessagePort.md)> | 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**
For details about the sample code, see [onMessageEventExt](./arkts-apis-webview-WebMessagePort.md#onmessageeventext10).
## 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](./arkts-apis-webview-WebMessagePort.md)> | 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 25%.
**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 })
}
}
}
```
## 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 **User-Agent**, see [Developing User-Agent](../../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 customize **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 {
// Customize a 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 to name and store a file based on the **baseName** value. The value **true** means to automatically generate a file name based on the current URL and store the file in the **baseName** directory.|
| 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 to name and store a file based on the **baseName** value. The value **true** means to automatically generate a file name based on the current URL and store the file in the **baseName** directory.|
**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 1 ms 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 1 ms 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 value **true** indicates that the current web page can be scrolled, and the value **false** indicates the opposite. Default value: **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/arkts-apis-image-PixelMap.md) | **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 the **window.navigator.onLine** attribute is enabled. The value **true** indicates that the **window.navigator.onLine** attribute is enabled, and the value **false** indicates the opposite. Default value: **true**.|
**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. The value **true** indicates that this page contains images, and the value **false** indicates 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. |
| 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. The value **true** indicates that this page contains images, and the value **false** indicates 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. |
| 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
Removes all Webview cache files in an 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 })
}
}
}
```
## removeAllCache18+
static removeAllCache(clearRom: boolean): void
Removes all Webview cache files in an application.
> **NOTE**
>
> You can view the WebView cache files in the **data/app/el2/100/base/\/cache/web/** directory.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | -------------------------------------------------------- |
| clearRom | boolean | Yes | Whether to clear the cache files in both ROM and RAM. If this parameter is set to **true**, the cache files in both ROM and RAM are cleared. If this parameter is set to **false**, only the cache files in RAM are cleared.|
**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('removeAllCache')
.onClick(() => {
try {
webview.WebviewController.removeAllCache(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 **false** means to scroll the page up by half the viewport, and the value **true** means to jump to the top 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. |
| 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 **false** means to scroll the page down by half the viewport, and the value **true** means to jump to the bottom 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. |
| 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.
> **NOTE**
>
> [onLoadIntercept](./arkts-basic-components-web-events.md#onloadintercept10) is triggered when the loading starts. At this time, no historical node is generated. Therefore, the historical stack obtained by calling **getBackForwardEntries** in **onLoadIntercept** does not include the page that is being loaded.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ----------------------------------- | --------------------------- |
| [BackForwardList](./arkts-apis-webview-BackForwardList.md) | 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.error("console error 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](./arkts-basic-components-web-events.md#oninterceptrequest9) 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](./arkts-apis-webview-i.md#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.
>
> - **prefetchPage** can also prefetch 302 redirect pages.
>
> - When a page is loaded after **prefetchPage** is executed, the prefetched resources are directly loaded from the cache.
>
> - If multiple URLs are specified for **prefetchPage**, only the first URL takes effect.
>
> - **prefetchPage** cannot be executed twice within 500 ms.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory | Description |
| ------------------| --------------------------------| ---- | ------------- |
| url | string | Yes | URL to be preloaded.|
| additionalHeaders | Array\<[WebHeader](./arkts-apis-webview-i.md#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 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
**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](./arkts-apis-webview-i.md#requestinfo12) | Yes | Information about the prefetched request. |
| additionalHeaders | Array\<[WebHeader](./arkts-apis-webview-i.md#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] Default value: **300s** Unit: second. |
**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 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
**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 pre-connection, 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 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
| 17100013 | 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 **src** of the **Web** component is set to a URL, set **User-Agent** in **onControllerAttached**. For details, see the following example. Avoid setting the user agent in **onLoadIntercept**. Otherwise, the setting may fail occasionally.
When **src** of the **Web** component is set to an empty string, call **setCustomUserAgent** to set **User-Agent** and then use **loadUrl** to load a specific page.
For details about the default **User-Agent**, see [Developing User-Agent](../../web/web-default-userAgent.md).
> **NOTE**
>
>If a URL is set for the **Web** component **src** and **User-Agent** is not set in the **onControllerAttached** callback, calling **setCustomUserAgent** may cause mismatches between the loaded page and the intended 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](./arkts-apis-webview-WebDownloadDelegate.md) | 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 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
**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 **User-Agent**, see [Developing User-Agent](../../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 })
}
}
}
```
## setAppCustomUserAgent20+
static setAppCustomUserAgent(userAgent: string): void
Sets the application-level custom user agent, which will overwrite the system user agent and take effect for all **Web** components in the application.
If you need to set the application-level custom user agent, you are advised to call the **setAppCustomUserAgent** method to set the user agent before creating the **Web** component, and then create the **Web** component with the specified src or load the page using [loadUrl](#loadurl).
For details about the default User-Agent definition, application scenarios, and API priorities, see [Developing User-Agent](../../web/web-default-userAgent.md).
**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 [getDefaultUserAgent](#getdefaultuseragent14) and then customize the obtained user agent.|
**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.initializeWebEngine();
let defaultUserAgent = webview.WebviewController.getDefaultUserAgent();
let appUA = defaultUserAgent + " appUA";
webview.WebviewController.setAppCustomUserAgent(appUA);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## setUserAgentForHosts20+
static setUserAgentForHosts(userAgent: string, hosts: Array\): void
Sets a custom user agent for a specific website, which overwrites the system user agent and takes effect for all **Web** components in the application.
To set a custom user agent for a specific website, you are advised to call the **setUserAgentForHosts** method to set **User-Agent** before creating a **Web** component, and then create a **Web** component with a specified src or use [loadUrl](#loadurl) to load a specific page.
For details about the default User-Agent definition, application scenarios, and API priorities, see [Developing User-Agent](../../web/web-default-userAgent.md).
**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 [getDefaultUserAgent](#getdefaultuseragent14) and then customize the obtained user agent.|
| hosts | Array\ | Yes | List of domain names related to the custom user agent. Only the latest list is retained each time the API is called. The maximum number of entries is 20,000, and the excessive entries are automatically truncated.|
**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.initializeWebEngine();
let defaultUserAgent = webview.WebviewController.getDefaultUserAgent();
let appUA = defaultUserAgent + " appUA";
webview.WebviewController.setUserAgentForHosts(
appUA,
[
"www.example.com",
"www.baidu.com"
]
);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
build() {
Column() {
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 | Timeout interval of the socket connection, in seconds. The value 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 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
**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.
> **NOTE**
>
> This API does not take effect.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------| ------- | ---- | ---------------------------|
| enable | boolean | Yes | Whether to enable the safe browsing feature. The value **true** means to enable the safe browsing feature, and **false** means the opposite. Default value: **false**.|
**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 for this web page. The value **true** indicates that the safe browsing feature is enabled, and **false** indicates the opposite. Default value: **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.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------| ------- | ---- | ---------------------------|
| enable | boolean | Yes | Whether to enable intelligent tracking prevention. The value **true** means to enable intelligent tracking prevention, and **false** means the opposite. Default value: **false**.|
**Error codes**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support intelligent tracking prevention
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. |
| 801 | Capability not supported. |
**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 this web page. The value **true** indicates that intelligent tracking prevention is enabled, and **false** indicates the opposite. Default value: **false**.|
**Error codes**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support intelligent tracking prevention
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. |
| 801 | Capability not supported. |
**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**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support intelligent tracking prevention
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. |
| 801 | Capability not supported. |
**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**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support intelligent tracking prevention
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. |
| 801 | Capability not supported. |
**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
**Error codes**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support intelligent tracking prevention
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID | Error Message |
| -------- | ------------------------ |
| 801 | Capability not supported. |
**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.
For details about the default **User-Agent**, see [Developing User-Agent](../../web/web-default-userAgent.md).
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Default **User-Agent** string of ArkWeb.|
**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();
let defaultUserAgent = webview.WebviewController.getDefaultUserAgent();
console.log("defaultUserAgent: " + defaultUserAgent);
}
}
```
## enableAdsBlock12+
enableAdsBlock(enable: boolean): void
Enables ad blocking.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory | Description |
| --------| ------- | ---- | ---------------------------|
| enable | boolean | Yes | Whether to enable ad blocking. The value **true** means to enable ad blocking, and **false** means the opposite. Default value: **false**.|
**Error codes**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
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. |
| 801 | Capability not supported. |
**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.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ---------------------- |
| boolean | **true** is returned if ad blocking is enabled; otherwise, **false** is returned. Default value: **false**.|
**Error codes**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID| Error Message |
| -------- | ----------------------- |
| 801 | Capability not supported. |
**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](./arkts-apis-webview-AdsBlockManager.md#addadsblockdisallowedlist12) to disable the feature for specific domains.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ---------------------- |
| boolean | **true** is returned if ad blocking is enabled; otherwise, **false** is returned.|
**Error codes**
> **NOTE**
>
> Since API version 18, exception 801 will be thrown when this API is called on a device that does not support ad blocking.
For details about the error codes, see [Webview Error Codes](errorcode-webview.md).
| ID| Error Message |
| -------- | ----------------------- |
| 801 | Capability not supported. |
**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](./arkts-apis-webview-e.md#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](./arkts-apis-webview-e.md#renderprocessmode12) | Render subprocess mode. You can call **getRenderProcessMode()** to obtain the ArkWeb child render process mode of the current device. The enumerated value **0** indicates the single child render process mode, and **1** indicates the multi-child render process 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 | Whether the render process is terminated. The value **true** indicates that the render process can be destroyed or has been destroyed, and **false** indicates 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';
@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 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. |
| 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, this.getUIContext().getHostContext());
} 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. The value **true** indicates that incognito mode is enabled for WebView, and **false** indicates the opposite. Default value: **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('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](./arkts-apis-webview-e.md#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 this web page is scrollable. The value **true** indicates that this web page is scrollable, and **false** indicates the opposite. Default value: **true**.|
| type | [ScrollType](./arkts-apis-webview-e.md#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 this web page is scrollable. The value **true** indicates that this web page is scrollable, and **false** indicates 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. The value **true** indicates that the web page background is printed, and **false** indicates 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
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 last frame from which the JavaScript proxy object was called. You can inject a JavaScript object into the window object using APIs like [registerJavaScriptProxy](#registerjavascriptproxy) or [javaScriptProxy](./arkts-basic-components-web-attributes.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
**Return value**
| Type | Description |
| ------ | ------------ |
| string | URL of the last frame from which the JavaScript proxy object was called.|
**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](./arkts-apis-webview-e.md#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](./arkts-apis-webview-WebSchemeHandler.md) class for the current Web component to intercept requests of the specified scheme.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | :------------------------ |
| scheme | string | Yes | Protocol to be intercepted.|
| handler | [WebSchemeHandler](./arkts-apis-webview-WebSchemeHandler.md) | 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](./arkts-apis-webview-WebSchemeHandler.md) | 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. Before using the camera, add the **ohos.permission.CAMERA** permission to **module.json5**. For details about how to add the permission, see [Declaring Permissions in the Configuration File](../../security/AccessToken/declare-permissions.md).
**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();
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
uiContext: UIContext = this.getUIContext();
aboutToAppear(): void {
let context: Context | undefined = this.uiContext.getHostContext() 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);
})
}
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) {
this.uiContext.showAlertDialog({
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](./arkts-apis-webview-i.md#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;
context: UIContext;
}
let storage : LocalStorage | undefined = undefined;
export class NodeControllerImpl extends NodeController {
private rootNode: BuilderNode | null = null;
private wrappedBuilder: WrappedBuilder | null = null;
constructor(wrappedBuilder: WrappedBuilder, context: UIContext) {
storage = context.getSharedLocalStorage();
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, data.context);
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, data.context);
})
.fileAccess(true)
}
export const precompileWebview = wrapBuilder(WebBuilder);
export const precompile = async (controller: WebviewController, configs: Array, context: UIContext) => {
for (const config of configs) {
let content = await readRawFile(config.localPath, context);
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, context: UIContext) {
try {
return await context.getHostContext()!.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, context: this.getUIContext()});
}
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,
context: this.getUIContext()
});
})
// 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 of the web page](./arkts-basic-components-web-attributes.md#enablenativemediaplayer12) and a media file 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](./arkts-apis-webview-t.md#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