WebviewController is the core controller for various behaviors of the Web component, providing extensive functions such as page loading and navigation control, JavaScript interaction, lifecycle management, scroll control, page zoom and content search, message port communication, and cache and certificate management. A WebviewController object can control only one Web component, and methods on WebviewController (except static methods) can be called only after the Web component is bound to WebviewController.
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.
The sample effect is subject to the actual device.
constructor(webTag?: string)
Constructs a WebviewController object.
No parameter: new webview.WebviewController() indicates an empty constructor. No parameter is required when the C API is not used.
Parameter is a valid string: new webview.WebviewController("xxx"), used for developers to distinguish multiple instances and call methods under the corresponding instance.
Empty parameter: new webview.WebviewController("") or new webview.WebviewController(undefined). In this scenario, the parameter is meaningless and cannot distinguish multiple instances. undefined is returned directly, and developers need to check whether the return value is normal.
After the Web component is destroyed, it is unbound from WebViewController. Subsequently, calling non-static methods of WebviewController will throw a 17100001 exception. Pay attention to the call timing and catch 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
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
class WebObj {
constructor() {
}
webTest(): string {
console.info('Web test');
return "Web test";
}
webString(): void {
console.info('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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="htmlTest()">Click Me!</button>
<p id="demo"></p>
<p id="webDemo"></p>
<script type="text/javascript">
function htmlTest() {
// This function call expects to return "Web test"
let webStr = objTestName.webTest();
document.getElementById("webDemo").innerHTML=webStr;
console.info('objTestName.webTest result:'+ webStr)
}
</script>
</body>
</html> static initializeWebEngine(): void
Loads the dynamic library file of the web engine through this API before the Web component is initialized, so as to improve startup performance. It also automatically preconnects to frequently visited websites in history.
System capability: SystemCapability.Web.Webview.Core
Example
This example uses EntryAbility to describe how to load the dynamic library of the Web component during the Ability creation phase.
// EntryAbility.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.info("EntryAbility onCreate")
webview.WebviewController.initializeWebEngine()
console.info("EntryAbility onCreate done")
}
} 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 | 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 Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
Example
// EntryAbility.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.info("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.info("EntryAbility onCreate done")
}
} static setWebDebuggingAccess(webDebuggingAccess: boolean): void
Sets whether to enable web debugging. For details, see Debugging Frontend Pages by Using DevTools.
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 feature in the officially released version of the application.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| webDebuggingAccess | boolean | Yes | Sets whether to enable web debugging. The value true means to enable web debugging, and false means the opposite. Default value: false. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3.Parameter verification failed. |
Example
// 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(url: string | Resource, headers?: Array<WebHeader>): 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> | No | Additional HTTP request header of the URL. Default value: []. If undefined or null is passed, error code 401 will be thrown. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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. |
| 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
// 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 })
}
}
} // 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:
// 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 })
}
}
} Using the resource://rawfile/ protocol prefix can avoid the issue where the URL is truncated by the number sign (#) when the conventional $rawfile method is used to handle URLs containing "#" for routing. When a URL contains a "#", the content following the "#" is treated as a fragment.
// 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#home");
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} Create an index.html file in src/main/resources/rawfile.
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<div id="content"></div>
<script>
function loadContent() {
var hash = window.location.hash;
var contentDiv = document.getElementById('content');
if (hash === '#home') {
contentDiv.innerHTML = '<h1>Home Page</h1><p>Welcome to the Home Page!</p>';
} else {
contentDiv.innerHTML = '<h1>Default Page</h1><p>This is the default content.</p>';
}
}
// Load the UI.
window.addEventListener('load', loadContent);
// Update the UI when the hash changes.
window.addEventListener('hashchange', loadContent);
</script>
</body>
</html> HTML file to be loaded:
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html> 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.
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 <meta name="viewport" content="width=device-width, initial-scale=1.0" charset="utf-8"> 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. If undefined or null is passed, error code 401 will be thrown. |
| 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. If undefined or null is passed, error code 401 will be thrown. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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. Applicable versions: 9-10 |
| 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:
// 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(
"<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
"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 })
}
}
} // 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 })
}
}
} Specifies baseUrl.
// 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(
"<img src=aa/bb.jpg>", // 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:
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
updateContent: string = '<body><div><image src="resource://rawfile/xxx.png" alt="image -- end" width="500" height="250"></image></div></body>'
build() {
Column() {
Button('loadData')
.onClick(() => {
try {
// UTF-8 is charset.
this.controller.loadData(this.updateContent, "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 })
}
}
} Load the sandbox image.
// 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(
"<img src=bb.jpg>", // Try to download the image from "file:///xxx/" + "bb.jpg".
"text/html",
"UTF-8",
// Load the image path in the local application sandbox. Change the path to the actual sandbox path.
"file:///data/storage/el2/base/haps/entry/files/data/.cache_dir/",
""
);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.fileAccess(true) // Enable the file access functionality to load images in the application sandbox.
}
}
} accessForward(): boolean
Checks whether going to the next page can be performed on the current page.
You can use getBackForwardEntries to obtain the historical information list of the current WebView and use 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info('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(): void
Moves forward by one page in the history stack. Generally used together with accessForward.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): boolean
Checks whether going to the previous page can be performed on the current page.
You can use getBackForwardEntries to obtain the historical information list of the current WebView and use accessStep to determine whether to move forward or backward based on the specified number of steps.
If setCustomUserAgent is called when the Web component is loaded for the first time, the value of accessBackward 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 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info('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(): void
Moves to the previous page based on the history stack. This API is generally used together with accessBackward.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): 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).
If the page was previously in the inactive state, the event listener registered through document.addEventListener('visibilitychange',...) in the H5 page will be triggered, and document.visibilityState changes from "hidden" to "visible".
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): 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. To reactivate the Web component, use onActive.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} refresh(ignoreCache: boolean): void
Notifies the Web component to refresh the web page. You can choose whether to ignore the cache refresh.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| ignoreCache | boolean | Yes | Whether to ignore cache refresh when the Web component refreshes the web page. The value true means to ignore the cache refresh, and false means the opposite. NOTE If undefined or null is passed in, the value is false. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(true);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} 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 and Universal Error Codes.
| 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
// 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.info('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(): 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(jsObject: object, name: string, methodList: Array<string>, asyncMethodList?: Array<string>, 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.
For the example, see Invoking Application Functions on the Frontend Page.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| jsObject | 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. 1. The parameter and return value can be any of the following types: string, number, boolean. 2. Dictionary or Array, with a maximum of 10 nested layers and 10,000 data records per layer. 3. Object, which must contain the methodNameListForJsProxy:[fun1, fun2] attribute, where fun1 and fun2 are methods that can be called. 4. The parameter also supports Function and Promise. Their callback cannot have return values. 5. The return value supports Promise. Its callback cannot have a return value. |
| 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<string> | Yes | Synchronous methods of the JavaScript object to be registered at the application side. |
| asyncMethodList12+ | Array<string> | 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. If undefined or null is passed, error code 401 will be thrown. |
| 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. 1. The scheme and host parameters cannot be empty. The host does not support wildcards and can contain only complete host names. 2. You can configure only the object-level trustlist, which takes effect for all JSBridge methods. 3. If method-level trustlists are configured for JSBridge method A, the intersection of object-level and method-level trustlists takes effect. If undefined or null is passed, error code 401 will be thrown. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
class TestObj {
constructor() {
}
test(testStr: string): string {
console.info('Web Component str' + testStr);
return testStr;
}
toString(): void {
console.info('Web Component toString');
}
testNumber(testNum: number): number {
console.info('Web Component number' + testNum);
return testNum;
}
asyncTestBool(testBol: boolean): void {
console.info('Web Component boolean' + testBol);
}
}
class WebObj {
constructor() {
}
webTest(): string {
console.info('Web test');
return "Web test";
}
webString(): void {
console.info('Web test toString');
}
}
class AsyncObj {
constructor() {
}
asyncTest(): void {
console.info('Async test');
}
asyncString(testStr: string): void {
console.info('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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="htmlTest()">Click Me!</button>
<p id="demo"></p>
<p id="webDemo"></p>
<p id="asyncDemo"></p>
<script type="text/javascript">
function htmlTest() {
// This function call expects to return "ArkUI Web Component"
let str=objName.test("webtest data");
objName.testNumber(1);
objName.asyncTestBool(true);
document.getElementById("demo").innerHTML=str;
console.info('objName.test result:'+ str)
// This function call expects to return "Web test"
let webStr = objTestName.webTest();
document.getElementById("webDemo").innerHTML=webStr;
console.info('objTestName.webTest result:'+ webStr)
objAsyncName.asyncTest();
objAsyncName.asyncString("async test data");
}
</script>
</body>
</html> For more examples, see Invoking Application Functions on the Frontend Page.
runJavaScript(script: string, callback : AsyncCallback<string>): 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.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| script | string | Yes | JavaScript script. |
| callback | AsyncCallback<string> | 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 and Universal Error Codes.
| 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. |
| 17100003 | Calling a JS method that returns an empty ArrayBuffer via runJavaScript. |
Example
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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Hello world!
<script type="text/javascript">
function test() {
console.info('Ark WebComponent')
return "This value is from index.html"
}
</script>
</body>
</html> runJavaScript(script: string): Promise<string>
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.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| script | string | Yes | JavaScript script. |
Return value
| Type | Description |
|---|---|
| Promise<string> | 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 and Universal Error Codes.
| 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. |
| 17100003 | Calling a JS method that returns an empty ArrayBuffer via runJavaScript. |
Example
// 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.info('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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
Hello world!
<script type="text/javascript">
function test() {
console.info('Ark WebComponent')
return "This value is from index.html"
}
</script>
</body>
</html> runJavaScriptExt(script: string | ArrayBuffer, callback : AsyncCallback<JsMessageExt>): 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> | Yes | Callback used to return the result. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
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 {
if (result.getErrorDescription()) {
// If an exception occurs or the return type is not supported, getErrorDescription is not empty.
console.info(`runJavaScriptExt getErrorDescription: ${result.getErrorDescription()}`);
return;
}
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}`);
}
}
});
if (e) {
console.info('url: ', e.url);
}
} catch (resError) {
console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`);
}
})
}
}
} // 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 {
if (result.getErrorDescription()) {
// If an exception occurs or the return type is not supported, getErrorDescription is not empty.
console.info(`runJavaScriptExt getErrorDescription: ${result.getErrorDescription()}`);
return;
}
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 (resError) {
console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`);
}
})
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
}
}
} HTML file to be loaded:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en-gb">
<body>
<h1>run JavaScript Ext demo</h1>
</body>
<script type="text/javascript">
function test() {
return "hello, world";
}
</script>
</html> runJavaScriptExt(script: string | ArrayBuffer): Promise<JsMessageExt>
Executes a JavaScript script asynchronously and returns the script execution result through a promise. runJavaScriptExt can be invoked only after loadUrl is executed, for example, 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> | Promise used to return the script execution result. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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 {
if (result.getErrorDescription()) {
// If an exception occurs or the return type is not supported, getErrorDescription is not empty.
console.info(`runJavaScriptExt getErrorDescription: ${result.getErrorDescription()}`);
return;
}
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);
})
})
}
}
} // 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 {
if (result.getErrorDescription()) {
// If an exception occurs or the return type is not supported, getErrorDescription is not empty.
console.info(`runJavaScriptExt getErrorDescription: ${result.getErrorDescription()}`);
return;
}
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:
<!-- index.html -->
<!DOCTYPE html>
<html lang="en-gb">
<body>
<h1>run JavaScript Ext demo</h1>
</body>
<script type="text/javascript">
function test() {
return "hello, world";
}
</script>
</html> deleteJavaScriptRegister(name: string): void
Deletes a JavaScript object with the specified name on the application side that is registered with the window using registerJavaScriptProxy or javaScriptProxy. The deletion takes effect after the page is reloaded.
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 and Universal Error Codes.
| 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
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
class TestObj {
constructor() {
}
test(): string {
return "ArkUI Web Component";
}
toString(): void {
console.info('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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="htmlTest()">Click Me!</button>
<p id="demo"></p>
<script type="text/javascript">
function htmlTest() {
let str=objName.test();
document.getElementById("demo").innerHTML=str;
console.info('objName.test result:'+ str)
}
</script>
</body>
</html> zoom(factor: number): void
Zooms in or out of this web page. This API is effective only when 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 and Universal Error Codes.
| 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
// 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 = 2;
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(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.
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 and Universal Error Codes.
| 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
// 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.info("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting);
}
})
}
}
} HTML file to be loaded:
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World Highlight Hello World</p>
</body>
</html> clearMatches(): void
Clears the matches found through searchAllAsync.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.
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 and Universal Error Codes.
| 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
// 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.
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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(isExtentionType?: boolean): Array<WebMessagePort>
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. If undefined or null is passed, error code 401 will be thrown. |
Return value
| Type | Description |
|---|---|
| Array<WebMessagePort> | List of web message ports. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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. Applicable version: 10+ |
Example
For details about the sample code, see onMessageEventExt.
postMessage(name: string, ports: Array<WebMessagePort>, 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> | 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 and Universal Error Codes.
| 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
// 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.info("received string message from html5, string is:" + result);
msg = msg + result;
} else if (typeof (result) == "object") {
if (result instanceof ArrayBuffer) {
console.info("received arraybuffer from html5, length is:" + result.byteLength);
msg = msg + "length is " + result.byteLength;
} else {
console.info("not support");
}
} else {
console.info("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:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebView Message Port Demo</title>
</head>
<body>
<h1>WebView Message Port Demo</h1>
<div>
<input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
<input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
<script src="xxx.js"></script>
</html> // 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.info("received string message from html5, string is:" + result);
msg = msg + result;
} else if (typeof(result) == "object") {
if (result instanceof ArrayBuffer) {
console.info("received arraybuffer from html5, length is:" + result.byteLength);
msg = msg + "length is " + result.byteLength;
} else {
console.info("not support");
}
} else {
console.info("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(): void
Requests focus for the specified component.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100004 | Function not enabled. |
Example
// 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(): 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100004 | Function not enabled. |
Example
// 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(): number
Obtains the index value of the Web component, which can be used for managing multiple Web components.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| number | Index of the Web component. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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(): string
Obtains the default user agent of this web page.
For details about the default User-Agent, see Developing User-Agent.
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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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.
// 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(): 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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(): number
Obtains the height of this web page. For details, see Obtaining the Web Page Content Height.
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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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(baseName: string, autoName: boolean, callback: AsyncCallback<string>): 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 the file is stored with the file name specified by baseName, and true means the file name is automatically generated based on the current URL and stored in the directory specified by baseName. |
| callback | AsyncCallback<string> | 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 and Universal Error Codes.
| 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
// 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(baseName: string, autoName: boolean): Promise<string>
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 the file is stored with the file name specified by baseName, and true means the file name is automatically generated based on the current URL and stored in the directory specified by baseName. |
Return value
| Type | Description |
|---|---|
| Promise<string> | 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 and Universal Error Codes.
| 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
// 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(): string
Obtains the URL of the current page.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| string | URL address of the current page. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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(): void
Stops page loading.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(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 and Universal Error Codes.
| 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
// 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(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. If null or undefined is passed, error code 401 is thrown. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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); // 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:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
body {
width:2000px;
height:2000px;
padding-right:170px;
padding-left:170px;
border:5px solid blueviolet;
}
</style>
</head>
<body>
Scroll Test
</body>
</html> 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. If null or undefined is passed, error code 401 is thrown. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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. |
Calling scrollBy does not trigger the nested scrolling of the parent component.
Example
// 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); // 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:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
body {
width:2000px;
height:2000px;
padding-right:170px;
padding-left:170px;
border:5px solid blueviolet;
}
</style>
</head>
<body>
Scroll Test
</body>
</html> 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. Unit: vp |
| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward. Unit: vp |
Return value
| Type | Description |
|---|---|
| boolean | The value true indicates that the current web page can be scrolled, and false indicates that the current web page cannot be scrolled. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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.info("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:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
body {
width:2000px;
height:2000px;
padding-right:170px;
padding-left:170px;
border:5px solid blueviolet;
}
</style>
</head>
<body>
Scroll Test
</body>
</html> 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 swipe scrolling, where rightward is the positive direction. Unit: vp/s. |
| vy | number | Yes | Vertical velocity component of swipe scrolling, where downward is the positive direction. Unit: vp/s. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<title>Demo</title>
<style>
body {
width:3000px;
height:3000px;
padding-right:170px;
padding-left:170px;
border:5px solid blueviolet;
}
</style>
</head>
<body>
Scroll Test
</body>
</html> getOriginalUrl(): string
Obtains the original URL of the current page.
Risk warning: If you want to obtain the URL for JavaScriptProxy communication API authentication, use getLastJavascriptProxyCallingFrameUrl12+.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| string | Original URL address of the current page. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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(): image.PixelMap
Obtains the favicon of this page.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| image.PixelMap | PixelMap object of the favicon of the page. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(enable: boolean): void
Sets the window.navigator.onLine attribute in JavaScript.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable the window.navigator.onLine attribute. 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 and Universal Error Codes.
| 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
// 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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<h1>online attribute </h1>
<p id="demo"></p>
<button onclick="func()">click</button>
<script>
// Check whether the browser is online.
var online1 = navigator.onLine;
document.getElementById("demo").innerHTML = "Browser online:" + online1;
function func(){
var online2 = navigator.onLine;
document.getElementById("demo").innerHTML = "Browser online:" + online2;
}
</script>
</body>
</html> hasImage(callback: AsyncCallback<boolean>): 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<boolean> | 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 and Universal Error Codes.
| 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
// 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(): Promise<boolean>
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<boolean> | 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 and Universal Error Codes.
| 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
// 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(clearRom: boolean): void
Removes all resource caches generated by Webview in the app.
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 and Universal Error Codes.
| 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
// 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 })
}
}
} static removeAllCache(clearRom: boolean): void
Removes all resource caches generated by Webview (including private mode) in the app.
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 Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
Example
// 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(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 and Universal Error Codes.
| 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
// 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: $rawfile("index.html"), controller: this.controller })
}
}
} <!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
<style>
.blue {
background-color: lightblue;
}
.green {
background-color: lightgreen;
}
.blue, .green {
font-size:16px;
height:200px;
text-align: center; /* Horizontally centered */
line-height: 200px; /* Vertically centered (the height matches the container height) */
}
</style>
</head>
<body>
<div class="blue" >webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
</body>
</html> 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 and Universal Error Codes.
| 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
// 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: $rawfile("index.html"), controller: this.controller })
}
}
} HTML file to be loaded:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
<style>
.blue {
background-color: lightblue;
}
.green {
background-color: lightgreen;
}
.blue, .green {
font-size:16px;
height:200px;
text-align: center; /* Horizontally centered */
line-height: 200px; /* Vertically centered (the height matches the container height) */
}
</style>
</head>
<body>
<div class="blue" >webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
</body>
</html> getBackForwardEntries(): BackForwardList
Obtains the historical information list of the current WebView.
onLoadIntercept 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 | The history list of the current WebView. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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(): 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 state history of the current WebView. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} Obtain the path of the application cache file.
// 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(state: Uint8Array): void
The current WebView restores the page state history from serialized data.
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 and Universal Error Codes.
| 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
// 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 })
}
}
} Obtain the path of the application cache file.
// 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);
}
} static customizeSchemes(schemes: Array<WebCustomScheme>): void
Grants the cross-domain request and fetch request permissions for custom protocol URLs to the web kernel. When the Web performs a cross-domain fetch of a custom protocol URL, the fetch request can be intercepted by the onInterceptRequest event API, so that developers can further process the request. It is recommended to call this API before any Web component is initialized.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| schemes | Array<WebCustomScheme> | Yes | Array of up to 10 custom schemes. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
| 17100020 | Failed to register custom schemes. Supported versions: 12+ |
Example
// 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.info('url:' + event.request.getRequestUrl());
}
return this.responseWeb;
})
}
}
} static customizeSchemes(schemes: Array<WebCustomScheme>, lazyInitWebEngine: boolean): void
Grants the cross-domain request and fetch request permissions for custom protocol URLs to the web kernel. When the Web performs a cross-domain fetch of a custom protocol URL, the fetch request can be intercepted by the onInterceptRequest event API, so that developers can further process the request. It is recommended to call this API before any Web component is initialized.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| schemes | Array<WebCustomScheme> | Yes | Array of up to 10 custom schemes. |
| lazyInitWebEngine | boolean | Yes | Whether to skip WebEngine initialization in the API. The value true means to skip the WebEngine initialization and store the registered schemes temporarily. When the WebEngine is initialized, the schemes are transferred to the WebEngine. The value false means to initialize the WebEngine automatically in the API. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. The length of the schemes array is greater than 10. 2. The character length of the scheme is greater than 32. 3. The character in the scheme is not within the allowed range of lowercase English letters, numbers, and the symbols ".", "+", "-". |
| 17100020 | Failed to register custom schemes. |
Example
// 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], 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 })
}
}
} getCertificate(): Promise<Array<cert.X509Cert>>
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 of the current website.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| Promise<Array<cert.X509Cert>> | 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a web component. |
Example
// 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<cert.X509Cert>) {
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<cert.X509Cert>) => {
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<cert.X509Cert>) => {
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%')
}
}
} getCertificate(callback: AsyncCallback<Array<cert.X509Cert>>): void
Obtains the certificate information of the current 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 (for the X509Cert certificate type definition, see X509Cert) of the current website, so that developers can display the website certificate information.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | AsyncCallback<Array<cert.X509Cert>> | 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 and Universal Error Codes.
| 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
// 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<cert.X509Cert>) {
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<cert.X509Cert>) => {
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<cert.X509Cert>) => {
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%')
}
}
} setAudioMuted(mute: boolean): void
Mutes the web page. Typical use cases include: the app needs to control the web page volume (such as providing a mute switch), or needs to mute during background playback.
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 and Universal Error Codes.
| 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
// 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 })
}
}
} prefetchPage(url: string, additionalHeaders?: Array<WebHeader>, prefetchOptions?: PrefetchOptions): 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.
The downloaded page resources are cached for about five minutes. After this period, the Web component automatically releases them.
prefetchPage can also normally prefetch 302 redirect pages.
When prefetchPage is executed first and then the page is loaded, the prefetched resources are loaded directly from the cache.
prefetchPage caches all resources except those with the Cache-Control: no-store header. If a Vary response header or Cache-Control: no-store header exists, or the downloaded page resources have been cached for more than five minutes, the resources are revalidated before use.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| url | string | Yes | URL to preload. |
| additionalHeaders | Array<WebHeader> | No | Additional HTTP request headers for the URL. Default value: [] |
| prefetchOptions | PrefetchOptions | No | Options for customizing the prefetch behavior. The minimum interval between two prefetches is 500 ms. By default, Cache-Control: no-store in the response header is not ignored. |
Error codes
For details about the error codes, see Webview Error Codes.
| 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. Applicable to version: 21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Applicable to version: 22+ |
Example
// 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.
let options = new webview.PrefetchOptions();
options.ignoreCacheControlNoStore = true;
options.minTimeBetweenPrefetchesMs = 100;
this.controller.prefetchPage('https://www.example.com', [{ headerKey: "headerKey", headerValue: "headerValue" }], options);
} 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 })
}
}
} prefetchPage(url: string, additionalHeaders?: Array<WebHeader>): 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.
The downloaded page resources are cached for about five minutes. After this period, the Web component automatically releases them.
prefetchPage can also normally prefetch 302 redirect pages.
When prefetchPage is executed first and then the page is loaded, the prefetched resources are loaded directly from the cache.
When multiple URLs are prefetched consecutively with prefetchPage, only the first one takes effect.
prefetchPage has a time limit. Multiple prefetches cannot be performed within 500 ms.
prefetchPage caches all resources except those with the Cache-Control: no-store header. If a Vary response header or Cache-Control: no-store header exists, or the downloaded page resources have been cached for more than five minutes, the resources are revalidated before use.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| url | string | Yes | URL to preload. |
| additionalHeaders | Array<WebHeader> | No | Additional HTTP request headers for the URL. Default value: [] |
Error codes
For details about the error codes, see Webview Error Codes.
| 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. Applicable version: 10-21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Applicable to version: 22+ |
Example
// 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 })
}
}
} static prefetchResource(request: RequestInfo, additionalHeaders?: Array<WebHeader>, cacheKey?: string, cacheValidTime?: number): void
Prefetches resource requests based on specified request information and additional HTTP request headers, saves them to the memory cache, and specifies the cache key and validity period to accelerate loading. Currently, only POST requests with Content-Type of application/x-www-form-urlencoded are supported. A maximum of six POST requests can be prefetched. To prefetch a seventh one, use clearPrefetchedResource to clear unnecessary POST request caches. Otherwise, the earliest prefetched POST cache is automatically cleared. To use the prefetched resource cache, developers need to add the key-value pair "ArkWebPostCacheKey" to the request header of the actual POST request, with the value being the cacheKey of the corresponding cache.
Resources in the memory cache are automatically managed by the kernel. When too many resources are injected, causing excessive memory pressure, the kernel automatically releases unused resources. However, injecting a large number of resources into the memory cache should still be avoided.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| request | RequestInfo | Yes | Information about the prefetched request. |
| additionalHeaders | Array<WebHeader> | No | Additional HTTP request header of the prefetched request. If undefined or null is passed, error code 401 will be thrown. |
| 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. If undefined or null is passed, error code 401 will be thrown. |
| cacheValidTime | number | No | Validity period of the prefetched resource cache. Value range: (0, 2147483647]. Default value: 300s. Unit: s. If undefined or null is passed in, an exception with error code 401 is thrown. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. 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. Supported versions: 12-21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Supported versions: 22+ |
Example
// EntryAbility.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.info("EntryAbility onCreate");
webview.WebviewController.initializeWebEngine();
// During prefetching, replace "https://www.example1.com/post?e=f&g=h" with the actual website address to be accessed.
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.info("EntryAbility onCreate done");
}
} static clearPrefetchedResource(cacheKeyList: Array<string>): 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.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| cacheKeyList | Array<string> | 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
// Index.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(() => {
// During prefetching, replace "https://www.example1.com/post?e=f&g=h" with the actual website address to be accessed.
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",]);
})
}
}
} static prepareForPageLoad(url: string, preconnectable: boolean, numSockets: number): void
Preconnects to a URL. Call this API before loading the URL. It only performs DNS resolution and socket connection for the URL, without fetching the main resource or sub-resources.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| url | string | Yes | URL for preconnection. |
| preconnectable | boolean | Yes | Whether to perform preconnection. If the value is true, DNS resolution and socket connection preconnection are performed for the URL. If the value is false, no preconnection operation is performed. |
| 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.
| ID | Error Message |
|---|---|
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. Applicable version: 10-21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Applicable to version: 22+ |
| 17100013 | The number of preconnect sockets is invalid. |
Example
// EntryAbility.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.info("EntryAbility onCreate");
webview.WebviewController.initializeWebEngine();
// During preconnection, replace 'https://www.example.com' with a real website address.
webview.WebviewController.prepareForPageLoad("https://www.example.com", true, 2);
AppStorage.setOrCreate("abilityWant", want);
console.info("EntryAbility onCreate done");
}
} 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, it is recommended to set User-Agent in the onControllerAttached callback. Do not set it in the onLoadIntercept callback, as this may cause the setting to fail or lead to unexpected results.
If User-Agent is not set in the onControllerAttached callback, calling setCustomUserAgent later may cause an anomaly where the loaded page does not match the actually set User-Agent.
When src of the Web component is not set to a URL, it is recommended to call setCustomUserAgent to set User-Agent first, and then use loadUrl to load a specific page.
For the definition and usage scenarios of the default User-Agent, see User-Agent Development Guide
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 and then customize the obtained user agent. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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.info("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}`);
}
})
}
}
} setDownloadDelegate(delegate: WebDownloadDelegate): void
Sets a WebDownloadDelegate for the current Web component. The delegate is used to receive the download progress triggered within the page.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| delegate | WebDownloadDelegate | Yes | Delegate used to receive the download progress. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} startDownload(url: string): void
Uses the download capability of the Web component to download a specified URL, for example, downloading a specified image from a web page.
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.
| 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. Applicable versions: 11-21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Applicable to version: 22+ |
Example
// 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 })
}
}
} getCustomUserAgent(): string
Obtains a custom user agent.
For details about the default User-Agent, see Developing User-Agent.
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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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 })
}
}
} 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.
For details about the default User-Agent definition, application scenarios, and API priorities, see Developing 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 getDefaultUserAgent and then customize the obtained user agent. |
Example
// 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 })
}
}
} static setUserAgentForHosts(userAgent: string, hosts: Array<string>): 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 to load a specific page.
For details about the default User-Agent definition, application scenarios, and API priorities, see Developing 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 getDefaultUserAgent and then customize the obtained user agent. |
| hosts | Array<string> | 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. |
Example
// 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 })
}
}
} static setConnectionTimeout(timeout: number): void
Sets the network connection timeout interval. You can use the onErrorReceive method in the Web component to obtain the timeout error code. If this API is not called, the default timeout interval is 30 seconds.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| timeout | number | Yes | Socket connection timeout duration, in seconds. The value must be a positive integer. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. 3. Parameter verification failed. |
Example
// 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.info("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.info('getErrorInfo:' + event.error.getErrorInfo());
console.info('getErrorCode:' + event.error.getErrorCode());
}
})
}
}
} static warmupServiceWorker(url: string): void
Warms up ServiceWorker to improve the loading speed of the first screen page (only for pages that use ServiceWorker). Call this API before loading the URL.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| url | string | Yes | URL of the ServiceWorker to preload. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. Applicable versions: 12-21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Applicable to version: 22+ |
Example
// EntryAbility.ets
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.info("EntryAbility onCreate");
webview.WebviewController.initializeWebEngine();
webview.WebviewController.warmupServiceWorker("https://www.example.com");
AppStorage.setOrCreate("abilityWant", want);
}
} 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. HarmonyOS 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 and DidRedirectNavigation in WebContentsObserver for detection.
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 Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
Example
// 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.info("enableSafeBrowsing: true");
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} 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
// 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.info("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} enableIntelligentTrackingPrevention(enable: boolean): void
Enables intelligent tracking prevention.
System capability: SystemCapability.Web.Webview.Core
Device behavior differences: This API is supported on phones, PCs/2-in-1 devices, tablets, and TVs. Since API version 18, it returns error code 801 on wearable devices.
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
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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. Applicable version: 18+ |
Example
// 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.info("enableIntelligentTrackingPrevention: true");
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} isIntelligentTrackingPreventionEnabled(): boolean
Obtains whether the Web component has enabled intelligent tracking prevention.
System capability: SystemCapability.Web.Webview.Core
Device behavior differences: This API is supported on phones, PCs/2-in-1 devices, tablets, and TVs. Since API version 18, it returns error code 801 on wearable devices.
Return value
| Type | Description |
|---|---|
| boolean | Whether the Web component has enabled the smart anti-tracking feature. The value true indicates that the smart anti-tracking feature is enabled, and false indicates that it is not enabled. Default value: false |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 801 | Capability not supported. Applicable version: 18+ |
Example
// 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.info("result: " + result);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} static addIntelligentTrackingPreventionBypassingList(hostList: Array<string>): void
Adds a list of domain names that bypass intelligent tracking prevention.
System capability: SystemCapability.Web.Webview.Core
Device behavior differences: This API is supported on phones, PCs/2-in-1 devices, tablets, and TVs. Since API version 18, it returns error code 801 on wearable devices.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| hostList | Array<string> | Yes | List of domain names that bypass intelligent tracking prevention. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
| 801 | Capability not supported. Applicable version: 18+ |
Example
// 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 })
}
}
} static removeIntelligentTrackingPreventionBypassingList(hostList: Array<string>): void
Deletes the domain names from the list of domain names added through the addIntelligentTrackingPreventionBypassingList API.
System capability: SystemCapability.Web.Webview.Core
Device behavior differences: This API is supported on phones, PCs/2-in-1 devices, tablets, and TVs. Since API version 18, it returns error code 801 on wearable devices.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| hostList | Array<string> | Yes | List of domain names that bypass intelligent tracking prevention. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
| 801 | Capability not supported. Applicable version: 18+ |
Example
// 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 })
}
}
} static clearIntelligentTrackingPreventionBypassingList(): void
Deletes all domain names from the list of domain names added through the addIntelligentTrackingPreventionBypassingList API.
System capability: SystemCapability.Web.Webview.Core
Device behavior differences: This API is supported on phones, PCs/2-in-1 devices, tablets, and TVs. Since API version 18, it returns error code 801 on wearable devices.
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. Supported since: 18+ |
Example
// 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 })
}
}
} 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.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| string | Default User-Agent string of ArkWeb. |
Example
// EntryAbility.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.info("EntryAbility onCreate");
webview.WebviewController.initializeWebEngine();
let defaultUserAgent = webview.WebviewController.getDefaultUserAgent();
console.info("defaultUserAgent: " + defaultUserAgent);
}
} 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
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 and Universal Error Codes.
| 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. Supported since: 18+ |
Example
// 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.info("enableAdsBlock: true")
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} 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
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 Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. Supported since: 18+ |
Example
// 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.info("isAdsBlockEnabled:", isAdsBlockEnabled);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} 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 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
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 Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. Supported since: 18+ |
Example
// 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.info("isAdsBlockEnabledForCurPage:", isAdsBlockEnabledForCurPage);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} static setRenderProcessMode(mode: RenderProcessMode): void
Sets the ArkWeb rendering subprocess mode. You can select the appropriate mode based on the app's requirements for memory usage and rendering process isolation.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | RenderProcessMode | Yes | Render subprocess mode. You can call getRenderProcessMode() 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. By default, mobile phones use the single render subprocess mode, and tablets and PCs/2in1 devices use 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 Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
Example
// 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 })
}
}
} static getRenderProcessMode(): RenderProcessMode
Obtains the ArkWeb render subprocess mode.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| RenderProcessMode | 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
// 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.info("getRenderProcessMode: " + mode);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("terminateRenderProcess result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} postUrl(url: string, postData: ArrayBuffer): void
Loads a URL with postData using the "POST" method. If the URL is not a network URL, the loadUrl method is used to load the URL, and the postData parameter is 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 and Universal Error Codes.
| 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. |
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Incorrect parameter types. |
Example
// 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 })
}
}
} 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 | Adapter for the print document, which controls the print behavior and print task. It can print the current web page content through the print service. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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 })
}
}
} 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info('isIncognitoMode' + result);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} getSecurityLevel(): SecurityLevel
Obtains the security level of this web page.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| SecurityLevel | 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
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);
}
})
}
}
} 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 | 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. If null or undefined is passed, error code 401 is thrown. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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 })
}
}
} 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("scrollEnabled: " + scrollEnabled);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} setPrintBackground(enable: boolean): void
Sets whether to print the background of a web page. If the setting of this API is inconsistent with that of PrintAttributes, the setting of this API takes precedence.
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 and Universal Error Codes.
| 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
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 })
}
}
} getPrintBackground(): boolean
Obtains whether the web page background is printed.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether to print the web page background. The value true means to print the web page background; false means not to print the web page background. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
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.info("getPrintBackground: " + enable);
} catch (error) {
console.error(`ErrorCode:${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} getLastJavascriptProxyCallingFrameUrl(): string
Injects a JavaScript object into the window object through registerJavaScriptProxy or javaScriptProxy. This API obtains the URL of the frame that last called the injected object.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| string | URL of the frame of the last injected object. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info('Web Component str' + testStr + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl());
return testStr;
}
toString(): void {
console.info('Web Component toString ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl());
}
testNumber(testNum: number): number {
console.info('Web Component number' + testNum + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl());
return testNum;
}
testBool(testBol: boolean): boolean {
console.info('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.info('Web test ' + " url " + this.mycontroller.getLastJavascriptProxyCallingFrameUrl());
return "Web test";
}
webString(): void {
console.info('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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>
<button type="button" onclick="htmlTest()">Click Me!</button>
<p id="demo"></p>
<p id="webDemo"></p>
<script type="text/javascript">
function htmlTest() {
// This function call expects to return "ArkUI Web Component"
let str=objName.test("webtest data");
objName.testNumber(1);
objName.testBool(true);
document.getElementById("demo").innerHTML=str;
console.info('objName.test result:'+ str)
// This function call expects to return "Web test"
let webStr = objTestName.webTest();
document.getElementById("webDemo").innerHTML=webStr;
console.info('objTestName.webTest result:'+ webStr)
}
</script>
</body>
</html> static pauseAllTimers(): void
Pauses all WebView timers. While the timers are paused, timer operations such as setInterval and setTimeout in the web page are suspended. It is recommended to pause timers when the app enters the background and resume them when the app returns to the foreground, so as to save resources. This API can be used in pair with resumeAllTimers() to avoid timer state confusion.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Row() {
Button('PauseAllTimers')
.onClick(() => {
webview.WebviewController.pauseAllTimers();
})
}
Web({ src: $rawfile("index.html"), controller: this.controller })
}
}
} HTML file to be loaded:
<!DOCTYPE html>
<html>
<body>
<button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button>
<button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button>
<input style="width:300px;height:150px;font-size:50px" value="0" id="show_num">
</body>
</html>
<script>
var timer = null;
var num = 0;
function startTimer() {
timer = setInterval(function() {
document.getElementById("show_num").value = ++num;
}, 1000);
}
function resetTimer() {
clearInterval(timer);
document.getElementById("show_num").value = 0;
num = 0;
}
</script> static 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Row() {
Button('ResumeAllTimers')
.onClick(() => {
webview.WebviewController.resumeAllTimers();
})
Button('PauseAllTimers')
.onClick(() => {
webview.WebviewController.pauseAllTimers();
})
}
Web({ src: $rawfile("index.html"), controller: this.controller })
}
}
} HTML file to be loaded:
<!DOCTYPE html>
<html>
<body>
<button style="width:300px;height:150px;font-size:50px" onclick="startTimer()">start</button>
<button style="width:300px;height:150px;font-size:50px" onclick="resetTimer()">reset</button>
<input style="width:300px;height:150px;font-size:50px" value="0" id="show_num">
</body>
</html>
<script>
var timer = null;
var num = 0;
function startTimer() {
timer = setInterval(function() {
document.getElementById("show_num").value = ++num;
}, 1000);
}
function resetTimer() {
clearInterval(timer);
document.getElementById("show_num").value = 0;
num = 0;
}
</script> 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} getMediaPlaybackState(): MediaPlaybackState
Queries the audio and video playback status of the current web page.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| MediaPlaybackState | 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.info("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 })
}
}
} setWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void
Sets a WebSchemeHandler for the Web component. The WebSchemeHandler class is used to intercept requests of a specified scheme.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scheme | string | Yes | Protocol to be intercepted. |
| handler | WebSchemeHandler | Yes | Interceptor that intercepts this protocol. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| 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
// 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 })
}
}
} clearWebSchemeHandler(): void
Clears all WebSchemeHandlers set for the Web component.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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 })
}
}
} setServiceWorkerWebSchemeHandler(scheme: string, handler: WebSchemeHandler): void
Sets a WebSchemeHandler for all Web components of the current app, used to intercept requests of a specified scheme in ServiceWorker.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scheme | string | Yes | Protocol to be intercepted. |
| handler | WebSchemeHandler | Yes | Interceptor that intercepts this protocol. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Incorrect parameter types. |
Example
// 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 })
}
}
} clearServiceWorkerWebSchemeHandler(): void
Clears all WebSchemeHandlers that are set in the application and used to intercept ServiceWorker.
System capability: SystemCapability.Web.Webview.Core
Example
// 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 })
}
}
} 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.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<video id="video" width="400px" height="400px" autoplay>
</video>
<input type="button" title="HTML5 Camera" value="Enable Camera" onclick="getMedia()" />
<script>
function getMedia() {
let constraints = {
video: {
width: 500,
height: 500
},
audio: true
}
let video = document.getElementById("video");
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function(mediaStream) {
video.srcObject = mediaStream;
video.play();
})
}
</script>
</body>
</html> 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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
For the complete sample code, see startCamera.
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.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
For the complete sample code, see startCamera.
precompileJavaScript(url: string, script: string | Uint8Array, cacheOptions: CacheOptions): Promise<number>
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 | Yes | Whether to update the bytecode cache. |
Return value
| Type | Description |
|---|---|
| Promise<number> | 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 and Universal Error Codes.
| 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:
First, store the UIContext in localStorage in EntryAbility.
// 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>("uiContext", windowStage.getMainWindowSync().getUIContext());
});
}
} Write the basic code required by the dynamic component.
// 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<BuilderData[]> | null = null;
private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null;
constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>, 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>("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<BuilderData[]>, data: BuilderData) => {
const baseNode = new NodeControllerImpl(wrappedBuilder, data.context);
baseNode.initWeb(data.url, data.controller);
return baseNode;
} 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.
// 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<BuilderData[]>(WebBuilder);
export const precompile = async (controller: WebviewController, configs: Array<Config>, 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 data request. However, the HTTP response headers obtained through this method are not in the standard HTTP response header format. You need to convert the response headers to the standard HTTP response header format before use. For example, if the response header obtained through data request is e-tag, it needs to be converted to E-Tag before use.
Compile the code of the service component.
// 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<BuilderData[]>(WebBuilder); Write the resource configuration information.
// PrecompileConfig.ets
import { webview } from '@kit.ArkWeb'
export interface Config {
url: string,
localPath: string, // Local resource path
options: webview.CacheOptions
}
export let configs: Array<Config> = [
{
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"}
]
}
}
] Use the component on the page.
// 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.
onCreateNativeMediaPlayer(callback: CreateNativeMediaPlayerCallback): void
Registers a callback function. After enableNativeMediaPlayer is used to enable the app to take over web page media playback, the registered callback function is triggered when media is played on the web page.
If the application does not take over media playback on the web page, this callback is not invoked.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| callback | CreateNativeMediaPlayerCallback | Yes | Callback when the application takes over media playback on the web page. |
Example
// 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 <video> tag are changed.
// Make changes based on the information change.
}
play() {
// Start the native media player for playback.
}
pause() {
//Pause the playback on the local player.
}
seek(targetTime: number) {
// The local player jumps to a specified time point.
}
release() {
// Destroy the local player.
}
setVolume(volume: number) {
// The ArkWeb kernel requires to adjust the volume of the local player.
// Set the volume of the local player.
}
setMuted(muted: boolean) {
// Mute or unmute the local player.
}
setPlaybackRate(playbackRate: number) {
// Adjust the playback speed of the local player.
}
enterFullscreen() {
// Set the local player to play in full screen mode.
}
exitFullscreen() {
// Set the local player to exit full screen mode.
}
resumePlayer() {
// Create a player again.
// Resume the status information of the player.
}
suspendPlayer(type: webview.SuspendType) {
// Record the status information of the player.
// Destroy the player.
}
}
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.enableNativeMediaPlayer({enable: true, shouldOverlay: false})
.onPageBegin((event) => {
this.controller.onCreateNativeMediaPlayer((handler: webview.NativeMediaPlayerHandler, mediaInfo: webview.MediaInfo) => {
if (!shouldHandle(mediaInfo)) {
// The local player does not take over the media.
// The ArkWeb engine will play the media with its own player.
return null;
}
let nativePlayer: webview.NativeMediaPlayerBridge = new NativeMediaPlayerImpl(handler, mediaInfo);
return nativePlayer;
});
})
}
}
}
// stub
function getVolume() {
return 1;
}
function getCurrentPlayingTime() {
return 1;
}
function getCurrentBufferedTime() {
return 1;
}
function convertToSeconds(input: number) {
return input;
}
function getLastReadyState() {
return webview.ReadyState.HAVE_NOTHING;
}
function getCurrentReadyState() {
return webview.ReadyState.HAVE_NOTHING;
}
function shouldHandle(mediaInfo: webview.MediaInfo) {
return true;
} static enableWholeWebPageDrawing(): void
Enables the full drawing capability for the web page. This API works only during Web component initialization.
System capability: SystemCapability.Web.Webview.Core
Example
// 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.enableWholeWebPageDrawing();
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
} webPageSnapshot(info: SnapshotInfo, callback: AsyncCallback<SnapshotResult>): void
Obtains the full drawing result of the web page.
This API does not support concurrent calls.
Only supports taking snapshots of resources on the rendering process: static images and text.
If the page contains a video, a placeholder image of the video is displayed in the snapshot. If there is no placeholder image, a blank area is displayed.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| info | SnapshotInfo | Yes | Information for obtaining the full drawing result. |
| callback | AsyncCallback<SnapshotResult> | Yes | Callback used to return the result. |
Example
// 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('webPageSnapshot')
.onClick(() => {
try {
this.controller.webPageSnapshot({ id: "1234", size: { width: 100, height: 100 } }, (error, result) => {
if (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
return;
}
if (result) {
console.info(`return value is:${result}`);
// You can process the returned result as required.
}
});
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} injectOfflineResources(resourceMaps: Array<OfflineResourceMap>): void
Injects local offline resources to the memory cache to improve the initial page startup speed.
Resources in the memory cache are automatically managed by the ArkWeb engine. When the injected resources are excessive and cause significant memory pressure, the engine will automatically release unused resources. It is advisable to avoid injecting a large number of resources into the memory cache.
Under normal circumstances, the validity period of the resources is controlled by the provided Cache-Control or Expires response header, with a default validity period of 86,400 seconds, which is one day.
The MIME type of the resources is configured through the provided Content-Type response header. The Content-Type must comply with standards; otherwise, the resources cannot be used correctly. For resources of type MODULE_JS, a valid MIME type must be provided. For other types, the MIME type is optional.
Resources injected in this mode can be loaded only through HTML tags. If a script tag on the web page uses the crossorigin attribute, the Cross-Origin response header must be set in the responseHeaders parameter of the API. The value for this header should be anonymous or use-credentials.
After webview.WebviewController.SetRenderProcessMode(webview.RenderProcessMode.MULTIPLE) is called, the application starts the multi-rendering process mode. This API does not take effect in this scenario.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| resourceMaps | Array<OfflineResourceMap> | Yes | Configuration object for local offline resources. A maximum of 30 resources can be injected in a single call, with a maximum size of 10 MB per individual resource. |
Error codes
For details about the error codes, see Webview Error Codes.
| 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. |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2048. Supported versions: 12-21 |
| 17100002 | URL error. The webpage corresponding to the URL is invalid, or the URL length exceeds 2*1024*1024. Supported versions: 22+ |
Example
When appropriate, use this API in conjunction with dynamic components. Offline Web components are used to inject resources into the engine's memory cache, and at the appropriate time, the service Web components load and utilize these resources. The following is a code example:
First, store the UIContext in localStorage in EntryAbility.
// 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>("uiContext", windowStage.getMainWindowSync().getUIContext());
});
}
} Write the basic code required by the dynamic component.
// 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<BuilderData[]> | null = null;
private wrappedBuilder: WrappedBuilder<BuilderData[]> | null = null;
constructor(wrappedBuilder: WrappedBuilder<BuilderData[]>, 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>("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<BuilderData[]>, data: BuilderData) => {
const baseNode = new NodeControllerImpl(wrappedBuilder, data.context);
baseNode.initWeb(data.url, data.controller);
return baseNode;
} Write the component code for injecting resources. In this example, the local resource content reads the local file in the rawfile directory through the file reading API.
// InjectWebview.ets
import { webview } from '@kit.ArkWeb';
import { resourceConfigs } from "./Resource";
import { BuilderData } from "./DynamicComponent";
@Builder
function WebBuilder(data: BuilderData) {
Web({ src: data.url, controller: data.controller })
.onControllerAttached(async () => {
try {
data.controller.injectOfflineResources(await getData (data.context));
} catch (err) {
console.error("error: " + err.code + " " + err.message);
}
})
.fileAccess(true)
}
export const injectWebview = wrapBuilder<BuilderData[]>(WebBuilder);
export async function getData(context: UIContext) {
const resourceMapArr: Array<webview.OfflineResourceMap> = [];
// Read the configuration and read the file content from the rawfile directory.
for (let config of resourceConfigs) {
let buf: Uint8Array = new Uint8Array(0);
if (config.localPath) {
buf = await readRawFile(config.localPath, context);
}
resourceMapArr.push({
urlList: config.urlList,
resource: buf,
responseHeaders: config.responseHeaders,
type: config.type,
})
}
return resourceMapArr;
}
export async function readRawFile(url: string, context: UIContext) {
try {
return await context.getHostContext()!.resourceManager.getRawFileContent(url);
} catch (err) {
return new Uint8Array(0);
}
} Compile the code of the service component.
// 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<BuilderData[]>(WebBuilder); Write the resource configuration information.
// Resource.ets
import { webview } from '@kit.ArkWeb';
export interface ResourceConfig {
urlList: Array<string>,
type: webview.OfflineResourceType,
responseHeaders: Array<Header>,
localPath: string, // Path for storing local resources in the rawfile directory.
}
export const resourceConfigs: Array<ResourceConfig> = [
{
localPath: "example.png",
urlList: [
"https://www.example.com/",
"https://www.example.com/path1/example.png",
"https://www.example.com/path2/example.png",
],
type: webview.OfflineResourceType.IMAGE,
responseHeaders: [
{ headerKey: "Cache-Control", headerValue: "max-age=1000" },
{ headerKey: "Content-Type", headerValue: "image/png" },
]
},
{
localPath: "example.js",
urlList: [ // Provide only one URL, which serves as both the source of the resource and the network request address of the resource.
"https://www.example.com/example.js",
],
type: webview.OfflineResourceType.CLASSIC_JS,
responseHeaders: [
// Used in <script crossorigin="anonymous"/> mode to provide additional response headers.
{ headerKey: "Cross-Origin", headerValue:"anonymous" }
]
},
]; Use the component on the page.
// Index.ets
import { webview } from '@kit.ArkWeb';
import { NodeController } from '@kit.ArkUI';
import { createNode } from "./DynamicComponent"
import { injectWebview } from "./InjectWebview"
import { businessWebview } from "./BusinessWebview"
@Entry
@Component
struct Index {
@State injectNode: NodeController | undefined = undefined;
injectController: webview.WebviewController = new webview.WebviewController();
@State businessNode: NodeController | undefined = undefined;
businessController: webview.WebviewController = new webview.WebviewController();
aboutToAppear(): void {
// Initialize the Web component for injecting local resources. Provide an empty HTML page as the URL.
this.injectNode = createNode(injectWebview,
{ url: "https://www.example.com/empty.html", controller: this.injectController, 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);
}
}
} Example of a loaded HTML web page:
<!DOCTYPE html> <html lang="en"> <head></head> <body> <img src="https://www.example.com/path1/request.png" /> <img src="https://www.example.com/path2/request.png" /> <script src="https://www.example.com/example.js" crossorigin="anonymous"></script> </body> </html>
static setHostIP(hostName: string, address: string, aliveTime: number): void
Sets the IP address of the host after domain name resolution.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| hostName | string | Yes | Domain name of the host whose DNS records are to be added. |
| address | string | Yes | Host domain name resolution address (IPv4 and IPv6). |
| aliveTime | number | Yes | Cache validity period, in seconds. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. |
Example
For details, see clearHostIP.
static clearHostIP(hostName: string): void
Clears the IP address of a specified host after domain name resolution.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| hostName | string | Yes | Domain name of the host whose DNS records are to be cleared. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Incorrect parameter types.3. Parameter verification failed. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
// Takes effect before URL loading.
Button('setHostIP')
.onClick(() => {
try {
webview.WebviewController.setHostIP('www.example.com', '127.0.0.1', 30);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('clearHostIP')
.onClick(() => {
try {
webview.WebviewController.clearHostIP('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 })
}
}
} getSurfaceId(): string
Obtains the ID of the surface corresponding to ArkWeb. The ID can be used to capture a screenshot of the web page.
This API is valid only when the Web component rendering mode is ASYNC_RENDER. The value of getSurfaceId can be obtained only after the Web component is initialized.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| string | ID of the surface held by ArkWeb. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { image } from '@kit.ImageKit';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct Example{
controller: webview.WebviewController = new webview.WebviewController();
@State imagePixelMap: image.PixelMap | undefined = undefined;
build(){
Column(){
Button("Screenshot")
.onClick(()=>{
try {
let surfaceId = this.controller.getSurfaceId();
console.info("surfaceId: " + surfaceId);
if(surfaceId.length != 0) {
let region:image.Region = { x: 0, y: 0, size: { height: 800, width: 1000}}
this.imagePixelMap = image.createPixelMapFromSurfaceSync(surfaceId, region)
}
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Image(this.imagePixelMap)
.height(100)
Web({src: 'www.example.com', controller: this.controller})
}
}
} setUrlTrustList(urlTrustList: string): void
Sets a URL trustlist for the Web. Only URLs in the trustlist are allowed to be loaded or navigated to. Otherwise, they are intercepted and an alert page is displayed.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| urlTrustList | string | Yes | URL trustlist, configured in JSON format. The maximum size is 10 MB. The trustlist setting API uses an overwrite mode. When the API is called multiple times, the last setting takes effect. When this parameter is set to an empty string, the trustlist is canceled and access to all URLs is allowed. JSON format example: { "UrlPermissionList": [ { "scheme": "https", "host": "www.example1.com", "port": 443, "path": "pathA/pathB" }, { "scheme": "http", "host": "www.example2.com", "port": 80, "path": "test1/test2/test3" } ] } |
Parameters in JSON format:
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scheme | string | No | Optional parameter. The supported protocols are HTTP and HTTPS. |
| host | string | Yes | Mandatory parameter. Exact match: the request is allowed only when the host field of the URL exactly matches the rule field. Multiple rules can take effect simultaneously for the same host. |
| port | number | No | Optional parameter. |
| path | string | No | Optional parameter. This field uses prefix matching. For example, in pathA/pathB/pathC, pathA/pathB/ is specified, and all level-3 directories such as pathC can be accessed, which must be a complete directory name or file name. Partial matching is not allowed. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified.2. Parameter string is too long.3. Parameter verification failed. |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
urltrustList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"trust.example.com\", \"port\":80, \"path\":\"test\"}]}"
build() {
Column() {
Button('Setting the trustlist')
.onClick(() => {
try {
// Set a trustlist to allow access only to trust web pages.
this.controller.setUrlTrustList(this.urltrustList);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Cancel the trustlist.')
.onClick(() => {
try {
// Pass an empty string to the trustlist to disable the trustlist mechanism, allowing all URLs to be accessed.
this.controller.setUrlTrustList("");
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Access the trust web')
.onClick(() => {
try {
// The trustlist is enabled and trust web pages can be accessed.
this.controller.loadUrl('http://trust.example.com/test');
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Access the untrust web')
.onClick(() => {
try {
// The trustlist is enabled that untrust web pages cannot be accessed and an error page is displayed.
this.controller.loadUrl('http://untrust.example.com/test');
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'http://untrust.example.com/test', controller: this.controller }).onControllerAttached(() => {
try {
// Set the trustlist in the onControllerAttached callback to ensure it takes effect before the URL is loaded. In this case, untrust web pages cannot be accessed and an error page is displayed.
this.controller.setUrlTrustList(this.urltrustList);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}
}
} setPathAllowingUniversalAccess(pathList: Array<string>): void
Sets a path list. When the file protocol accesses resources in the path list, cross-origin access to local files and other online resources is allowed. In addition, when a path list is set, the file protocol only allows access to resources in the path list. Typical use case: used when the Web component needs to be allowed to access local resource files across origins while restricting the access scope to ensure security. (The behavior of fileAccess will be overridden by the behavior of this API.)
Using setPathAllowingUniversalAccess to relax cross-origin access restrictions on directories is a high-risk operation. Based on the principle of least privilege, the paths for el1 and el2 are fixed. The paths in the path list must conform to one of the following path formats:
/data/storage/el2/base/files/example
/data/storage/el2/base/haps/entry/files/example
/data/storage/el1/bundle/entry/resource/resfile
/data/storage/el1/bundle/entry/resource/resfile/example
/data/storage/el2/base/cache
/data/storage/el2/base/haps/entry/cache/example
The cache/web directory is not allowed. If it is included, an exception with the code 401 will be thrown. If the cache directory is set, cache/web cannot be accessed.
/data/storage/el2/base/temp
/data/storage/el2/base/haps/entry/temp/example
If a path in the list is not of the preceding paths, error code 401 is reported and the path list fails to be set. When the path list is set to empty, the accessible files for the file protocol are subject to the behavior of the fileAccess.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| pathList | Array<string> | Yes | The path list. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: WebviewController = new webview.WebviewController();
uiContext: UIContext = this.getUIContext();
build() {
Row() {
Web({ src: "", controller: this.controller })
.onControllerAttached(() => {
try {
// Set the list of paths that can be accessed across domains.
this.controller.setPathAllowingUniversalAccess([
this.uiContext.getHostContext()!.resourceDir,
this.uiContext.getHostContext()!.filesDir + "/example"
])
this.controller.loadUrl("file://" + this.getUIContext().getHostContext()!.resourceDir + "/index.html")
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
.javaScriptAccess(true)
.fileAccess(true)
.domStorageAccess(true)
}
}
} Load the HTML file, which is located in the application resource directory resource/resfile/index.html.
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no, viewport-fit=cover">
<script>
function getFile() {
var file = "file:///data/storage/el1/bundle/entry/resources/resfile/js/script.js";
var xmlHttpReq = new XMLHttpRequest();
xmlHttpReq.onreadystatechange = function(){
console.info("readyState:" + xmlHttpReq.readyState);
console.info("status:" + xmlHttpReq.status);
if(xmlHttpReq.readyState == 4){
if (xmlHttpReq.status == 200) {
// If the path list is set on the eTS, resources can be obtained.
const element = document.getElementById('text');
element.textContent = "load " + file + " success";
} else {
// If the path list is not set on the eTS, a CORS error is triggered.
const element = document.getElementById('text');
element.textContent = "load " + file + " failed";
}
}
}
xmlHttpReq.open("GET", file);
xmlHttpReq.send(null);
}
</script>
</head>
<body>
<div class="page">
<button id="example" onclick="getFile()">stealFile</button>
</div>
<div id="text"></div>
</body>
</html> In the HTML file, use the file protocol to access the local JS file through XMLHttpRequest. The JS file is stored in resource/resfile/js/script.js.
const body = document.body;
const element = document.createElement('div');
element.textContent = 'success';
body.appendChild(element); static enableBackForwardCache(features: BackForwardCacheSupportedFeatures): void
Enables the back-forward cache of a Web component. You can specify whether to add a specific page to the back-forward cache.
This API must be called before initializeWebEngine() initializes the kernel.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| features | BackForwardCacheSupportedFeatures | Yes | Features of the pages, which allow them to be added to the back-forward cache. |
Example
// EntryAbility.ets
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) {
let features = new webview.BackForwardCacheSupportedFeatures();
features.nativeEmbed = true;
features.mediaTakeOver = true;
// If a page uses the same-layer rendering and takes over media playback at the same time,
// you need to set the values of nativeEmbed and mediaTakeOver to true to add the page to the back-forward cache.
webview.WebviewController.enableBackForwardCache(features);
webview.WebviewController.initializeWebEngine();
AppStorage.setOrCreate("abilityWant", want);
}
} setBackForwardCacheOptions(options: BackForwardCacheOptions): void
Sets the back-forward cache options of the Web component.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| options | BackForwardCacheOptions | Yes | Options to control the back-forward cache of the Web component. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ts
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Row() {
Button("Add options").onClick((event: ClickEvent) => {
let options = new webview.BackForwardCacheOptions();
options.size = 3;
options.timeToLive = 10;
this.controller.setBackForwardCacheOptions(options);
})
Button("Backward").onClick((event: ClickEvent) => {
this.controller.backward();
})
Button("Forward").onClick((event: ClickEvent) => {
this.controller.forward();
})
}
Web({ src: "https://www.example.com", controller: this.controller })
}
.height('100%')
.width('100%')
}
} trimMemoryByPressureLevel(level: PressureLevel): void
Clears the cache occupied by Web component based on the specified memory pressure level.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| level | PressureLevel | Yes | Pressure level of the memory to be cleared. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified. 2. Parameter string is too long. 3.Parameter verification failed. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: WebviewController = new webview.WebviewController();
build() {
Column() {
Row() {
Button('trim_Memory')
.onClick(() => {
try {
// Set the current memory pressure level to moderate and release a small amount of memory.
webview.WebviewController.trimMemoryByPressureLevel(
webview.PressureLevel.MEMORY_PRESSURE_LEVEL_MODERATE);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}.height('10%')
Web({ src: 'www.example.com', controller: this.controller })
}
}
} createPdf(configuration: PdfConfiguration, callback: AsyncCallback<PdfData>): void
Obtains the data stream of a specified web page using an asynchronous callback.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| configuration | PdfConfiguration | Yes | Parameters required for creating a PDF file. |
| callback | AsyncCallback<PdfData> | Yes | Callback used to return the data stream of an online PDF file. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Invalid input parameter. |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
import { fileIo } from '@kit.CoreFileKit';
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
pdfConfig: webview.PdfConfiguration = {
width: 8.27,
height: 11.69,
marginTop: 0,
marginBottom: 0,
marginRight: 0,
marginLeft: 0,
shouldPrintBackground: true
}
build() {
Column() {
Button('SavePDF')
.onClick(() => {
this.controller.createPdf(
this.pdfConfig,
(error, result: webview.PdfData) => {
try {
// Obtain the component context.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
// Obtain the sandbox path and set the PDF file name.
let filePath = context.filesDir + "/test.pdf";
let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
if (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
return;
}
fileIo.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => {
console.info("createPDF write data to file succeeded and size is:" + writeLen);
}).catch((err: BusinessError) => {
console.error("createPDF write data to file failed with error message: " + err.message +
", error code: " + err.code);
}).finally(() => {
fileIo.closeSync(file);
});
} catch (resError) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
});
})
Web({ src: "www.example.com", controller: this.controller })
}
}
} createPdf(configuration: PdfConfiguration): Promise<PdfData>
Obtains the data stream of a specified web page using a promise.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| configuration | PdfConfiguration | Yes | Parameters required for creating a PDF file. |
Return value
| Type | Description |
|---|---|
| Promise<PdfData> | Promise used to return the result. It returns a web page PDF data stream (a PdfData object containing PDF binary data represented as an ArrayBuffer). |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Invalid input parameter. |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
import { fileIo } from '@kit.CoreFileKit';
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct Index {
controller: webview.WebviewController = new webview.WebviewController();
pdfConfig: webview.PdfConfiguration = {
width: 8.27,
height: 11.69,
marginTop: 0,
marginBottom: 0,
marginRight: 0,
marginLeft: 0,
shouldPrintBackground: true
}
build() {
Column() {
Button('SavePDF')
.onClick(() => {
this.controller.createPdf(this.pdfConfig)
.then((result: webview.PdfData) => {
try {
// Obtain the component context.
let context = this.getUIContext().getHostContext() as common.UIAbilityContext;
// Obtain the sandbox path and set the PDF file name.
let filePath = context.filesDir + "/test.pdf";
let file = fileIo.openSync(filePath, fileIo.OpenMode.READ_WRITE | fileIo.OpenMode.CREATE);
fileIo.write(file.fd, result.pdfArrayBuffer().buffer).then((writeLen: number) => {
console.info("createPDF write data to file succeeded and size is:" + writeLen);
}).catch((err: BusinessError) => {
console.error("createPDF write data to file failed with error message: " + err.message +
", error code: " + err.code);
}).finally(() => {
fileIo.closeSync(file);
});
} catch (resError) {
console.error(`ErrorCode: ${(resError as BusinessError).code}, Message: ${(resError as BusinessError).message}`);
}
})
})
Web({ src: "www.example.com", controller: this.controller })
}
}
} getScrollOffset(): ScrollOffset
Obtains the current scrolling offset (including the over-scrolling offset) of the web page.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| ScrollOffset | Current scroll offset of the web page (including the overscroll offset), containing x and y coordinates, in vp. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
@State testTitle: string = 'webScroll'
controller: webview.WebviewController = new webview.WebviewController();
@State controllerX: number =-100;
@State controllerY: number =-100;
@State mode: OverScrollMode = OverScrollMode.ALWAYS;
build() {
Column() {
Row() {
Text(this.testTitle)
.fontSize(30)
.fontWeight(FontWeight.Bold)
.margin(5)
}
Column() {
Text(`controllerX: ${this.controllerX}, controllerY: ${this.controllerY}`)
}
.margin({ top: 10, bottom: 10 })
Web({ src: $rawfile("index.html"), controller: this.controller })
.key("web_01")
.overScrollMode(this.mode)
.onTouch(() => {
this.controllerX = this.controller.getScrollOffset().x;
this.controllerY = this.controller.getScrollOffset().y;
let componentInfo = this.getUIContext().getComponentUtils().getRectangleById("web_01");
let webHeight = this.getUIContext().px2vp(componentInfo.size.height);
let pageHeight = this.controller.getPageHeight();
if (this.controllerY < 0) {
// Case 1: When a web page is scrolled down, use ScrollOffset.y directly.
console.info(`get downwards overscroll offsetY = ${this.controllerY}`);
} else if ((this.controllerY != 0) && (this.controllerY > (pageHeight - webHeight))) {
// Case 2: When a web page is scrolled up, calculate the offset between the lower boundary of the web page and that of the Web component.
console.info(`get upwards overscroll offsetY = ${this.controllerY - (pageHeight >= webHeight ? (pageHeight - webHeight) : 0)}`);
} else {
// Case 3: If the web page is not scrolled, use ScrollOffset.y directly.
console.info(`get scroll offsetY = ${this.controllerY}`);
}
})
.height(600)
}
.width('100%')
.height('100%')
}
} HTML file to be loaded:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" id="viewport" content="width=device-width,initial-scale=1.0">
<title>Demo</title>
<style>
body {
width:3000px;
height:6000px;
padding-right:170px;
padding-left:170px;
border:5px solid blueviolet;
}
</style>
</head>
<body>
Scroll Test
</body>
</html> getPageOffset(): ScrollOffset
Obtains the current scrolling offset of the web page (excluding the over-scrolling offset).
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| ScrollOffset | Current scroll offset of the web page (excluding over-scroll offset), which contains x and y coordinates, in vp. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. |
Example
// xxx.ets
import { BusinessError } from '@kit.BasicServicesKit';
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('index.html'), controller: this.controller })
.onScroll((event) => {
try {
console.info("getPageOffset x:" + this.controller.getPageOffset().x + ",y:" +
this.controller.getPageOffset().y);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}
}
} <!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" id="viewport" content="width=device-width, initial-scale=1.0">
<style>
.blue {
background-color: lightblue;
}
.green {
background-color: lightgreen;
}
.blue, .green {
font-size:16px;
height:200px;
text-align: center; /* Horizontally centered */
line-height: 200px; /* Vertically centered (the height matches the container height) */
}
</style>
</head>
<body>
<div class="blue" >webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
<div class="green">webArea</div>
<div class="blue">webArea</div>
</body>
</html> getLastHitTest(): HitTestValue
Obtains the element information of the area being clicked last time.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| HitTestValue | Element information of the area being clicked. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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('getLastHitTest')
.onClick(() => {
try {
let hitValue = this.controller.getLastHitTest();
console.info("hitType: " + hitValue.type);
console.info("extra: " + hitValue.extra);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} getAttachState(): ControllerAttachState
Checks whether the current WebViewController is bound to a Web component.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| ControllerAttachState | Attach status of WebViewController and the Web component. |
Example
Click the button to obtain the attach status of the current WebViewController and output logs.
// 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('getAttachState')
.onClick(() => {
try {
if (this.controller.getAttachState() == webview.ControllerAttachState.ATTACHED) {
console.info('Controller is attached.');
} else {
console.info('Controller is unattached.');
}
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} on(type: 'controllerAttachStateChange', callback: Callback<ControllerAttachState>): void
Registers the attach state event of WebViewController, which obtains the attach state change notification through a callback.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Attach state event of WebViewController, whose value is fixed to controllerAttachStateChange. |
| callback | Callback<ControllerAttachState> | Yes | Callback triggered when the attach state of WebViewController changes. |
Example
For details, see off.
off(type: 'controllerAttachStateChange', callback?: Callback<ControllerAttachState>): void
Deregisters the attach state event of WebViewController. After the deregistration, callback notifications will not be received.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| type | string | Yes | Attach state event of WebViewController, whose value is fixed to controllerAttachStateChange. |
| callback | Callback<ControllerAttachState> | No | Callback triggered when the attach state of WebViewController changes. By default, this parameter is left blank. If Callback is specified, only the specified callback is deregistered. Otherwise, all callbacks will be deregistered. If null or undefined is passed, error code 401 is thrown. |
Example
Use on to register multiple callbacks, which are triggered when the attach state changes. Use off to deregister a callback or all callbacks.
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
// Build a callback.
handleControllerAttachStateChange = (state: webview.ControllerAttachState) => {
if (state == webview.ControllerAttachState.UNATTACHED) {
console.info('handleControllerAttachStateChange: Controller is unattached.');
} else {
console.info('handleControllerAttachStateChange: Controller is attached.');
}
};
aboutToAppear() {
try {
this.controller.on('controllerAttachStateChange', this.handleControllerAttachStateChange);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
try {
// Register a callback to receive the notification of the controller attach state change.
this.controller.on('controllerAttachStateChange', (state: webview.ControllerAttachState) => {
if (state == webview.ControllerAttachState.UNATTACHED) {
console.info('Controller is unattached.');
} else {
console.info('Controller is attached.');
}
})
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
aboutToDisappear() {
// Cancel the specified registered callback.
// this.controller.off('controllerAttachStateChange', this.handleControllerAttachStateChange);
// Cancel all registered callbacks.
this.controller.off('controllerAttachStateChange');
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
} waitForAttached(timeout: number):Promise<ControllerAttachState>
Asynchronously waits for the WebViewController to be attached to the Web component. If the attachment is complete or times out, a callback is triggered to return the current ControllerAttachState through a promise.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| timeout | number | Yes | Asynchronous waiting duration. Value range: [0, 65535] Unit: ms. |
Return value
| Type | Description |
|---|---|
| Promise<ControllerAttachState> | Promise used to return the current ControllerAttachState. |
Example
In the initialization phase, set the WebViewController to wait for the attachment to complete. The timeout interval is 1000 ms. If the attachment is complete or times out, the callback is triggered.
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
async aboutToAppear() {
this.controller.waitForAttached(1000).then((state: webview.ControllerAttachState) => {
if (state == webview.ControllerAttachState.ATTACHED) {
// The callback is triggered when the attachment is complete or times out.
console.info('Controller is attached.');
}
})
try {
const state = await this.controller.waitForAttached(1000);
if (state == webview.ControllerAttachState.ATTACHED) {
console.info('Controller is attached.');
}
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
} static setWebDebuggingAccess(webDebuggingAccess: boolean, port: number): void
Sets whether to enable wireless web debugging. By default, wireless web debugging is disabled.
If no port is specified, this API is equivalent to the setWebDebuggingAccess API. In this case, ArkWeb starts a local domain socket listener.
When a port is specified, ArkWeb starts a TCP socket listener. In this case, you can debug the web page wirelessly. For details, see Wireless Debugging.
A port number smaller than 1024 is a well-known or system port and can be enabled only with privileges in the operating system. Therefore, the value of port must be greater than 1024. Otherwise, the API throws an exception.
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 feature in the officially released version of the application.
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 page debugging is enabled, and false indicates the opposite. |
| port | number | Yes | Specifies the TCP port number of the DevTools service. If no port is specified, this API is equivalent to the [setWebDebuggingAccess] (#setwebdebuggingaccess) API. Value range: (1024, 65535] If the value of port is within the range of [0, 1024], the BusinessError exception is thrown. The error code is 17100023. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100023 | The port number is not within the allowed range. |
Example
// 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, 8888);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
} getProgress(): number
Obtains the loading progress of the current web page.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| number | Loading progress of the current page. The value range is [0, 100]. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. |
Example
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 })
.onPageBegin(() => {
let curProgress = this.controller.getProgress();
console.info("current page loading progress is :" + curProgress);
})
}
}
} getHitTest(): WebHitTestType
Obtains the element type of the area being clicked.
This API is supported since API version 9 and deprecated since API version 18. You are advised to use getLastHitTest instead.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| WebHitTestType | Element type of the area being clicked. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Button('getHitTest')
.onClick(() => {
try {
let hitTestType = this.controller.getHitTest();
console.info("hitTestType: " + hitTestType);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} getHitTestValue(): HitTestValue
Obtains the element information of the area being clicked.
This API is supported since API version 9 and deprecated since API version 18. You are advised to use getLastHitTest instead.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| HitTestValue | Element information of the area being clicked. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Button('getHitTestValue')
.onClick(() => {
try {
let hitValue = this.controller.getHitTestValue();
console.info("hitType: " + hitValue.type);
console.info("extra: " + hitValue.extra);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} avoidVisibleViewportBottom(avoidHeight: number): void
Sets the bottom avoidance height of the visible viewport on the web page.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| avoidHeight | number | Yes | Bottom avoidance height of the visible viewport on the web page. Unit: vp. Value range: [0, height of the Web component] If the value is less than 0, the value 0 is used. If the value is greater than the height of the Web component, the height of the Web component is used. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 801 | Capability not supported. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
avoidHeight: number = 100;
build() {
Column() {
Button('avoid')
.onClick(() => {
try {
this.controller.avoidVisibleViewportBottom(this.avoidHeight);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('reset')
.onClick(() => {
try {
this.controller.avoidVisibleViewportBottom(0);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} setErrorPageEnabled(enable: boolean): void
Sets whether to enable the default error page.
When this API is set to true, if an error occurs during page loading, the onOverrideErrorPage callback is triggered. You can customize the error display page in the callback.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable the default error page. The value true means to enable the default error page, and false means the opposite. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
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 })
.onControllerAttached(() => {
this.controller.setErrorPageEnabled(true);
if (!this.controller.getErrorPageEnabled()) {
this.controller.setErrorPageEnabled(true);
}
})
}
}
} getErrorPageEnabled(): boolean
Queries whether the default error page is enabled.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether the default error page is enabled. The value true indicates that the default error page is enabled, and false indicates the opposite. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
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 })
.onControllerAttached(() => {
this.controller.setErrorPageEnabled(true);
if (!this.controller.getErrorPageEnabled()) {
this.controller.setErrorPageEnabled(true);
}
})
}
}
} static enablePrivateNetworkAccess(enable: boolean): void
Sets the private network access check feature.
After this feature is enabled, the Web component performs CORS preflight on private network requests (such as requests for accessing local servers or intranet resources). It sends an OPTIONS preflight request to obtain explicit authorization from the target server and then transmits the actual data. Disabling this feature will skip the security check.
The private network access check feature currently takes effect mainly for Web Worker scenarios.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable the private network access check feature. The value true means to enable the private network access check feature, and false means the opposite. |
Example
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 })
.onControllerAttached(() => {
// If the value is set to false, ArkWeb does not check whether the private network request is valid.
webview.WebviewController.enablePrivateNetworkAccess(false);
})
}
}
} static isPrivateNetworkAccessEnabled(): boolean
Obtains whether the private network access check feature is enabled for the Web component.
The private network access check feature currently takes effect mainly for Web Worker scenarios.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether the private network access check feature is enabled for the Web component. The value true indicates that the private network access check feature is enabled, and false indicates the opposite. |
Example
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Button('isPrivateNetworkAccessEnabled')
.onClick(() => {
try {
let isEnabled: boolean = webview.WebviewController.isPrivateNetworkAccessEnabled();
console.info("isPrivateNetworkAccessEnabled:", isEnabled);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.onControllerAttached(() => {
// If the value is set to false, ArkWeb does not check whether the private network request is valid.
webview.WebviewController.enablePrivateNetworkAccess(false);
})
}
}
} getBlanklessInfoWithKey(key: string): BlanklessInfo
Obtains the prediction information about blankless loading (for details, see BlanklessInfo) and starts to generate the loading transition frame. The application determines whether to enable blankless loading based on the information. This API must be used together with the setBlanklessLoadingWithKey API before the page loading API is triggered or in onLoadIntercept, and after the WebViewController is bound to the Web component.
System capability: SystemCapability.Web.Webview.Core
Device behavior differences: This API can be called on phones. For other device types, error code 801 is returned.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Key value that uniquely identifies the page. The value cannot be empty and can contain a maximum of 2048 characters. Invalid values do not take effect. |
Return value
| Type | Description |
|---|---|
| BlanklessInfo | Prediction information object for the first screen loading of a page. The app uses this information to decide whether to enable blankless loading frame insertion. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | This functionality is not supported. |
Example
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: 'https://www.example.com', controller: this.controller })
.javaScriptAccess(true)
.onLoadIntercept((event) => {
// Enable frame interpolation only when the similarity exceeds 50% and the loading duration is less than 1000 ms.
try {
let info = this.controller.getBlanklessInfoWithKey('https://www.example.com/page1');
if (info.errCode == webview.WebBlanklessErrorCode.SUCCESS) {
if (info.similarity >= 0.5 && info.loadingTime < 1000) {
this.controller.setBlanklessLoadingWithKey('http://www.example.com/page1', true);
} else {
this.controller.setBlanklessLoadingWithKey('http://www.example.com/page1', false);
}
} else {
console.info('getBlankless info err');
}
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
return false;
})
}
}
} setBlanklessLoadingWithKey(key: string, is_start: boolean): WebBlanklessErrorCode
Sets whether to enable blankless loading. This API must be used together with getBlanklessInfoWithKey.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Key value that uniquely identifies the page. This value must be the same as the key value of the getBlanklessInfoWithKey API. The value cannot be empty and can contain a maximum of 2048 characters. When an invalid value is set, the error code WebBlanklessErrorCode is returned, and the API does not take effect. |
| is_start | boolean | Yes | Whether to enable frame interpolation. The value true means to enable frame interpolation, and false means the opposite. If undefined or null is passed in, the value is false. |
Return value
| Type | Description |
|---|---|
| WebBlanklessErrorCode | Whether the API is successfully called. For details, see WebBlanklessErrorCode. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | This functionality is not supported. |
Example
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: 'https://www.example.com', controller: this.controller })
.javaScriptAccess(true)
.onLoadIntercept((event) => {
// Enable frame interpolation only when the similarity exceeds 50% and the loading duration is less than 1000 ms.
try {
let info = this.controller.getBlanklessInfoWithKey('https://www.example.com/page1');
if (info.errCode == webview.WebBlanklessErrorCode.SUCCESS) {
if (info.similarity >= 0.5 && info.loadingTime < 1000) {
this.controller.setBlanklessLoadingWithKey('http://www.example.com/page1', true);
} else {
this.controller.setBlanklessLoadingWithKey('http://www.example.com/page1', false);
}
} else {
console.info('getBlankless info err');
}
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
return false;
})
}
}
} setBlanklessLoadingWithParams(key: string, param: BlanklessLoadingParam): WebBlanklessErrorCode
Sets the configuration parameters for frame interpolation during blankless loading. This API must be used with getBlanklessInfoWithKey. Compared with setBlanklessLoadingWithKey, this API supports more parameter settings for frame interpolation during blankless loading, including the frame interpolation duration, cache data validity period, and custom callback after frame interpolation is complete.
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| key | string | Yes | Key value that uniquely identifies the page. This value must be the same as the key value of the getBlanklessInfoWithKey API. The value cannot be empty and can contain a maximum of 2048 characters. When an invalid value is set, the error code WebBlanklessErrorCode is returned, and the API does not take effect. |
| param | BlanklessLoadingParam | Yes | Parameters for frame interpolation of blankless loading. |
Return value
| Type | Description |
|---|---|
| WebBlanklessErrorCode | API calling result. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | Capability not supported. |
Example
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: 'https://www.example.com', controller: this.controller })
.javaScriptAccess(true)
.onLoadIntercept((event) => {
try {
let info = this.controller.getBlanklessInfoWithKey('https://www.example.com/page1');
if (info.errCode == webview.WebBlanklessErrorCode.SUCCESS) {
let data = new Date(2026, 5, 10, 0, 0, 0, 0);
let param: webview.BlanklessLoadingParam = {
enable: info.similarity > 0.4 && info.similarity < 2000,
duration: info.loadingTime,
expirationTime: data.getTime(),
callback: (info: webview.BlanklessFrameInterpolationInfo)=>{
// Data monitoring.
},
};
this.controller.setBlanklessLoadingWithParams('http://www.example.com/page1', param);
} else {
console.info('getBlankless info err');
}
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code},
Message: ${(error as BusinessError).message}`);
}
return false;
})
}
}
} static clearBlanklessLoadingCache(keys?: Array<string>): void
Clears the blankless loading cache of the page with a specified key value.
In an applet or web application, when the content changes significantly during page loading, an obvious scene change may occur. If you are concerned about this change, you can use this API to clear the page cache.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| keys | Array<string> | No | Key value list on the pages using the blankless optimization solution. The key value has been specified in getBlanklessInfoWithKey. Default value: key list of all pages cached by the blankless optimization solution. Valid value range: The key length cannot exceed 2048 characters, and the number of keys must be less than or equal to 100. The key value is the same as that input to the Web component during page loading. Invalid value setting behavior: If undefined or null is passed, error code 401 is thrown. If the key length exceeds 2048, the key does not take effect. If the key length exceeds 100, the first 100 values are used. If the key is empty, the default value is used. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | This functionality is not supported. |
Example
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.info("EntryAbility onCreate");
// If the web page of the application will be greatly changed on June 10, 2025, for example, during product promotion activities, you are advised to clear the frame interpolation to optimize the cache.
webview.WebviewController.initializeWebEngine();
let pageUpdateTime: number = Date.UTC(2025, 5, 10, 0, 0, 0, 0);
let pageUpdateTime1: number = Date.UTC(2025, 5, 11, 0, 0, 0, 0);
let pageUpdateTimeNow: number = Date.now();
if (pageUpdateTimeNow > pageUpdateTime && pageUpdateTime < pageUpdateTime1) {
// Clear the cache of the frame interpolation on the specified page.
try {
webview.WebviewController.clearBlanklessLoadingCache(["https://www.example.com", "https://www.example1.com"]);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
}
AppStorage.setOrCreate("abilityWant", want);
console.info("EntryAbility onCreate done");
}
} static setBlanklessLoadingCacheCapacity(capacity: number): number
Sets the persistent cache capacity of the blankless loading solution and returns the value that takes effect. If the API is not explicitly called, the default cache capacity is 30 MB. When this limit is exceeded, transition frames that are not frequently used are eliminated.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| capacity | number | Yes | Sets the persistent cache capacity, in MB. The maximum value cannot exceed 100 MB. Valid value range: [0, 100]. When set to 0, no cache space is available and the feature is globally disabled. Behavior for invalid values: if the value is less than 0, the effective value is 0; if the value is greater than 100, the effective value is 100. |
Return value
| Type | Description |
|---|---|
| number | Effective value that ranges from 0 MB to 100 MB. When a value less than 0 is set, the value 0 takes effect. When a value greater than 100 is set, the value 100 takes effect. |
Error codes
For details about the error codes, see Universal Error Codes.
| ID | Error Message |
|---|---|
| 801 | This functionality is not supported. |
Example
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.info("EntryAbility onCreate");
webview.WebviewController.initializeWebEngine();
// Set the cache capacity to 10 MB.
try {
webview.WebviewController.setBlanklessLoadingCacheCapacity(10);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
AppStorage.setOrCreate("abilityWant", want);
console.info("EntryAbility onCreate done");
}
} setWebDestroyMode(mode: WebDestroyMode): void
Sets the destroy mode of the Web component. The destroy mode of the Web component affects the time when web kernel resources, such as the JavaScript running context and rendering context, are released. The default value is WebDestroyMode.NORMAL_MODE (normal mode), indicating that the system determines the destroy time. You can set WebDestroyMode.FAST_MODE (fast mode) to destroy resources immediately, improving performance in specific scenarios.
WebDestroyMode.FAST_MODE changes the time when the Web component is destroyed. When it is used, pay attention to the incorrect implementation that depends on the destroy time of the Web component. For example, when a WebViewController is called in fast mode rather than using WebDestroyMode.NORMAL_MODE, the unbinding exception (17100001) is more likely to be triggered. In this case, the application needs to capture the exception, or use getAttachState to obtain the attach state to avoid stability problems.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | WebDestroyMode | Yes | Destroy mode of the Web component. Default value: WebDestroyMode.NORMAL_MODE |
Example
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.info("EntryAbility onCreate");
webview.WebviewController.initializeWebEngine();
// Set the fast destroy mode.
webview.WebviewController.setWebDestroyMode(webview.WebDestroyMode.FAST_MODE);
AppStorage.setOrCreate("abilityWant", want);
console.info("EntryAbility onCreate done");
}
} static setScrollbarMode(scrollbarMode: ScrollbarMode): void
Sets the global scrollbar mode in the web page. When this API is not explicitly called, ScrollbarMode.OVERLAY_LAYOUT_SCROLLBAR is used by default, indicating that the scroll bar is not always displayed.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scrollbarMode | ScrollbarMode | Yes | Scroll bar mode. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
aboutToAppear(): void {
webview.WebviewController.setScrollbarMode(webview.ScrollbarMode.FORCE_DISPLAY_SCROLLBAR);
}
build() {
Column() {
Web({ src: $rawfile('index.html'), controller: this.controller })
.height('90%')
}
}
} HTML file to be loaded:
<!--index.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Demo</title>
<style>
body {
width:2560px;
height:2560px;
padding-right:170px;
padding-left:170px;
border:5px solid blueviolet;
}
</style>
</head>
<body>
Scroll Test
</body>
</html> static setActiveWebEngineVersion(engineVersion: ArkWebEngineVersion): void
Sets the ArkWeb kernel version. If the system does not support the specified version, the setting does not take effect and the system default kernel is used (see Constraints). This API is a global static API and must be executed before initializeWebEngine is called. If any Web component has been loaded, the setting does not take effect. Typical use case: when features or compatibility requirements of a specific kernel version are needed, you can switch to the corresponding kernel version.
Legacy kernel adaptation
Since HarmonyOS 6.0, some ArkWeb APIs do not take effect when the legacy kernel (M114) is used. For details, see Adaptation Guide for the M114 Kernel on HarmonyOS 6.0.
Since HarmonyOS 7.0, some ArkWeb APIs do not take effect when the legacy kernel (M132) is used. For details, see Adaptation Guide for the M132 Kernel on HarmonyOS 7.0.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| engineVersion | ArkWebEngineVersion | Yes | ArkWeb kernel version. |
Example
This example shows how to set the ArkWeb kernel version in the EntryAbility creation phase.
// 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.info("EntryAbility onCreate")
webview.WebviewController.setActiveWebEngineVersion(webview.ArkWebEngineVersion.M132)
if (webview.WebviewController.getActiveWebEngineVersion() == webview.ArkWebEngineVersion.M132) {
console.info("Active Web Engine Version set to M132")
}
console.info("EntryAbility onCreate done")
}
} static getActiveWebEngineVersion(): ArkWebEngineVersion
Obtains the current ArkWeb kernel version.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| ArkWebEngineVersion | The ArkWeb kernel version defined by ArkWebEngineVersion. |
Example
For details, see setActiveWebEngineVersion.
static isActiveWebEngineEvergreen(): boolean
Checks whether the system is using the evergreen kernel, that is, the latest kernel.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether the system is using the evergreen kernel. If the system is using the evergreen kernel, true is returned. Otherwise, false is returned. |
Example
This example shows how to determine whether the evergreen kernel is used in the EntryAbility creation phase.
// 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.info("EntryAbility onCreate")
if (webview.WebviewController.isActiveWebEngineEvergreen()) {
console.info("Active Web Engine is Evergreen")
}
console.info("EntryAbility onCreate done")
}
} static setAutoPreconnect(enabled: boolean): void
Sets the automatic preconnection status of the Web kernel. If this API is not set, automatic preconnection is enabled by default.
This API must be called before initializeWebEngine() initializes the kernel or a Web component is created. If any Web component has been loaded, the setting does not take effect.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether to enable automatic preconnection of the Web kernel. The value true means to enable the private network access check feature, and false means the opposite. |
Example
// EntryAbility.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) {
webview.WebviewController.setAutoPreconnect(false);
webview.WebviewController.initializeWebEngine();
AppStorage.setOrCreate("abilityWant", want);
}
} static isAutoPreconnectEnabled(): boolean
Queries the automatic preconnection status of the Web kernel.
If the automatic preconnection status of the Web kernel is not set by using setAutoPreconnect, automatic preconnection is enabled by default, and true is returned.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether auto preconnection is enabled for the Web kernel. The value true indicates that the private network access check feature is enabled, and false indicates the opposite. |
Example
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
build() {
Column() {
Button('isAutoPreconnectEnabled')
.onClick(() => {
try {
let isEnabled: boolean = webview.WebviewController.isAutoPreconnectEnabled();
console.info("isAutoPreconnectEnabled:", isEnabled);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}
}
} static getSiteIsolationMode(): SiteIsolationMode
Queries the currently effective site isolation mode.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| SiteIsolationMode | Site isolation mode. getSiteIsolationMode() queries the currently effective site isolation mode. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Button('getSiteIsolationMode')
.onClick(() => {
let mode = webview.WebviewController.getSiteIsolationMode();
console.info("getSiteIsolationMode: " + mode);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} setSiteIsolationMode(mode: SiteIsolationMode): void
Sets the site isolation mode. The site isolation mechanism isolates websites from different origins in different rendering processes to reduce the cross-domain attack surface. For example, on devices such as PCs, when site isolation mode is not enabled, the original process model assigns one rendering process per tab. After site isolation is enabled, iframes from different origins within a tab can run in independent rendering processes.
For third-party applications that load only trusted web pages, you can disable this functionality to improve performance, reduce memory usage, and reduce interception of cross-domain access. The default value varies according to the device. SiteIsolationMode.STRICT is used for PCs and tablets, and SiteIsolationMode.PARTIAL is used for phones. In Secure Shield mode, strict site isolation is used.
Strict site isolation cannot be set in single-process mode.
This API can be called only once during initialization. The site isolation mode cannot be repeatedly changed.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | SiteIsolationMode | Yes | Site isolation mode. The default value depends on the device type and device mode. For PCs and tablets, strict site isolation is used by default. For phones, partial site isolation is used by default. In Secure Shield mode, strict site isolation is used by default. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. Possible causes: 1. Site Isolation mode is already set by the developer. 2. Site Isolation mode cannot be strict in single-render-process mode. 3. Site Isolation mode cannot be changed while Secure Shield mode is active. |
Example
// 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('setSiteIsolationMode')
.onClick(() => {
try {
webview.WebviewController.setSiteIsolationMode(webview.SiteIsolationMode.PARTIAL);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
} static setSocketIdleTimeout(timeout: number): void
Sets the timeout interval for used sockets to stay idle in the Web component. If the value is different from the timeout interval of existing idle sockets, the existing idle sockets are cleared according to the new value.
If this API is not used to set the timeout interval for idle sockets, the default value 300s is used for the Web component.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| timeout | number | Yes | Timeout interval for used sockets to stay idle in the Web component, in seconds. Value range: [30, 300]. If the value is less than 30, the value 30 takes effect. If the value is greater than 300, the value 300 takes effect. |
Example
// EntryAbility.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) {
webview.WebviewController.setSocketIdleTimeout(200);
AppStorage.setOrCreate("abilityWant", want);
}
} setSoftKeyboardBehaviorMode(mode: WebSoftKeyboardBehaviorMode): void
Sets the automatic control mode of the soft keyboard. When this API is not explicitly called, the system attempts to automatically hide or show the soft keyboard when the Web component loses or gains focus, or when its state switches to inactive or active. Typical use case: when you do not want the Web component to automatically hide or re-show the soft keyboard during inactive or active state switching, use DISABLE_AUTO_KEYBOARD_ON_ACTIVE; when you need to retain the default automatic management behavior, use DEFAULT.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| mode | WebSoftKeyboardBehaviorMode | Yes | Behavior mode of the web soft keyboard. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// index.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Button('Web InActive').onClick(() => {
this.controller.setSoftKeyboardBehaviorMode(webview.WebSoftKeyboardBehaviorMode.DISABLE_AUTO_KEYBOARD_ON_ACTIVE);
})
Web({ src: 'www.example.com', controller: this.controller })
.keyboardAvoidMode(WebKeyboardAvoidMode.RETURN_TO_UICONTEXT)
}
}
} resumeMicrophone(): void
Resumes microphone capture on the current web page. Before using the microphone , add the ohos.permission.MICROPHONE permission to module.json5. For details about how to add the permission, see Declaring Permissions in the Configuration File.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// 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.MICROPHONE'], (err: BusinessError, data: PermissionRequestResult) => {
if (err) {
console.error(`ErrorCode: ${err.code}, Message: ${err.message}`);
return;
}
console.info('data:' + JSON.stringify(data));
console.info('data permissions:' + data.permissions);
console.info('data authResults:' + data.authResults);
})
}
build() {
Column() {
Button("resumeMicrophone").onClick(() => {
try {
this.controller.resumeMicrophone();
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button("pauseMicrophone").onClick(() => {
try {
this.controller.pauseMicrophone();
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button("stopMicrophone").onClick(() => {
try {
this.controller.stopMicrophone();
} 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();
}
})
}
})
.onMicrophoneCaptureStateChange((event: MicrophoneCaptureStateChangeInfo) => {
console.info("MicrophoneCapture from ", event.originalState, " to ", event.newState);
})
}
}
} HTML file to be loaded:
<!-- index.html -->
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body>
<video id="video" width="400px" height="400px" autoplay="autoplay">
</video>
<input type="button" title="HTML5 Microphone" value="Enable Microphone" onclick="getMedia()" />
<script>
function getMedia() {
let constraints = {
video: {
width: 500,
height: 500
},
audio: true
}
let video = document.getElementById("video");
let promise = navigator.mediaDevices.getUserMedia(constraints);
promise.then(function(MediaStream) {
video.srcObject = MediaStream;
video.play();
})
}
</script>
</body>
</html> pauseMicrophone(): void
Pauses microphone capture on the current web page.
Differences from resumeMicrophone and stopMicrophone:
pauseMicrophone only pauses microphone capture and can be restored through resumeMicrophone; stopMicrophone stops capture and releases resources.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
For the complete sample code, see resumeMicrophone.
stopMicrophone(): void
Stops microphone capture on the current web page.
System capability: SystemCapability.Web.Webview.Core
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
For the complete sample code, see resumeMicrophone.
static setUserAgentClientHintsEnabled(enabled: boolean): void
Sets whether to enable the User-Agent Client Hints feature.
User-Agent Client Hints (UA-CH) is a privacy protection mechanism that replaces the traditional User-Agent string. It transfers client information through on-demand requests and structured data, reducing the risk of excessive tracking.
If this method is not used, the User-Agent Client Hints feature is disabled by default.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enabled | boolean | Yes | Whether to enable the User-Agent Client Hints feature. The value true means enabled, and false means disabled. |
Example
// 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('setUserAgentMetadata').fontSize(20)
.onClick((e: ClickEvent) => {
try {
let arrayVersions: Array<webview.UserAgentBrandVersion> = new Array<webview.UserAgentBrandVersion>;
let brandVersion:webview.UserAgentBrandVersion = new webview.UserAgentBrandVersion();
brandVersion.setBrand("brand HarmonyOS");
brandVersion.setMajorVersion("major version 1.0");
brandVersion.setFullVersion("blank full version 1.0");
arrayVersions.push(brandVersion);
let metadata:webview.UserAgentMetadata = new webview.UserAgentMetadata();
metadata.setBrandVersionList(arrayVersions);
metadata.setFormFactors([webview.UserAgentFormFactor.AUTOMOTIVE]);
metadata.setArchitecture("arch HarmonyOS");
metadata.setBitness("bitness 64");
metadata.setFullVersion("full version HarmonyOS");
metadata.setMobile(true);
metadata.setModel("model HarmonyOS");
metadata.setPlatform("platform HarmonyOS");
metadata.setPlatformVersion("platform version HarmonyOS");
metadata.setWow64(false);
this.controller.setUserAgentMetadata(this.userAgent, metadata);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('getUserAgentMetadata').fontSize(20)
.onClick((e: ClickEvent) => {
try {
this.userAgent = this.controller.getUserAgent();
let metadata = this.controller.getUserAgentMetadata(this.userAgent);
let versionList = metadata.getBrandVersionList();
for(let i = 0; i < versionList.length; i++) {
console.info("Brand:" + versionList[i].getBrand());
console.info("MajorVersion " + versionList[i].getMajorVersion());
console.info("FullVersion " + versionList[i].getFullVersion());
}
let FormFactors = metadata.getFormFactors();
for(let j = 0; j < FormFactors.length; j++) {
console.info("FormFactor:" + FormFactors[j]);
}
console.info("Bitness:" + metadata.getBitness());
console.info("FullVersion:" + metadata.getFullVersion());
console.info("Mobile:" + metadata.getMobile());
console.info("Model:" + metadata.getModel());
console.info("Platform:" + metadata.getPlatform());
console.info("PlatformVersion:" + metadata.getPlatformVersion());
console.info("Wow64:" + metadata.getWow64());
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'https://www.example.com', controller: this.controller })
.onControllerAttached(() => {
try {
this.userAgent = this.controller.getUserAgent();
let metaData: webview.UserAgentMetadata = new webview.UserAgentMetadata();
metaData.setPlatform("HarmonyOS");
this.controller.setCustomUserAgent(this.userAgent);
let enabled: boolean = webview.WebviewController.getUserAgentClientHintsEnabled();
console.info("isUserAgentClientHintsEnabled:", enabled);
webview.WebviewController.setUserAgentClientHintsEnabled(true);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}
}
} static getUserAgentClientHintsEnabled(): boolean
Queries whether the User-Agent Client Hints feature is currently enabled.
System capability: SystemCapability.Web.Webview.Core
Return value
| Type | Description |
|---|---|
| boolean | Whether the User-Agent Client Hints feature is enabled. The value true indicates enabled, and false indicates disabled. |
Example
For details about the sample code, see setUserAgentClientHintsEnabled.
setUserAgentMetadata(userAgent: string, metaData: UserAgentMetadata): void
Sets the UserAgentMetadata corresponding to the User-Agent.
User-Agent Metadata is used to populate user agent client hints. It can provide the brand and version information of the client, the brand and major version of the underlying operating system, and detailed information about the underlying device.
The user agent can be set through setCustomUserAgent, setAppCustomUserAgent, or setUserAgentForHosts.
If no UserAgentMetadata is found based on the overridden User-Agent, and the overridden User-Agent contains the system default User-Agent, the system default value is used.
If no UserAgentMetadata is found based on the overridden User-Agent, but the overridden User-Agent does not contain the system default user agent, only low-level user agent client hints are generated.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| userAgent | string | Yes | Information about the custom user agent. You can use getUserAgent to obtain the current default user agent. |
| metaData | UserAgentMetadata | Yes | UserAgentMetadata corresponding to the user agent. You can use getUserAgentMetadata to obtain the current default value and then modify it using the corresponding method. |
Example
For details about the sample code, see setUserAgentClientHintsEnabled.
getUserAgentMetadata(userAgent: string): UserAgentMetadata
Obtains the UserAgentMetadata information of a user agent.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| userAgent | string | Yes | Information about the custom user agent. You can use getUserAgent to obtain the current default user agent. |
Return value
| Type | Description |
|---|---|
| UserAgentMetadata | UserAgentMetadata corresponding to userAgent. |
Example
For details about the sample code, see setUserAgentClientHintsEnabled.
setUrlTrustList(urlTrustList: string, allowOpaqueOrigin: boolean, supportWildcard: boolean): void
Sets a URL trustlist for the Web. Only URLs in the trustlist are allowed to be loaded or navigated to. Otherwise, they are intercepted and an alert page is displayed. This API extends the control over opaque origin URLs and wildcard rules.
System capability: SystemCapability.Web.Webview.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| urlTrustList | string | Yes | URL trustlist, configured in JSON format. The maximum size is 10 MB. The trustlist setting API uses an overwrite mode. When the API is called multiple times, the last setting takes effect. When this parameter is set to an empty string, the trustlist is canceled and access to all URLs is allowed. JSON format example: { "UrlPermissionList": [ { "scheme": "https", "host": "www.example1.com", "port": 443, "path": "pathA/pathB" }, { "scheme": "http", "host": "www.example2.com", "port": 80, "path": "test1/test2/test3" } ] } |
| allowOpaqueOrigin | boolean | Yes | Whether to allow loadUrl to directly load opaque origin URLs such as javascript/data. The value true means allowed, and false means not allowed. |
| supportWildcard | boolean | Yes | Whether to support wildcard matching for host and path. For example, to allow access to a.example.com and b.example.com when ***.example.com** is configured in the trustlist. true to support, and false otherwise. |
Parameters in JSON format:
| Name | Type | Mandatory | Description |
|---|---|---|---|
| scheme | string | No | Optional parameter. The supported protocols are HTTP and HTTPS. |
| host | string | Yes | Mandatory parameter. When supportWildcard is false, exact match is used, meaning the URL host field must exactly match the rule field for the request to be allowed. Multiple rules can take effect simultaneously for the same host. When supportWildcard is true, the wildcard * can be used for arbitrary string matching. The matching rules are as follows: 1. The host is segmented by ".". 2. A single wildcard * matches only one segment. For example, www.*.com matches www.example.com but not www.example1.example2.com. 3. Multiple wildcards can be used to match multiple segments. For example, www.*.* matches www.example.com but not www.example1.example2.com. 4. Wildcards can only be used alone. Consecutive * characters or combining * with other strings is not supported, for example, **.example.com or *ww.example.com. 5. Wildcards cannot be used for IP address matching. For example, 127.0.0.* cannot match 127.0.0.1. 6. For non-ASCII hosts (such as Chinese domain names), IDN conversion must be performed in advance. |
| port | number | No | Optional parameter. |
| path | string | No | Optional field. If not set, this item is not matched. When supportWildcard is false, prefix matching is used. Taking pathA/pathB/pathC as an example: all content under the three-level directory pathA/pathB/pathC is allowed, where pathC must be a complete directory name or file name. Partial matching is not supported. When supportWildcard is true, the wildcard * can be used for arbitrary string matching. The matching rules are as follows: 1. The path is segmented by "/". 2. If the wildcard * is not the last segment, it matches only one segment. For example, pathA/*/pathD matches pathA/pathB/pathD but not pathA/pathB/pathC/pathD. 3. If the wildcard * is the last segment, it can match multiple subsequent segments. For example, pathA/* matches pathA/pathB and also pathA/pathB/pathC; it can also match files such as pathA/xxx.txt. 4. Wildcards can only be used alone. Multiple * characters or combining * with other strings is not supported, for example, **/pathA/pathB or path*/pathB/pathC. 5. The URL part in the rule must be URL-encoded. |
Error codes
For details about the error codes, see Webview Error Codes and Universal Error Codes.
| ID | Error Message |
|---|---|
| 401 | Parameter error, possible causes: 1. Mandatory parameters are left unspecified 2. JSON string exceeds 10MB limit 3. JSON parsing failed (syntax errors, etc.) 4. UrlPermissionList field is missing 5. URL rule validation failed: - scheme must be http or https - host cannot be empty - port must be between 0-65535 - path length cannot exceed 65536 characters |
| 17100001 | Initialization error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
urltrustList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"trust.example.com\", \"path\":\"test\"}]}"
urlWildcardList: string = "{\"UrlPermissionList\":[{\"scheme\":\"http\", \"host\":\"*.example.com\", \"path\":\"*\"}]}"
build() {
Column() {
Button('Setting the trustlist')
.onClick(() => {
try {
// Set a trustlist to allow access only to trust web pages.
this.controller.setUrlTrustList(this.urltrustList);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Setting the wildcardlist')
.onClick(() => {
try {
// Set a wildcard trustlist to allow access to all URLs.
this.controller.setUrlTrustList(this.urlWildcardList, true, true);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Cancel the trustlist.')
.onClick(() => {
try {
// Pass an empty string to the trustlist to disable the trustlist mechanism, allowing access to all URLs.
this.controller.setUrlTrustList("");
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Access the trust web')
.onClick(() => {
try {
// The trustlist is enabled and trust web pages can be accessed.
this.controller.loadUrl('http://trust.example.com/test');
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Button('Access the untrust web')
.onClick(() => {
try {
// The trustlist is enabled that untrust web pages cannot be accessed and an error page is displayed.
this.controller.loadUrl('http://untrust.example.com/test');
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'http://untrust.example.com/test', controller: this.controller }).onControllerAttached(() => {
try {
// Set the trustlist in the onControllerAttached callback to ensure it takes effect before the URL is loaded. In this case, untrusted web pages cannot be accessed and an error page is displayed.
this.controller.setUrlTrustList(this.urltrustList);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
}
}
} static enableAdvancedSecurityMode(securityParams: SecurityParams): void
Disables specific web engine capabilities by configuring security feature options to reduce the attack surface. Typical use cases include: apps with high security requirements (such as financial and government apps) should enable advanced security mode to disable unnecessary web engine capabilities.
Since: 26.0.0
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| securityParams | SecurityParams | Yes | Security feature option configuration. |
Example
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
aboutToAppear() {
webview.WebviewController.enableAdvancedSecurityMode({
disableJITCompilation: true,
disableWebAssembly: true,
disableWebGL: true,
disablePDFViewer: true,
disableMathML: true,
disableServiceWorker: true,
disableNonProxyUDP: true
});
webview.WebviewController.initializeWebEngine();
}
build() {
Column() {
Web({ src: 'https://www.example.com', controller: this.controller })
}
}
} executeAIPageCommand(command: string): Promise<string>
Executes AIPageCommand asynchronously. This API uses a promise to return the result. The command type and command parameters are specified through the command parameter in JSON string format.
Since: 26.0.0
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| command | string | Yes | Command parameters in JSON format. Different commands have different parameter formats. For query commands, see AIPageCommand. For interaction commands, see AIPageInteraction. |
Return value
| Type | Description |
|---|---|
| Promise<string> | Promise object. When the command is executed successfully, it returns the command execution result in JSON format. When the execution fails or no value is returned, it returns an empty string. |
Error codes
For details about the error codes, see Webview Error Codes.
| Error Code ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100024 | Command format error. The command parameter does not conform to the JSON format requirements. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';
interface AIPageCommand {
method: string;
}
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Button('executeAIPageCommand')
.onClick(async () => {
try {
let commandObj: AIPageCommand = { method: 'getFullDom' };
let command: string = JSON.stringify(commandObj);
let result: string = await this.controller.executeAIPageCommand(command);
console.info(`executeAIPageCommand result: ${result}`);
} catch (error) {
console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
}
})
Web({ src: 'https://www.example.com', controller: this.controller })
}
}
} setErrorPageEnabled(enable: boolean, includeSubframe: boolean): void
Sets whether to enable the mainframe error page feature, and controls whether to also enable the subframe error page feature.
When enable is set to true, an error page is displayed when a mainframe loading error occurs: if the onOverrideErrorPage callback is set, the user-defined error page is displayed; if not, the default error page provided by ArkWeb is displayed. When both enable and includeSubframe are set to true, an error page is also displayed when a subframe loading error occurs, and the onOverrideErrorPage callback also takes effect for subframes.
Since: 26.0.0
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| enable | boolean | Yes | Whether to enable the mainframe error page feature. The value true means to enable it, and false means to disable it. After it is enabled, an error page is displayed when the mainframe fails to load. |
| includeSubframe | boolean | Yes | Whether to enable the subframe error page feature at the same time. The value true means to enable it, and false means to disable it. After it is enabled, an error page is also displayed when the subframe fails to load. This parameter takes effect only when enable is true. |
Error codes
For details about the error codes, see Webview Error Codes.
| ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
// xxx.ets
import { webview } from '@kit.ArkWeb';
@Entry
@Component
struct WebComponent {
controller: webview.WebviewController = new webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile("iframe_error.html"), controller: this.controller })
.onControllerAttached(() => {
// Enable the error page function for mainframe and subframe.
this.controller.setErrorPageEnabled(true, true);
// Query whether the subframe error page function is enabled.
let isSubframeEnabled: boolean = this.controller.getSubframeErrorPageEnabled();
console.info("Subframe error page enabled: " + isSubframeEnabled);
})
.onOverrideErrorPage((event) => {
if (event.request.isMainFrame()) {
return "<html><body><h1>Main page failed to load</h1><p>Error code: " + event.error.getErrorCode() + "</p></body></html>";
}
return "<html><body><h1>Subpage failed to load</h1><p>Error code: " + event.error.getErrorCode() + "</p></body></html>";
})
}
}
} <!-- resources/rawfile/iframe_error.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>iframe</title>
</head>
<body>
<iframe src="https://error-test.com/" title="iframe_error.html" loading="lazy" referrerpolicy="no-referrer" allow="accelerometer; clipboard-write; encrypted-media; gyroscope; picture-in-picture"></iframe>
</body>
</html> Example description: The iframe_error.html file used in the example must be placed in the resources/rawfile/ directory of the app resources. This HTML file contains an iframe that loads a failed URL, used to trigger the subframe error page.
getSubframeErrorPageEnabled(): boolean
Queries whether the subframe error page feature is enabled.
Since: 26.0.0
System capability: SystemCapability.Web.Webview.Core
Model restriction: This API can be used only in the stage model.
Return value
| Type | Description |
|---|---|
| boolean | Returns whether the subframe error page function is enabled. - true: The subframe error page function is enabled (that is, both enable and includeSubframe are true); - false: The subframe error page function is not enabled (including two cases: the error page function is not enabled, or the error page function is enabled but the subframe error page function is not enabled). |
Error codes
For details about the error codes, see Webview Error Codes.
| Error Code ID | Error Message |
|---|---|
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
Example
For the complete sample code, see setErrorPageEnabled.