未验证 提交 ec1c9ea2 编写于 作者: O openharmony_ci 提交者: Gitee

!12344 翻译完成 11899/12135/11644/11473/11373/11273/11205/11102/11423

Merge pull request !12344 from ester.zhou/TR-11899
# Webview
The **Webview** module provides APIs for web control.
> **NOTE**
>
> - The initial APIs of this module are supported since API version 9. Updates will be marked with a superscript to indicate their earliest API version.
>
> - You can preview how the APIs of this module work on a real device. The preview is not yet available in the DevEco Studio Previewer.
## Required Permissions
**ohos.permission.INTERNET**, required for accessing online web pages. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
## Modules to Import
```ts
import web_webview from '@ohos.web.webview';
```
## WebMessagePort
Implements a **WebMessagePort** object to send and receive messages.
### close
close(): void
Closes this message port.
**System capability**: SystemCapability.Web.Webview.Core
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
msgPort: WebMessagePort[] = null;
build() {
Column() {
Button('close')
.onClick(() => {
if (this.msgPort && this.msgPort[1]) {
this.msgPort[1].close();
} else {
console.error("msgPort is null, Please initialize first");
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### postMessageEvent
postMessageEvent(message: string): void
Sends a message. For the complete sample code, see [postMessage](#postmessage).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | :------------- |
| message | string | Yes | Message to send.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------- |
| 17100010 | Can not post message using this port. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_webview.WebMessagePort[];
build() {
Column() {
Button('postMessageEvent')
.onClick(() => {
try {
this.ports = this.controller.createWebMessagePorts();
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
this.ports[1].postMessageEvent("post message from ets to html5");
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onMessageEvent
onMessageEvent(callback: (result: string) => void): void
Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | :------------------- |
| result | string | Yes | Message received.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ----------------------------------------------- |
| 17100006 | Can not register message event using this port. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_webview.WebMessagePort[];
build() {
Column() {
Button('onMessageEvent')
.onClick(() => {
try {
this.ports = this.controller.createWebMessagePorts();
this.ports[1].onMessageEvent((msg) => {
console.log("received message from html5, on message:" + msg);
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebviewController
Implements a **WebviewController** to control the behavior of the **\<Web>** component. A **WebviewController** can control only one **\<Web>** component, and the APIs in the **WebviewController** can be invoked only after it has been bound to the target **\<Web>** component.
### Creating an Object
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### loadUrl
loadUrl(url: string | Resource, headers?: Array\<HeaderV9>): 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\<[HeaderV9](#headerv9)> | No | Additional HTTP request header of the URL.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100002 | Invalid url. |
| 17100003 | Invalid resource path or file type. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
this.controller.loadUrl('www.example.com');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### loadData
loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void
Loads specified data.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | ------ | ---- | ------------------------------------------------------------ |
| data | string | Yes | Character 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**.|
| historyUrl | string | No | URL used for historical records. If this parameter is not empty, historical records are managed based on this URL. This parameter is invalid when **baseUrl** is left empty.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100002 | Invalid url. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_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"
);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### accessforward
accessForward(): boolean
Checks whether moving to the next page can be performed on the current page.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | --------------------------------- |
| boolean | Returns **true** if moving to the next page can be performed on the current page; returns **false** otherwise.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('accessForward')
.onClick(() => {
try {
let result = this.controller.accessForward();
console.log('result:' + result);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### forward
forward(): void
Moves to the next page based on the history stack. This API is generally used together with **accessForward**.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('forward')
.onClick(() => {
try {
this.controller.forward();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### accessBackward
accessBackward(): boolean
Checks whether moving to the previous page can be performed on the current page.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | Returns **true** if moving to the previous page can be performed on the current page; returns **false** otherwise.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('accessBackward')
.onClick(() => {
try {
let result = this.controller.accessBackward();
console.log('result:' + result);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### backward
backward(): void
Moves to the previous page based on the history stack. This API is generally used together with **accessBackward**.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('backward')
.onClick(() => {
try {
this.controller.backward();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onActive
onActive(): void
Invoked to instruct the **\<Web>** component to enter the foreground, active state.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('onActive')
.onClick(() => {
try {
this.controller.onActive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onInactive
onInactive(): void
Invoked to instruct the **\<Web>** component to enter the inactive state.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('onInactive')
.onClick(() => {
try {
this.controller.onInactive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### refresh
refresh(): void
Invoked to instruct the **\<Web>** component to refresh the web page.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('refresh')
.onClick(() => {
try {
this.controller.refresh();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### accessStep
accessStep(step: number): boolean
Checks whether a specific number of steps forward or backward can be performed on the current page.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ------------------------------------------ |
| step | number | Yes | Number of the steps to take. A positive number means to move forward, and a negative number means to move backward.|
**Return value**
| Type | Description |
| ------- | ------------------ |
| boolean | Whether moving forward or backward is performed on the current page.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State steps: number = 2;
build() {
Column() {
Button('accessStep')
.onClick(() => {
try {
let result = this.controller.accessStep(this.steps);
console.log('result:' + result);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### clearHistory
clearHistory(): void
Clears the browsing history.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('clearHistory')
.onClick(() => {
try {
this.controller.clearHistory();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getHitTest
getHitTest(): HitTestTypeV9
Obtains the element type of the area being clicked.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------------------------------------------------------------ | ---------------------- |
| [HitTestTypeV9](#hittesttypev9)| Element type of the area being clicked.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getHitTest')
.onClick(() => {
try {
let hitTestType = this.controller.getHitTest();
console.log("hitTestType: " + hitTestType);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### registerJavaScriptProxy
registerJavaScriptProxy(object: object, name: string, methodList: Array\<string>): void
Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. After this API is called, call [refresh](#refresh) for the registration to take effect.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| ---------- | -------------- | ---- | ------------------------------------------------------------ |
| object | object | Yes | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return values of the methods can only be of the string, number, or Boolean type.|
| 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 | Methods of the JavaScript object to be registered at the application side. |
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct Index {
controller: web_webview.WebviewController = new web_webview.WebviewController();
testObj = {
test: (data) => {
return "ArkUI Web Component";
},
toString: () => {
console.log('Web Component toString');
}
}
build() {
Column() {
Button('refresh')
.onClick(() => {
try {
this.controller.refresh();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Button('Register JavaScript To Window')
.onClick(() => {
try {
this.controller.registerJavaScriptProxy(this.testObj, "objName", ["test", "toString"]);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
}
}
}
```
### runJavaScript
runJavaScript(script: string, callback : AsyncCallback\<string>): void
Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**.
**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. Returns **null** if the JavaScript script fails to be executed or no value is returned.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_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.info(`run JavaScript error: ` + JSON.stringify(error))
return;
}
if (result) {
this.webResult = result
console.info(`The test() return value is: ${result}`)
}
});
console.info('url: ', e.url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
}
}
}
```
### runJavaScript
runJavaScript(script: string): Promise\<string>
Executes a JavaScript script. This API uses a promise to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | ---------------- |
| script | string | Yes | JavaScript script.|
**Return value**
| Type | Description |
| --------------- | --------------------------------------------------- |
| Promise\<string> | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_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()')
.then(function (result) {
console.log('result: ' + result);
})
.catch(function (error) {
console.error("error: " + error);
})
console.info('url: ', e.url);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
}
}
}
```
### deleteJavaScriptRegister
deleteJavaScriptRegister(name: string): void
Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately without invoking the [refresh](#refresh) API.
**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](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
| 17100008 | Cannot delete JavaScriptProxy. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State name: string = 'Object';
build() {
Column() {
Button('deleteJavaScriptRegister')
.onClick(() => {
try {
this.controller.deleteJavaScriptRegister(this.name);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### zoom
zoom(factor: number): void
Zooms in or out of this web page.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description|
| ------ | -------- | ---- | ------------------------------------------------------------ |
| factor | number | Yes | Relative zoom ratio. A positive value indicates zoom-in, and a negative value indicates zoom-out.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
| 17100004 | Function not enable. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State factor: number = 1;
build() {
Column() {
Button('zoom')
.onClick(() => {
try {
this.controller.zoom(this.factor);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### searchAllAsync
searchAllAsync(searchString: string): void
Searches the web page for content that matches the keyword specified by **'searchString'** and highlights the matches on the page. This API returns the result asynchronously through [onSearchResultReceive](../arkui-ts/ts-basic-components-web.md#onsearchresultreceive9).
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type| Mandatory| Description |
| ------------ | -------- | ---- | -------------- |
| searchString | string | Yes | Search keyword.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State searchString: string = "xxx";
build() {
Column() {
Button('searchString')
.onClick(() => {
try {
this.controller.searchAllAsync(this.searchString);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]" + ret.isDoneCounting);
})
}
}
}
```
### clearMatches
clearMatches(): void
Clears the matches found through [searchAllAsync](#searchallasync).
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('clearMatches')
.onClick(() => {
try {
this.controller.clearMatches();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### searchNext
searchNext(forward: boolean): void
Searches for and highlights the next match.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type| Mandatory| Description |
| ------- | -------- | ---- | ---------------------- |
| forward | boolean | Yes | Whether to search forward.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('searchNext')
.onClick(() => {
try {
this.controller.searchNext(true);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### clearSslCache
clearSslCache(): void
Clears the user operation corresponding to the SSL certificate error event recorded by the **\<Web>** component.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('clearSslCache')
.onClick(() => {
try {
this.controller.clearSslCache();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### clearClientAuthenticationCache
clearClientAuthenticationCache(): void
Clears the user operation corresponding to the client certificate request event recorded by the **\<Web>** component.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('clearClientAuthenticationCache')
.onClick(() => {
try {
this.controller.clearClientAuthenticationCache();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### createWebMessagePorts
createWebMessagePorts(): Array\<WebMessagePort>
Creates web message ports.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ---------------------- | ----------------- |
| Array\<WebMessagePort> | List of web message ports.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_webview.WebMessagePort[];
build() {
Column() {
Button('createWebMessagePorts')
.onClick(() => {
try {
this.ports = this.controller.createWebMessagePorts();
console.log("createWebMessagePorts size:" + this.ports.length)
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### postMessage
postMessage(name: string, ports: Array\<WebMessagePort>, uri: string): void
Sends a web message to an HTML5 window.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ---------------------- | ---- | :------------------------------- |
| name | string | Yes | Message to send, including the data and message port.|
| ports | Array\<WebMessagePort> | Yes | Ports for receiving the message. |
| uri | string | Yes | URI for receiving the message. |
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_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. Send one of the message ports to the HTML side, which can then save and use the port.
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
// 3. Register a callback for the other message port on the application side.
this.ports[1].onMessageEvent((result: string) => {
var msg = 'Got msg from HTML: ' + result;
this.receivedFromHtml = msg;
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// 4. Use the port on the application side to send messages to the message port that has been sent to the HTML.
Button('SendDataToHTML')
.onClick(() => {
try {
if (this.ports && this.ports[1]) {
this.ports[1].postMessageEvent("post message from ets to HTML");
} else {
console.error(`ports is null, Please initialize first`);
}
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: $rawfile('xxx.html'), controller: this.controller })
}
}
}
```
```html
<!--xxx.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>
```
```js
//xxx.js
var h5Port;
var output = document.querySelector('.output');
window.addEventListener('message', function (event) {
if (event.data == '__init_port__') {
if (event.ports[0] != null) {
The 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:' + event.data;
output.innerHTML = msg;
}
}
}
})
// 3. Use h5Port to send messages to the eTS side.
function PostMsgToEts(data) {
if (h5Port) {
h5Port.postMessage(data);
} else {
console.error("h5Port is null, Please initialize first");
}
}
```
### requestFocus
requestFocus(): void
Requests focus for this web page.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('requestFocus')
.onClick(() => {
try {
this.controller.requestFocus();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
});
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### zoomIn
zoomIn(): void
Zooms in on this web page by 20%.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100004 | Function not enable. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('zoomIn')
.onClick(() => {
try {
this.controller.zoomIn();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### zoomOut
zoomOut(): void
Zooms out of this web page by 20%.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100004 | Function not enable. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('zoomOut')
.onClick(() => {
try {
this.controller.zoomOut();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getHitTestValue
getHitTestValue(): HitTestValue
Obtains the element information of the area being clicked.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------------ | -------------------- |
| [HitTestValue](#hittestvalue) | Element information of the area being clicked.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getHitTestValue')
.onClick(() => {
try {
let hitValue = this.controller.getHitTestValue();
console.log("hitType: " + hitValue.type);
console.log("extra: " + hitValue.extra);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getWebId
getWebId(): number
Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------ | --------------------- |
| number | Index value of the current **\<Web>** component.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getWebId')
.onClick(() => {
try {
let id = this.controller.getWebId();
console.log("id: " + id);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getUserAgent
getUserAgent(): string
Obtains the default user agent of this web page.
**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](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getUserAgent')
.onClick(() => {
try {
let userAgent = this.controller.getUserAgent();
console.log("userAgent: " + userAgent);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getTitle
getTitle(): string
Obtains the title of the file selector.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------ | -------------------- |
| string | Title of the file selector.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getTitle')
.onClick(() => {
try {
let title = this.controller.getTitle();
console.log("title: " + title);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getPageHeight
getPageHeight(): number
Obtains the height of this web page.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | Height of the current web page.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getPageHeight')
.onClick(() => {
try {
let pageHeight = this.controller.getPageHeight();
console.log("pageHeight : " + pageHeight);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### storeWebArchive
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. The value cannot be null. |
| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
| 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](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100003 | Invalid resource path or file type. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('saveWebArchive')
.onClick(() => {
try {
this.controller.storeWebArchive("/data/storage/el2/base/", true, (error, filename) => {
if (error) {
console.info(`save web archive error: ` + JSON.stringify(error))
return;
}
if (filename != null) {
console.info(`save web archive success: ${filename}`)
}
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### storeWebArchive
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. The value cannot be null. |
| autoName | boolean | Yes | Whether to automatically generate a file name. The value **false** means not to automatically generate a file name. The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
**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](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
| 17100003 | Invalid resource path or file type. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('saveWebArchive')
.onClick(() => {
try {
this.controller.storeWebArchive("/data/storage/el2/base/", true)
.then(filename => {
if (filename != null) {
console.info(`save web archive success: ${filename}`)
}
})
.catch(error => {
console.log('error: ' + JSON.stringify(error));
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getUrl
getUrl(): string
Obtains the URL of this page.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------ | ------------------- |
| string | URL of the current page.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getUrl')
.onClick(() => {
try {
let url = this.controller.getUrl();
console.log("url: " + url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### stop
stop(): void
Stops page loading.
**System capability**: SystemCapability.Web.Webview.Core
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('stop')
.onClick(() => {
try {
this.controller.stop();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
});
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### backOrForward
backOrForward(step: number): void
Performs a specific number of steps forward or backward on the current page based on the history stack. No redirection will be performed if the corresponding page does not exist in the history stack.
**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](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
@State step: number = -2;
build() {
Column() {
Button('backOrForward')
.onClick(() => {
try {
this.controller.backOrForward(this.step);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebCookieManager
Implements a **WebCookie** object to manage behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie** object.
### getCookie
static getCookie(url: string): string
Obtains the cookie value corresponding to the specified URL.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | :------------------------ |
| url | string | Yes | URL of the cookie value to obtain.|
**Return value**
| Type | Description |
| ------ | ------------------------- |
| string | Cookie value corresponding to the specified URL.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100002 | Invalid url. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getCookie')
.onClick(() => {
try {
let value = web_webview.WebCookieManager.getCookie('www.example.com');
console.log("value: " + value);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### setCookie
static setCookie(url: string, value: string): void
Sets a cookie value for the specified URL.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | :------------------------ |
| url | string | Yes | URL of the cookie to set.|
| value | string | Yes | Cookie value to set. |
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100002 | Invalid url. |
| 17100005 | Invalid cookie value. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('setCookie')
.onClick(() => {
try {
web_webview.WebCookieManager.setCookie('www.example.com', 'a=b');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookieAsync
static saveCookieAsync(callback: AsyncCallback\<void>): void
Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | :------------------------------------------------- |
| callback | AsyncCallback\<void> | Yes | Callback used to return the operation result.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('saveCookieAsync')
.onClick(() => {
try {
web_webview.WebCookieManager.saveCookieAsync((error) => {
if (error) {
console.log("error: " + error);
}
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveCookieAsync
static saveCookieAsync(): Promise\<void>
Saves the cookies in the memory to the drive. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ---------------- | ----------------------------------------- |
| Promise\<void> | Promise used to return the operation result.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('saveCookieAsync')
.onClick(() => {
try {
web_webview.WebCookieManager.saveCookieAsync()
.then(() => {
console.log("saveCookieAsyncCallback success!");
})
.catch((error) => {
console.error("error: " + error);
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### putAcceptCookieEnabled
static putAcceptCookieEnabled(accept: boolean): void
Sets whether the **WebCookieManager** instance has the permission to send and receive cookies.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | :----------------------------------- |
| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('putAcceptCookieEnabled')
.onClick(() => {
try {
web_webview.WebCookieManager.putAcceptCookieEnabled(false);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### isCookieAllowed
static isCookieAllowed(): boolean
Checks whether the **WebCookieManager** instance has the permission to send and receive cookies.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | -------------------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('isCookieAllowed')
.onClick(() => {
let result = web_webview.WebCookieManager.isCookieAllowed();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### putAcceptThirdPartyCookieEnabled
static putAcceptThirdPartyCookieEnabled(accept: boolean): void
Sets whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------- | ---- | :----------------------------------------- |
| accept | boolean | Yes | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('putAcceptThirdPartyCookieEnabled')
.onClick(() => {
try {
web_webview.WebCookieManager.putAcceptThirdPartyCookieEnabled(false);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### isThirdPartyCookieAllowed
static isThirdPartyCookieAllowed(): boolean
Checks whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('isThirdPartyCookieAllowed')
.onClick(() => {
let result = web_webview.WebCookieManager.isThirdPartyCookieAllowed();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### existCookie
static existCookie(): boolean
Checks whether cookies exist.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | -------------------------------------- |
| boolean | Whether cookies exist.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('existCookie')
.onClick(() => {
let result = web_webview.WebCookieManager.existCookie();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteEntireCookie
static deleteEntireCookie(): void
Deletes all cookies.
**System capability**: SystemCapability.Web.Webview.Core
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('deleteEntireCookie')
.onClick(() => {
web_webview.WebCookieManager.deleteEntireCookie();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteSessionCookie
static deleteSessionCookie(): void
Deletes all session cookies.
**System capability**: SystemCapability.Web.Webview.Core
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('deleteSessionCookie')
.onClick(() => {
web_webview.WebCookieManager.deleteSessionCookie();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebStorage
Implements a **WebStorage** object to manage the Web SQL database and HTML5 Web Storage APIs. All **\<Web>** components in an application share a **WebStorage** object.
### deleteOrigin
static deleteOrigin(origin : string): void
Deletes all data in the specified origin.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------------ |
| origin | string | Yes | Index of the origin.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('deleteOrigin')
.onClick(() => {
try {
web_webview.WebStorage.deleteOrigin(this.origin);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### getOrigins
static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>) : void
Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | -------------------------------------- | ---- | ------------------------------------------------------ |
| callback | AsyncCallback\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Yes | Callback used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100012 | Invalid web storage origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getOrigins')
.onClick(() => {
try {
web_webview.WebStorage.getOrigins((error, origins) => {
if (error) {
console.log('error: ' + JSON.stringify(error));
return;
}
for (let i = 0; i < origins.length; i++) {
console.log('origin: ' + origins[i].origin);
console.log('usage: ' + origins[i].usage);
console.log('quota: ' + origins[i].quota);
}
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### getOrigins
static getOrigins() : Promise\<Array\<WebStorageOrigin>>
Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| -------------------------------- | ------------------------------------------------------------ |
| Promise\<Array\<[WebStorageOrigin](#webstorageorigin)>> | Promise used to return the information about the origins. For details, see [WebStorageOrigin](#webstorageorigin).|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100012 | Invalid web storage origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getOrigins')
.onClick(() => {
try {
web_webview.WebStorage.getOrigins()
.then(origins => {
for (let i = 0; i < origins.length; i++) {
console.log('origin: ' + origins[i].origin);
console.log('usage: ' + origins[i].usage);
console.log('quota: ' + origins[i].quota);
}
})
.catch(e => {
console.log('error: ' + JSON.stringify(e));
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### getOriginQuota
static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void
Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| origin | string | Yes | Index of the origin.|
| callback | AsyncCallback\<number> | Yes | Storage quota of the origin. |
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('getOriginQuota')
.onClick(() => {
try {
web_webview.WebStorage.getOriginQuota(this.origin, (error, quota) => {
if (error) {
console.log('error: ' + JSON.stringify(error));
return;
}
console.log('quota: ' + quota);
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### getOriginQuota
static getOriginQuota(origin : string) : Promise\<number>
Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| origin | string | Yes | Index of the origin.|
**Return value**
| Type | Description |
| --------------- | --------------------------------------- |
| Promise\<number> | Promise used to return the storage quota of the origin.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('getOriginQuota')
.onClick(() => {
try {
web_webview.WebStorage.getOriginQuota(this.origin)
.then(quota => {
console.log('quota: ' + quota);
})
.catch(e => {
console.log('error: ' + JSON.stringify(e));
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### getOriginUsage
static getOriginUsage(origin : string, callback : AsyncCallback\<number>) : void
Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------- | ---- | ------------------ |
| origin | string | Yes | Index of the origin.|
| callback | AsyncCallback\<number> | Yes | Storage usage of the origin. |
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('getOriginUsage')
.onClick(() => {
try {
web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => {
if (error) {
console.log('error: ' + JSON.stringify(error));
return;
}
console.log('usage: ' + usage);
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### getOriginUsage
static getOriginUsage(origin : string) : Promise\<number>
Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| origin | string | Yes | Index of the origin.|
**Return value**
| Type | Description |
| --------------- | ------------------------------------- |
| Promise\<number> | Promise used to return the storage usage of the origin.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ----------------------------------------------------- |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('getOriginUsage')
.onClick(() => {
try {
web_webview.WebStorage.getOriginUsage(this.origin)
.then(usage => {
console.log('usage: ' + usage);
})
.catch(e => {
console.log('error: ' + JSON.stringify(e));
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### deleteAllData
static deleteAllData(): void
Deletes all data in the Web SQL Database.
**System capability**: SystemCapability.Web.Webview.Core
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('deleteAllData')
.onClick(() => {
try {
web_webview.WebStorage.deleteAllData();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
## WebDataBase
Implements a **WebDataBase** object.
### getHttpAuthCredentials
static getHttpAuthCredentials(host: string, realm: string): Array\<string>
Retrieves HTTP authentication credentials for a given host and realm. This API returns the result synchronously.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ---------------------------- |
| host | string | Yes | Host to which HTTP authentication credentials apply.|
| realm | string | Yes | Realm to which HTTP authentication credentials apply. |
**Return value**
| Type | Description |
| ----- | -------------------------------------------- |
| Array\<string> | Returns the array of the matching user names and passwords if the operation is successful; returns an empty array otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
host: string = "www.spincast.org";
realm: string = "protected example";
username_password: string[];
build() {
Column() {
Button('getHttpAuthCredentials')
.onClick(() => {
try {
this.username_password = web_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm);
console.log('num: ' + this.username_password.length);
ForEach(this.username_password, (item) => {
console.log('username_password: ' + item);
}, item => item)
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveHttpAuthCredentials
static saveHttpAuthCredentials(host: string, realm: string, username: string, password: string): void
Saves HTTP authentication credentials for a given host and realm. This API returns the result synchronously.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ---------------------------- |
| host | string | Yes | Host to which HTTP authentication credentials apply.|
| realm | string | Yes | Realm to which HTTP authentication credentials apply. |
| username | string | Yes | User name. |
| password | string | Yes | Password. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
host: string = "www.spincast.org";
realm: string = "protected example";
build() {
Column() {
Button('saveHttpAuthCredentials')
.onClick(() => {
try {
web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche");
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### existHttpAuthCredentials
static existHttpAuthCredentials(): boolean
Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ------- | ------------------------------------------------------------ |
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('existHttpAuthCredentials')
.onClick(() => {
try {
let result = web_webview.WebDataBase.existHttpAuthCredentials();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteHttpAuthCredentials
static deleteHttpAuthCredentials(): void
Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously.
**System capability**: SystemCapability.Web.Webview.Core
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('deleteHttpAuthCredentials')
.onClick(() => {
try {
web_webview.WebDataBase.deleteHttpAuthCredentials();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebAsyncController
Implements a **WebAsyncController** object, which can be used to control the behavior of a **\<Web>** component with asynchronous callbacks. A **WebAsyncController **object controls one **\<Web>** component.
### Creating an Object
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
webAsyncController: WebAsyncController = new web_webview.WebAsyncController(this.controller)
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### constructor<sup>9+</sup>
constructor(controller: WebController)
Implements a **WebAsyncController** by binding it with a [WebController](../arkui-ts/ts-basic-components-web.md#webcontroller) object.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description|
| ----- | ---- | ---- | --- |
| controller | [WebController](../arkui-ts/ts-basic-components-web.md#webcontroller) | Yes| **WebviewController** to bind.|
### storeWebArchive<sup>9+</sup>
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. The value cannot be null.
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('saveWebArchive')
.onClick(() => {
let webAsyncController = new web_webview.WebAsyncController(this.controller)
webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => {
if (filename != null) {
console.info(`save web archive success: ${filename}`)
}
})
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### storeWebArchive<sup>9+</sup>
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. The value cannot be null.
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
**Return value**
| Type | Description |
| ---------------------------------------- | ---------------------------------------- |
| Promise<string> | Promise used to return the save path if the operation is successful and null otherwise.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveWebArchive')
.onClick(() => {
let webAsyncController = new web_webview.WebAsyncController(this.controller);
webAsyncController.storeWebArchive("/data/storage/el2/base/", true)
.then(filename => {
if (filename != null) {
console.info(`save web archive success: ${filename}`)
}
})
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## GeolocationPermissions
Implements a **GeolocationPermissions** object.
### allowGeolocation
static allowGeolocation(origin: string): void
Allows the specified origin to use the geolocation information.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| origin | string | Yes |Index of the origin.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('allowGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.allowGeolocation(this.origin);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteGeolocation
static deleteGeolocation(origin: string): void
Clears the geolocation permission status of a specified origin.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | ------------------ |
| origin | string | Yes | Index of the origin.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('deleteGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.deleteGeolocation(this.origin);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getAccessibleGeolocation
static getAccessibleGeolocation(origin: string, callback: AsyncCallback\<boolean>): void
Obtains the geolocation permission status of the specified origin. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------- | ---- | ------------------------------------------------------------ |
| origin | string | Yes | Index of the origin. |
| callback | AsyncCallback\<boolean> | Yes | Callback used to return the geolocation permission status of the specified origin. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified origin is not found.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('getAccessibleGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => {
if (error) {
console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error));
return;
}
console.log('getAccessibleGeolocationAsync result: ' + result);
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getAccessibleGeolocation
static getAccessibleGeolocation(origin: string): Promise\<boolean>
Obtains the geolocation permission status of the specified origin. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name| Type| Mandatory| Description |
| ------ | -------- | ---- | -------------------- |
| origin | string | Yes | Index of the origin.|
**Return value**
| Type | Description |
| ---------------- | ------------------------------------------------------------ |
| Promise\<boolean> | Promise used to return the geolocation permission status of the specified origin. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified origin is not found.|
**Error codes**
For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
| ID| Error Message |
| -------- | ------------------------------------------------------ |
| 17100011 | Invalid origin. |
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
origin: string = "file:///";
build() {
Column() {
Button('getAccessibleGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin)
.then(result => {
console.log('getAccessibleGeolocationPromise result: ' + result);
}).catch(error => {
console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error));
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getStoredGeolocation
static getStoredGeolocation(callback: AsyncCallback\<Array\<string>>): void
Obtains the geolocation permission status of all origins. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ---------------------------- | ---- | ---------------------------------------- |
| callback | AsyncCallback\<Array\<string>> | Yes | Callback used to return the geolocation permission status of all origins.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getStoredGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => {
if (error) {
console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error));
return;
}
let origins_str: string = origins.join();
console.log('getStoredGeolocationAsync origins: ' + origins_str);
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getStoredGeolocation
static getStoredGeolocation(): Promise\<Array\<string>>
Obtains the geolocation permission status of all origins. This API uses a promise to return the result.
**System capability**: SystemCapability.Web.Webview.Core
**Return value**
| Type | Description |
| ---------------------- | --------------------------------------------------------- |
| Promise\<Array\<string>> | Promise used to return the geolocation permission status of all origins.|
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('getStoredGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.getStoredGeolocation()
.then(origins => {
let origins_str: string = origins.join();
console.log('getStoredGeolocationPromise origins: ' + origins_str);
}).catch(error => {
console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error));
});
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteAllGeolocation
static deleteAllGeolocation(): void
Clears the geolocation permission status of all sources.
**System capability**: SystemCapability.Web.Webview.Core
**Example**
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('deleteAllGeolocation')
.onClick(() => {
try {
web_webview.GeolocationPermissions.deleteAllGeolocation();
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## HeaderV9
Describes the request/response header returned by the **\<Web>** component.
**System capability**: SystemCapability.Web.Webview.Core
| Name | Type | Readable| Writable|Description |
| ----------- | ------ | -----|------|------------------- |
| headerKey | string | Yes| Yes| Key of the request/response header. |
| headerValue | string | Yes| Yes| Value of the request/response header.|
## HitTestTypeV9
**System capability**: SystemCapability.Web.Webview.Core
| Name | Value| Description |
| ------------- | -- |----------------------------------------- |
| EditText | 0 |Editable area. |
| Email | 1 |Email address. |
| HttpAnchor | 2 |Hyperlink whose **src** is **http**. |
| HttpAnchorImg | 3 |Image with a hyperlink, where **src** is **http**.|
| Img | 4 |HTML::img tag. |
| Map | 5 |Geographical address. |
| Phone | 6 |Phone number. |
| Unknown | 7 |Unknown content. |
## HitTestValue
Provides the element information of the area being clicked. For details about the sample code, see **getHitTestValue**.
**System capability**: SystemCapability.Web.Webview.Core
| Name| Type| Readable| Writable| Description|
| ---- | ---- | ---- | ---- |---- |
| type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.|
| extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.|
## WebStorageOrigin
Provides usage information of the Web SQL Database.
**System capability**: SystemCapability.Web.Webview.Core
| Name | Type | Readable| Writable| Description|
| ------ | ------ | ---- | ---- | ---- |
| origin | string | Yes | No| Index of the origin.|
| usage | number | Yes | No| Storage usage of the origin. |
| quota | number | Yes | No| Storage quota of the origin. |
# Web
The **<Web\>** component can be used to display web pages.
> **NOTE**
>
> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
> - You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
The **<Web\>** component can be used to display web pages.
## Required Permissions
To use online resources, the application must have the **ohos.permission.INTERNET** permission. For details about how to apply for a permission, see [Declaring Permissions](../../security/accesstoken-guidelines.md).
......@@ -25,9 +25,9 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController})
**Parameters**
| Name | Type | Mandatory | Description |
| ---------- | ------------------------------- | ---- | ------- |
| ---------- | ---------------------------------------- | ---- | ------- |
| src | [ResourceStr](ts-types.md) | Yes | Address of a web page resource.|
| controller | [WebController](#webcontroller) or WebviewController |Yes | Controller. |
| controller | [WebController](#webcontroller) \| [WebviewController<sup>9+</sup>](../apis/js-apis-webview.md#webviewcontroller) | Yes | Controller. |
**Example**
......@@ -88,7 +88,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController})
## Attributes
The **\<Web>** component has network attributes.
Only the following universal attributes are supported: [width](ts-universal-attributes-size.md#Attributes), [height](ts-universal-attributes-size.md#attributes), [padding](ts-universal-attributes-size.md#Attributes), [margin](ts-universal-attributes-size.md#attributes), and [border](ts-universal-attributes-border.md#attributes).
### domStorageAccess
......@@ -99,7 +99,7 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ---- | ------------------------------------ |
| ---------------- | ------- | ---- | ----- | ------------------------------------ |
| domStorageAccess | boolean | Yes | false | Whether to enable the DOM Storage API.|
**Example**
......@@ -123,12 +123,12 @@ Sets whether to enable the DOM Storage API. By default, this feature is disabled
fileAccess(fileAccess: boolean)
Sets whether to enable access to the file system in the application. Access to the files in **rawfile** specified through [$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md) are not affected by the setting.
Sets whether to enable access to the file system in the application. This setting does not affect the access to the files specified through [$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md).
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------- | ---- | ---- | ---------------------------------------- |
| ---------- | ------- | ---- | ---- | ---------------------- |
| fileAccess | boolean | Yes | true | Whether to enable access to the file system in the application. By default, this feature is enabled.|
**Example**
......@@ -148,35 +148,6 @@ Sets whether to enable access to the file system in the application. Access to t
}
```
### fileFromUrlAccess<sup>9+</sup>
fileFromUrlAccess(fileFromUrlAccess: boolean)
Sets whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled. Access to the files in **rawfile** specified through [$rawfile(filepath/filename)](../../quick-start/resource-categories-and-access.md) are not affected by the setting.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------------- | ------- | ---- | ----- | ---------------------------------------- |
| fileFromUrlAccess | boolean | Yes | false | Whether to allow the use of JavaScript scripts on web pages for access to content in the application file system. By default, this feature is disabled.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.fileFromUrlAccess(true)
}
}
}
```
### imageAccess
imageAccess(imageAccess: boolean)
......@@ -187,7 +158,7 @@ Sets whether to enable automatic image loading. By default, this feature is enab
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ------- | ---- | ---- | --------------- |
| imageAccess | boolean | Yes | true | Whether to enable automatic image loading. By default, this feature is enabled.|
| imageAccess | boolean | Yes | true | Whether to enable automatic image loading.|
**Example**
```ts
......@@ -210,16 +181,16 @@ Sets whether to enable automatic image loading. By default, this feature is enab
javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Array\<string\>,
controller: WebController | WebviewController})
Injects a JavaScript object into the window. Methods of this object can be invoked in the window. The parameters cannot be updated.
Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. The parameters cannot be updated.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ------------------------- |
| ---------- | ---------------------------------------- | ---- | ---- | ------------------------- |
| object | object | Yes | - | Object to be registered. Methods can be declared, but attributes cannot. |
| name | string | Yes | - | Name of the object to be registered, which is the same as that invoked in the window.|
| methodList | Array\<string\> | Yes | - | Methods of the JavaScript object to be registered at the application side. |
| controller | [WebController](#webcontroller) or WebviewController | Yes | - | Controller. |
| controller | [WebController](#webcontroller) or [WebviewController](../apis/js-apis-webview.md#webviewcontroller) | Yes | - | Controller. |
**Example**
......@@ -326,7 +297,7 @@ Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. B
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | --------------------------- | ---- | ---- | --------- |
| --------- | --------------------------- | ---- | -------------- | --------- |
| mixedMode | [MixedMode](#mixedmode)| Yes | MixedMode.None | Mixed content to load.|
**Example**
......@@ -443,7 +414,7 @@ Sets whether to enable database access. By default, this feature is disabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ------- | ---- | ---- | ----------------- |
| -------------- | ------- | ---- | ----- | ----------------- |
| databaseAccess | boolean | Yes | false | Whether to enable database access.|
**Example**
......@@ -472,7 +443,7 @@ Sets whether to enable geolocation access. By default, this feature is enabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ------- | ---- | ---- | ----------------- |
| ----------------- | ------- | ---- | ---- | --------------- |
| geolocationAccess | boolean | Yes | true | Whether to enable geolocation access.|
**Example**
......@@ -501,7 +472,7 @@ Sets whether a manual click is required for video playback.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | ---- | ---- | --------- |
| ------ | ------- | ---- | ---- | ----------------- |
| access | boolean | Yes | true | Whether a manual click is required for video playback.|
**Example**
......@@ -531,7 +502,7 @@ Sets whether to enable the multi-window permission.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------------- | ------- | ---- | ---- | ----------------- |
| ----------- | ------- | ---- | ----- | ------------ |
| multiWindow | boolean | Yes | false | Whether to enable the multi-window permission.|
**Example**
......@@ -560,7 +531,7 @@ Sets the cache mode.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | --------------------------- | ---- | ---- | --------- |
| --------- | --------------------------- | ---- | ----------------- | --------- |
| cacheMode | [CacheMode](#cachemode)| Yes | CacheMode.Default | Cache mode to set.|
**Example**
......@@ -590,7 +561,7 @@ Sets the text zoom ratio of the page. The default value is **100**, which indica
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | ---- | ---- | --------------- |
| ------------- | ------ | ---- | ---- | --------------- |
| textZoomRatio | number | Yes | 100 | Text zoom ratio to set.|
**Example**
......@@ -620,7 +591,7 @@ Sets the scale factor of the entire page. The default value is 100%.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | ---- | ---- | --------------- |
| ------- | ------ | ---- | ---- | --------------- |
| percent | number | Yes | 100 | Scale factor of the entire page.|
**Example**
......@@ -680,7 +651,7 @@ Sets whether to enable web debugging.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | ---- | ---- | --------- |
| ------------------ | ------- | ---- | ----- | ------------- |
| webDebuggingAccess | boolean | Yes | false | Whether to enable web debugging.|
**Example**
......@@ -701,10 +672,6 @@ Sets whether to enable web debugging.
}
```
> **NOTE**<br>
>
> Only the following universal attributes are supported: [width](ts-universal-attributes-size.md#Attributes), [height](ts-universal-attributes-size.md#attributes), [padding](ts-universal-attributes-size.md#Attributes), [margin](ts-universal-attributes-size.md#attributes), and [border](ts-universal-attributes-border.md#attributes).
## Events
The universal events are not supported.
......@@ -771,7 +738,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
Triggered when the current page is about to exit after the user refreshes or closes the page. If the user refreshes the page, this callback is invoked only when the page has obtained focus.
Triggered when this page is about to exit after the user refreshes or closes the page. This callback is triggered only when the page has obtained focus.
**Parameters**
......@@ -1263,7 +1230,7 @@ Triggered when loading of the web page is complete. This API is used by an appli
**Parameters**
| Name | Type | Description |
| ----------- | ------- | --------------------------------- |
| ----------- | ------- | ---------------------------------------- |
| url | string | URL to be accessed. |
| isRefreshed | boolean | Whether the page is reloaded. The value **true** means that the page is reloaded by invoking the [refresh](#refresh) API, and **false** means the opposite.|
......@@ -1335,7 +1302,7 @@ Triggered to process an HTML form whose input type is **file**, in response to t
**Return value**
| Type | Description |
| ------- | ----------------------------------- |
| ------- | ---------------------------------------- |
| boolean | The value **true** means that the pop-up window provided by the system is displayed. The value **false** means that the default web pop-up window is displayed.|
**Example**
......@@ -1384,7 +1351,7 @@ Invoked to notify the **\<Web>** component of the URL of the loaded resource fil
**Parameters**
| Name | Type | Description |
| ---- | ---------------------------------------- | --------- |
| ---- | ------ | -------------- |
| url | string | URL of the loaded resource file.|
**Example**
......@@ -1416,7 +1383,7 @@ Invoked when the display ratio of this page changes.
**Parameters**
| Name | Type | Description |
| ---- | ---------------------------------------- | --------- |
| -------- | ------ | ------------ |
| oldScale | number | Display ratio of the page before the change.|
| newScale | number | Display ratio of the page after the change.|
......@@ -1494,7 +1461,7 @@ Invoked when the **\<Web>** component is about to access a URL. This API is used
**Return value**
| Type | Description |
| ---------------------------------------- | --------------------------- |
| ---------------------------------------- | ---------------------------------------- |
| [WebResourceResponse](#webresourceresponse) | If response data is returned, the data is loaded based on the response data. If no response data is returned, null is returned, indicating that the data is loaded in the original mode.|
**Example**
......@@ -1622,9 +1589,9 @@ Invoked when an SSL error occurs during resource loading.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| ------- | ------------------------------------ | -------------- |
| handler | [SslErrorHandler](#sslerrorhandler9) | The user's operation.|
| error | [SslError](#sslerror9) | Error code.|
| error | [SslError](#sslerror9) | Error code. |
**Example**
......@@ -1668,18 +1635,18 @@ Invoked when an SSL error occurs during resource loading.
### onClientAuthenticationRequest<sup>9+</sup>
onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\<string>, issuers : Array\<string>}) => void)
onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array<string>, issuers : Array<string>}) => void)
Invoked when an SSL client certificate request is received.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation.|
| host | string | Host name of the server that requests a certificate.|
| port | number | Port number of the server that requests a certificate.|
| keyTypes| Array\<string> | Acceptable asymmetric private key types.|
| -------- | ---------------------------------------- | --------------- |
| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation. |
| host | string | Host name of the server that requests a certificate. |
| port | number | Port number of the server that requests a certificate. |
| keyTypes | Array\<string> | Acceptable asymmetric private key types. |
| issuers | Array\<string> | Issuer of the certificate that matches the private key.|
**Example**
......@@ -1730,8 +1697,8 @@ Invoked when a permission request is received.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| request | [PermissionRequest](#permissionrequest9) | The user's operation. |
| ------- | ---------------------------------------- | -------------- |
| request | [PermissionRequest](#permissionrequest9) | The user's operation.|
**Example**
......@@ -1779,14 +1746,14 @@ Invoked when a context menu is displayed upon a long press on a specific element
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| param | [WebContextMenuParam](#webcontextmenuparam9) | Parameters related to the context menu.|
| ------ | ---------------------------------------- | ----------- |
| param | [WebContextMenuParam](#webcontextmenuparam9) | Parameters related to the context menu. |
| result | [WebContextMenuResult](#webcontextmenuresult9) | Result of the context menu.|
**Return value**
| Type | Description |
| ------ | -------------------- |
| ------- | ------------------------ |
| boolean | The value **true** means a custom menu, and **false** means the default menu.|
**Example**
......@@ -1819,7 +1786,7 @@ Invoked when the scrollbar of the page scrolls.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| ------- | ------ | ------------ |
| xOffset | number | Position of the scrollbar on the x-axis.|
| yOffset | number | Position of the scrollbar on the y-axis.|
......@@ -1852,7 +1819,7 @@ Registers a callback for receiving a request to obtain the geolocation informati
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| ----------- | ------------------------------- | -------------- |
| origin | string | Index of the origin. |
| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.|
......@@ -1897,7 +1864,7 @@ Triggered to notify the user that the request for obtaining the geolocation info
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| -------- | ---------- | -------------------- |
| callback | () => void | Callback invoked when the request for obtaining geolocation information has been canceled. |
**Example**
......@@ -1929,7 +1896,7 @@ Registers a callback for the component's entering into full screen mode.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| ------- | ---------------------------------------- | -------------- |
| handler | [FullScreenExitHandler](#fullscreenexithandler9) | Function handle for exiting full screen mode.|
**Example**
......@@ -1962,7 +1929,7 @@ Registers a callback for the component's exiting full screen mode.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| -------- | ---------- | ------------- |
| callback | () => void | Callback invoked when the component exits full screen mode.|
**Example**
......@@ -1998,11 +1965,11 @@ Registers a callback for window creation.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| ------------- | ---------------------------------------- | -------------------------- |
| isAlert | boolean | Whether to open the target URL in a new window. The value **true** means to open the target URL in a new window, and **false** means to open the target URL in a new tab.|
| isUserTrigger | boolean | Whether the creation is triggered by the user. The value **true** means that the creation is triggered by the user, and **false** means the opposite.|
| targetUrl | string | Target URL.|
| handler | [ControllerHandler](#controllerhandler9) | **WebController** instance for setting the new window.|
| isUserTrigger | boolean | Whether the creation is triggered by the user. The value **true** means that the creation is triggered by the user, and **false** means the opposite. |
| targetUrl | string | Target URL. |
| handler | [ControllerHandler](#controllerhandler9) | **WebController** instance for setting the new window. |
**Example**
......@@ -2035,7 +2002,7 @@ Registers a callback for window closure.
**Parameters**
| Name | Type | Description |
| ----------- | ------------------------------- | ---------------- |
| -------- | ---------- | ------------ |
| callback | () => void | Callback invoked when the window closes.|
**Example**
......@@ -2057,6 +2024,41 @@ Registers a callback for window closure.
}
```
### onSearchResultReceive<sup>9+</sup>
onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute
Invoked to notify the caller of the search result on the web page.
**Parameters**
| Name | Type | Description |
| ------------------ | ------- | ---------------------------------------- |
| activeMatchOrdinal | number | Sequence number of the current match, which starts from 0. |
| numberOfMatches | number | Total number of matches. |
| isDoneCounting | boolean | Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting)
})
}
}
}
```
## ConsoleMessage
Implements the **ConsoleMessage** object. For details about the sample code, see [onConsole](#onconsole).
......@@ -2139,7 +2141,7 @@ Notifies the **\<Web>** component of the user's confirm operation in the dialog
## FullScreenExitHandler<sup>9+</sup>
Defines a **FullScreenExitHandler** for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9).
Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9).
### exitFullScreen<sup>9+</sup>
......@@ -2149,7 +2151,7 @@ Exits full screen mode.
## ControllerHandler<sup>9+</sup>
Defines a **WebController** for new web components. For the sample code, see [onWindowNew](#onwindownew9).
Implements a **WebController** object for new **\<Web>** components. For the sample code, see [onWindowNew](#onwindownew9).
### setWebController<sup>9+</sup>
......@@ -2160,7 +2162,7 @@ Sets a **WebController** object.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ----------- |
| ---------- | ------------- | ---- | ---- | ------------------------- |
| controller | WebController | Yes | - | **WebController** object to set.|
## WebResourceError
......@@ -2540,7 +2542,7 @@ Continues using the SSL certificate.
## ClientAuthenticationHandler<sup>9+</sup>
Defines a **ClientAuthenticationHandler** object returned by the **\<Web>** component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9).
Implements a **ClientAuthenticationHandler** object returned by the **\<Web>** component. For details about the sample code, see [onClientAuthenticationRequest](#onclientauthenticationrequest9).
### confirm<sup>9+</sup>
......@@ -2550,9 +2552,9 @@ Uses the specified private key and client certificate chain.
**Parameters**
| Name | Type| Mandatory | Description |
| -------- | ------ | ---- | ---------- |
| priKeyFile | string | Yes | File that stores the private key, which is a directory including the file name.|
| Name | Type | Mandatory | Description |
| ------------- | ------ | ---- | ------------------ |
| priKeyFile | string | Yes | File that stores the private key, which is a directory including the file name. |
| certChainFile | string | Yes | File that stores the certificate chain, which is a directory including the file name.|
### cancel<sup>9+</sup>
......@@ -2586,7 +2588,7 @@ Obtains the origin of this web page.
**Return value**
| Type | Description |
| ------- | --------------------- |
| ------ | ------------ |
| string | Origin of the web page that requests the permission.|
### getAccessibleResource<sup>9+</sup>
......@@ -2598,7 +2600,7 @@ Obtains the list of accessible resources requested for the web page. For details
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| --------------- | ------------- |
| Array\<string\> | List of accessible resources requested by the web page.|
### grant<sup>9+</sup>
......@@ -2609,8 +2611,8 @@ Grants the permission for resources requested by the web page.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| --------- | --------------- | ---- | ----- | ---------------------- |
| Name | Type | Mandatory | Default Value | Description |
| --------- | --------------- | ---- | ---- | ------------- |
| resources | Array\<string\> | Yes | - | List of accessible resources requested by the web page.|
## WebContextMenuParam<sup>9+</sup>
......@@ -2626,7 +2628,7 @@ Obtains the X coordinate of the context menu.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| ------ | ------------------ |
| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.|
### y<sup>9+</sup>
......@@ -2638,7 +2640,7 @@ Obtains the Y coordinate of the context menu.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| ------ | ------------------ |
| number | If the display is normal, a non-negative integer is returned. Otherwise, **-1** is returned.|
### getLinkUrl<sup>9+</sup>
......@@ -2650,7 +2652,7 @@ Obtains the URL of the destination link.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| ------ | ------------------------- |
| string | If it is a link that is being long pressed, the URL that has passed the security check is returned.|
### getUnfilterendLinkUrl<sup>9+</sup>
......@@ -2662,7 +2664,7 @@ Obtains the URL of the destination link.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| ------ | --------------------- |
| string | If it is a link that is being long pressed, the original URL is returned.|
### getSourceUrl<sup>9+</sup>
......@@ -2674,7 +2676,7 @@ Obtain the source URL.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| ------ | ------------------------ |
| string | If the selected element has the **src** attribute, the URL in the **src** is returned.|
### existsImageContents<sup>9+</sup>
......@@ -2686,12 +2688,12 @@ Checks whether image content exists.
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| ------- | ------------------------- |
| boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.|
## WebContextMenuResult<sup>9+</sup>
Defines the response event executed when a context menu is displayed. For details about the sample code, see [onContextMenuShow](#oncontextmenushow9).
Implements the response event executed when a context menu is displayed. For details about the sample code, see [onContextMenuShow](#oncontextmenushow9).
### closeContextMenu<sup>9+</sup>
......@@ -2717,15 +2719,15 @@ Sets the geolocation permission status of a web page.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| --------- | ------- | ---- | ----- | ---------------------- |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------- | ---- | ---- | ---------------------------------------- |
| origin | string | Yes | - | Index of the origin. |
| allow | boolean | Yes | - | Geolocation permission status.|
| allow | boolean | Yes | - | Geolocation permission status. |
| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.|
## WebController
Defines a **WebController** to control the behavior of the **\<Web>** component. A **WebController** can control only one **\<Web>** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\<Web>** component.
Implements a **WebController** object to control the behavior of the **\<Web>** component. A **WebController** can control only one **\<Web>** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\<Web>** component.
### Creating an Object
......@@ -3364,7 +3366,7 @@ Sets a zoom factor for the current web page.
### zoomIn<sup>9+</sup>
zoomIn(): boolean
Zooms in on the current web page by 20%.
Zooms in on this web page by 20%.
**Return value**
......@@ -3397,7 +3399,7 @@ Zooms in on the current web page by 20%.
### zoomOut<sup>9+</sup>
zoomOut(): boolean
Zooms out of the current web page by 20%.
Zooms out of this web page by 20%.
**Return value**
......@@ -3524,7 +3526,7 @@ Registers a JavaScript object and invokes the methods of the object in the windo
runJavaScript(options: { script: string, callback?: (result: string) => void })
Asynchronously executes a JavaScript script. This API uses a callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be executed in **onPageEnd**.
Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**.
**Parameters**
......@@ -3664,7 +3666,7 @@ Clears the user operation corresponding to the SSL certificate error event recor
clearClientAuthenticationCache(): void
Clears the user operation corresponding to the client certificate request event recorded by the \<Web> component.
Clears the user operation corresponding to the client certificate request event recorded by the **\<Web>** component.
**Example**
......@@ -3730,7 +3732,7 @@ Creates web message ports.
| Type | Description |
| ------------------------------- | ------------- |
| ---------------------------------------- | ---------- |
| Array\<[WebMessagePort](#webmessageport9)\> | List of web message ports.|
**Example**
......@@ -3764,9 +3766,9 @@ Sends a web message to an HTML5 window.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ------------------------- |
| message | [WebMessageEvent](#webmessageevent9) | Yes | - |Message to send, including the data and message port.|
| uri | string | Yes | - | URI for receiving the message.|
| ------- | ------------------------------------ | ---- | ---- | ----------------- |
| message | [WebMessageEvent](#webmessageevent9) | Yes | - | Message to send, including the data and message port.|
| uri | string | Yes | - | URI for receiving the message. |
**Example**
......@@ -3870,12 +3872,12 @@ Sends a web message to an HTML5 window.
getUrl(): string
Obtains the URL of the current page.
Obtains the URL of this page.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| ------ | ----------- |
| string | URL of the current page.|
**Example**
......@@ -3898,6 +3900,113 @@ Obtains the URL of the current page.
}
```
### searchAllAsync<sup>9+</sup>
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](#onsearchresultreceive9).
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | ---- | ---- | ------- |
| searchString | string | Yes | - | Search keyword.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
@State searchString: string = "xxx"
build() {
Column() {
Button('searchString')
.onClick(() => {
this.controller.searchAllAsync(this.searchString)
})
Button('clearMatches')
.onClick(() => {
this.controller.clearMatches()
})
Button('searchNext')
.onClick(() => {
this.controller.searchNext(true)
})
Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting)
})
}
}
}
```
### clearMatches<sup>9+</sup>
clearMatches(): void
Clears the matches found through [searchAllAsync](#searchallasync9).
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('clearMatches')
.onClick(() => {
this.controller.clearMatches()
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### searchNext<sup>9+</sup>
searchNext(forward: boolean): void
Searches for and highlights the next match.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------- | ------- | ---- | ---- | ----------- |
| forward | boolean | Yes | - | Whether to search forward.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('searchNext')
.onClick(() => {
this.controller.searchNext(true)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## HitTestValue<sup>9+</sup>
Implements the **HitTestValue** object. For details about the sample code, see [getHitTestValue](#gethittestvalue9).
......@@ -4009,13 +4118,13 @@ Obtains the cookie value corresponding to the specified URL.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ---- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie value to obtain.|
**Return value**
| Type | Description |
| ------- | -------------------- |
| ------ | ----------------- |
| string | Cookie value corresponding to the specified URL.|
**Example**
......@@ -4051,12 +4160,12 @@ Sets a cookie value for the specified URL.
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie to set.|
| value | string | Yes | - | Cookie value to set.|
| value | string | Yes | - | Cookie value to set. |
**Return value**
| Type | Description |
| ------- | -------------------- |
| ------- | ------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
......@@ -4124,7 +4233,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the
**Return value**
| Type | Description |
| ------- | -------------------- |
| ----------------- | --------------------------- |
| Promise\<boolean> | Promise used to return the result.|
**Example**
......@@ -4163,7 +4272,7 @@ Saves cookies in the memory to the drive. This API uses an asynchronous callback
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| -------- | ----------------------- | ---- | ---- | ---------------------------- |
| callback | AsyncCallback\<boolean> | Yes | - | Callback used to return the operation result.|
**Example**
......@@ -4198,7 +4307,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and
**Return value**
| Type | Description |
| ------- | -------------------- |
| ------- | ------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive cookies.|
**Example**
......@@ -4232,7 +4341,7 @@ Sets whether the **WebCookieManager** instance has the permission to send and re
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ------ | ------- | ---- | ---- | --------------------- |
| accept | boolean | Yes | - | Whether the **WebCookieManager** instance has the permission to send and receive cookies.|
**Example**
......@@ -4265,7 +4374,7 @@ Checks whether the **WebCookieManager** instance has the permission to send and
**Return value**
| Type | Description |
| ------- | -------------------- |
| ------- | ---------------------- |
| boolean | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.|
**Example**
......@@ -4299,7 +4408,7 @@ Sets whether the **WebCookieManager** instance has the permission to send and re
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ------ | ------- | ---- | ---- | ------------------------ |
| accept | boolean | Yes | - | Whether the **WebCookieManager** instance has the permission to send and receive third-party cookies.|
**Example**
......@@ -4332,7 +4441,7 @@ Checks whether cookies exist.
**Return value**
| Type | Description |
| ------- | -------------------- |
| ------- | ----------- |
| boolean | Whether cookies exist.|
**Example**
......@@ -4419,7 +4528,7 @@ Implements the **WebDataBase** object.
static existHttpAuthCredentials(): boolean
Checks whether any saved HTTP authentication credentials exist. This API is synchronous.
Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously.
**Return value**
......@@ -4482,7 +4591,7 @@ Deletes all HTTP authentication credentials saved in the cache. This API returns
static getHttpAuthCredentials(host: string, realm: string): Array\<string\>
Retrieves HTTP authentication credentials for a given host and domain. This API is synchronous.
Retrieves HTTP authentication credentials for a given host and domain. This API returns the result synchronously.
**Parameters**
......@@ -4565,18 +4674,18 @@ Saves HTTP authentication credentials for a given host and realm. This API retur
## GeolocationPermissions<sup>9+</sup>
Defines a **GeolocationPermissions** object.
Implements a **GeolocationPermissions** object.
### allowGeolocation<sup>9+</sup>
static allowGeolocation(origin: string): void
Allows the specified source to use the geolocation information.
Allows the specified origin to use the geolocation information.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ---------- |
| origin | string | Yes | - | Index of the origin.|
**Example**
......@@ -4605,12 +4714,12 @@ Allows the specified source to use the geolocation information.
static deleteGeolocation(origin: string): void
Clears the geolocation permission status of a specified source.
Clears the geolocation permission status of a specified origin.
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ---------- |
| origin | string | Yes | - | Index of the origin.|
**Example**
......@@ -4670,10 +4779,10 @@ Obtains the geolocation permission status of the specified source. This API uses
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| origin | string | Yes | - | Index of the origin.|
| callback | AsyncCallback\<boolean\> | Yes| - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------------------------ | ---- | ---- | ---------------------------------------- |
| origin | string | Yes | - | Index of the origin. |
| callback | AsyncCallback\<boolean\> | Yes | - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
**Example**
......@@ -4711,14 +4820,14 @@ Obtains the geolocation permission status of the specified source. This API uses
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ---------- |
| origin | string | Yes | - | Index of the origin.|
**Return value**
| Type | Description |
| ------------------ | ------------------------------------ |
| ------------------ | ---------------------------------------- |
| Promise\<boolean\> | Promise used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
**Example**
......@@ -4755,9 +4864,9 @@ Obtains the geolocation permission status of all sources. This API uses an async
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| callback | AsyncCallback\<Array\<string\>\> | Yes| - | Callback used to return the geolocation permission status of all sources.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------------------------- | ---- | ---- | -------------------- |
| callback | AsyncCallback\<Array\<string\>\> | Yes | - | Callback used to return the geolocation permission status of all sources.|
**Example**
......@@ -4795,14 +4904,14 @@ Obtains the geolocation permission status of all sources. This API uses a promis
**Parameters**
| Name | Type| Mandatory| Default Value| Description |
| -------- | -------- | ---- | ----- | ------------- |
| callback | AsyncCallback\<Array\<string\>\> | Yes| - | Callback used to return the geolocation permission status of all sources.|
| Name | Type | Mandatory | Default Value | Description |
| -------- | -------------------------------- | ---- | ---- | -------------------- |
| callback | AsyncCallback\<Array\<string\>\> | Yes | - | Callback used to return the geolocation permission status of all sources.|
**Return value**
| Type | Description |
| -------------------------- | ------------------------------------ |
| -------------------------- | -------------------------------- |
| Promise\<Array\<string\>\> | Promise used to return the geolocation permission status of all sources.|
**Example**
......@@ -4836,7 +4945,7 @@ Implements the **WebStorage** object, which can be used to manage the Web SQL an
### deleteAllData<sup>9+</sup>
static deleteAllData(): void
Deletes all data in the Web SQL database.
Deletes all data in the Web SQL Database.
**Example**
......@@ -4897,7 +5006,7 @@ Deletes all data in the specified origin.
### getOrigins<sup>9+</sup>
static getOrigins(callback: AsyncCallback\<Array\<WebStorageOrigin>>) : void
Obtains information about all origins that are currently using the Web SQL database. This API uses an asynchronous callback to return the result.
Obtains information about all origins that are currently using the Web SQL Database. This API uses an asynchronous callback to return the result.
**Parameters**
......@@ -4941,7 +5050,7 @@ Obtains information about all origins that are currently using the Web SQL datab
### getOrigins<sup>9+</sup>
static getOrigins() : Promise\<Array\<WebStorageOrigin>>
Obtains information about all origins that are currently using the Web SQL database. This API uses a promise to return the result.
Obtains information about all origins that are currently using the Web SQL Database. This API uses a promise to return the result.
**Return value**
......@@ -4985,7 +5094,7 @@ Obtains information about all origins that are currently using the Web SQL datab
### getOriginQuota<sup>9+</sup>
static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void
Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result.
Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result.
**Parameters**
......@@ -5026,7 +5135,7 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A
### getOriginQuota<sup>9+</sup>
static getOriginQuota(origin : string) : Promise\<number>
Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses a promise to return the result.
Obtains the storage quota of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result.
**Parameters**
......@@ -5072,7 +5181,7 @@ Obtains the storage quota of an origin in the Web SQL database, in bytes. This A
### getOriginUsage<sup>9+</sup>
static getOriginUsage(origin : string, callback : AsyncCallback\<number>) : void
Obtains the storage usage of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result.
Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses an asynchronous callback to return the result.
**Parameters**
......@@ -5113,7 +5222,7 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A
### getOriginUsage<sup>9+</sup>
static getOriginUsage(origin : string) : Promise\<number>
Obtains the storage usage of an origin in the Web SQL database, in bytes. This API uses a promise to return the result.
Obtains the storage usage of an origin in the Web SQL Database, in bytes. This API uses a promise to return the result.
**Parameters**
......@@ -5155,151 +5264,10 @@ Obtains the storage usage of an origin in the Web SQL database, in bytes. This A
}
}
```
### searchAllAsync<sup>9+</sup>
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](#onsearchresultreceive9).
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------------- |
| searchString | string | Yes | - | Search keyword.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
@State searchString: string = "xxx"
build() {
Column() {
Button('searchString')
.onClick(() => {
this.controller.searchAllAsync(this.searchString)
})
Button('clearMatches')
.onClick(() => {
this.controller.clearMatches()
})
Button('searchNext')
.onClick(() => {
this.controller.searchNext(true)
})
Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting)
})
}
}
}
```
### clearMatches<sup>9+</sup>
clearMatches(): void
Clears the matches found through [searchAllAsync](#searchallasync9).
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('clearMatches')
.onClick(() => {
this.controller.clearMatches()
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### searchNext<sup>9+</sup>
searchNext(forward: boolean): void
Searches for and highlights the next match.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------------- |
| forward | boolean | Yes | - | Whether to search forward.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Button('searchNext')
.onClick(() => {
this.controller.searchNext(true)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onSearchResultReceive<sup>9+</sup>
onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute
Invoked to notify the caller of the search result on the web page.
**Parameters**
| Name | Type | Description |
| ------------------ | ------------- | ----------------------------------- |
| activeMatchOrdinal | number | Sequence number of the current match, which starts from 0.|
| numberOfMatches | number | Total number of matches.|
| isDoneCounting | boolean | Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onSearchResultReceive(ret => {
console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal +
"[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting)
})
}
}
}
```
## WebStorageOrigin<sup>9+</sup>
Provides usage information about the Web SQL database.
Provides usage information about the Web SQL Database.
**Parameters**
......@@ -5365,6 +5333,7 @@ Enumerates the reasons why the rendering process exits.
| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.|
| Img | HTML::img tag. |
| Map | Geographical address. |
| Phone | Phone number. |
| Unknown | Unknown content. |
## SslError<sup>9+</sup>
......@@ -5372,7 +5341,7 @@ Enumerates the reasons why the rendering process exits.
Enumerates the error codes returned by **onSslErrorEventReceive** API.
| Name | Description |
| -------------- | ----------------- |
| ------------ | ----------- |
| Invalid | Minor error. |
| HostMismatch | The host name does not match. |
| DateInvalid | The certificate has an invalid date. |
......@@ -5381,7 +5350,7 @@ Enumerates the error codes returned by **onSslErrorEventReceive** API.
## ProtectedResourceType<sup>9+</sup>
| Name | Description | Remarks |
| --------- | -------------- | -------------- |
| --------- | ------------- | -------------------------- |
| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.|
## WebAsyncController
......@@ -5397,7 +5366,7 @@ webAsyncController: WebAsyncController = new WebAsyncController(webController);
### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\<string>): void
storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback<string>): void
Stores this web page. This API uses an asynchronous callback to return the result.
......@@ -5405,9 +5374,9 @@ Stores this web page. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null. |
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
| callback | AsyncCallback\<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
| baseName | string | Yes| Save path. The value cannot be null.|
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
| callback | AsyncCallback<string> | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example**
......@@ -5437,7 +5406,7 @@ Stores this web page. This API uses an asynchronous callback to return the resul
### storeWebArchive<sup>9+</sup>
storeWebArchive(baseName: string, autoName: boolean): Promise\<string>
storeWebArchive(baseName: string, autoName: boolean): Promise<string>
Stores this web page. This API uses a promise to return the result.
......@@ -5445,14 +5414,14 @@ Stores this web page. This API uses a promise to return the result.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| baseName | string | Yes| Save path. The value cannot be null. |
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
| baseName | string | Yes| Save path. The value cannot be null.|
| autoName | boolean | Yes| Whether to automatically generate a file name.<br>The value **false** means not to automatically generate a file name.<br>The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.|
**Return value**
| Type | Description |
| ---------------- | ------------------------------------------------------------ |
| Promise\<string> | Promise used to return the save path if the operation is successful and null otherwise. |
| --------------- | -------------------------------- |
| Promise<string> | Promise used to return the save path if the operation is successful and null otherwise.|
**Example**
......@@ -5483,7 +5452,7 @@ Stores this web page. This API uses a promise to return the result.
## WebMessagePort<sup>9+</sup>
Defines a **WebMessagePort** instance, which can be used to send and receive messages.
Implements a **WebMessagePort** instance, which can be used to send and receive messages.
### close<sup>9+</sup>
close(): void
......@@ -5498,7 +5467,7 @@ Sends messages. For the complete sample code, see [postMessage](#postmessage9).
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ------- | ------------------------------------ | ---- | ---- | ------- |
| message | [WebMessageEvent](#webmessageevent9) | Yes | - | Message to send.|
**Example**
......@@ -5533,7 +5502,7 @@ Registers a callback to receive messages from an HTML5 page. For the complete sa
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| -------- | -------- | ---- | ---- | ---------- |
| callback | function | Yes | - | Callback for receiving messages.|
**Example**
......@@ -5573,7 +5542,7 @@ Obtains the messages stored in this object.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| ------ | -------------- |
| string | Message stored in the object of this type.|
**Example**
......@@ -5605,7 +5574,7 @@ Sets the message in this object. For the complete sample code, see [postMessage]
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ---- | ------ | ---- | ---- | ------- |
| data | string | Yes | - | Message to send.|
**Example**
......@@ -5639,7 +5608,7 @@ Obtains the message port stored in this object.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| ---------------------------------------- | ---------------- |
| Array\<[WebMessagePort](#webmessageport9)\> | Message port stored in the object of this type.|
**Example**
......@@ -5673,7 +5642,7 @@ Sets the message port in this object. For the complete sample code, see [postMes
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| ----- | ---------------------------------------- | ---- | ---- | --------- |
| ports | Array\<[WebMessagePort](#webmessageport9)\> | Yes | - | Message port.|
**Example**
......
# Webview Error Codes
## 17100001 WebviewController Not Associated with a Web Component
**Error Message**
Init error. The WebviewController must be associated with a Web compoent.
**Description**
This error code is reported when the **WebviewController** object is not associated with any **\<Web>** component.
**Solution**
Bind the **WebviewController** object to a **\<Web>** component.
## 17100002 Invalid URL
**Error Message**
Invalid url.
**Description**
This error code is reported when the URL format is incorrect.
**Solution**
Verify the URL format.
## 17100003 Incorrect Resource Path
**Error Message**
Invalid resource path or file type.
**Description**
This error code is reported when the path to the resource file is incorrect.
**Possible Causes**
The resource file does not exist or cannot be accessed.
**Solution**
Make sure the path to the resource file is correct.
## 17100004 Function Not Enabled
**Error Message**
Function not enable.
**Description**
This error code is reported when the related function is not enabled.
**Solution**
Make sure the related function is enabled.
## 17100005 Invalid Cookie Value
**Error Message**
Invalid cookie value.
**Description**
This error code is reported when the cookie value type is invalid.
**Possible Causes**
The cookie value type is not supported.
**Solution**
Verify the cookie value type.
## 17100006 Message Port Callback Cannot Be Registered
**Error Message**
Can not register message event using this port.
**Description**
This error code is reported when a callback fails to be registered for the message port.
**Possible Causes**
The port is closed.
**Solution**
Make sure the port is open.
## 17100007 Invalid Forward or Backward Operation
**Error Message**
Invalid back or forward operation.
**Description**
This error code is reported when the specified forward or backward cannot be performed.
**Possible Causes**
1. The browsing history is cleared.
2. There is no browsing operation corresponding to the forward or backward operation.
**Solution**
1. Check whether **clearHistory** has been performed.
2. Check whether the number of pages specified by the forward or backward operation is available.
## 17100008 javaScriptProxy Does Not Exist
**Error Message**
Cannot delete JavaScriptProxy.
**Description**
This error code is reported when the **javaScriptProxy** object to delete does not exist.
**Possible Causes**
The target **javaScriptProxy** object is not yet registered.
**Solution**
Make sure the **javaScriptProxy** object is registered.
## 17100009 Zoom Operation Failure
**Error Message**
Cannot zoom in or zoom out.
**Description**
This error code is reported when the page cannot be zoomed in or out.
**Possible Causes**
The zoom ratio has reached its maximum or minimum.
**Solution**
Check whether the zoom ratio has reached its maximum or minimum.
## 17100010 Failure to Send Messages Through a Port
**Error Message**
Cannot post message using this port.
**Description**
This error code is reported when the current port cannot be used to send messages.
**Possible Causes**
The local or remote port is closed.
**Solution**
1. Make sure the local port is open.
2. Make sure an **onMessageEvent** callback is registered for the remote port.
## 17100011 Invalid Origin
**Error Message**
Invalid origin.
**Description**
This error code is reported when the input parameter **origin** is invalid.
**Possible Causes**
1. The **origin** parameter is empty.
2. The **origin** value is invalid.
**Solution**
Make sure the **origin** value is valid.
## 17100012 No Web Storage Origin
**Error Message**
Invalid web storage origin.
**Description**
This error code is reported when no web storage origin is available.
**Possible Causes**
The related JS database API is not used.
**Solution**
1. Check whether the JS database API is used.
2. If the JS database API is used, find out the failure cause, for example, check whether **databaseAccess** is enabled.
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册