提交 7015c61a 编写于 作者: E ester.zhou

update docs

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 b482f8a1
...@@ -556,7 +556,7 @@ Obtains all notification slots. This API uses an asynchronous callback to return ...@@ -556,7 +556,7 @@ Obtains all notification slots. This API uses an asynchronous callback to return
| Name | Readable| Writable| Type | Mandatory| Description | | Name | Readable| Writable| Type | Mandatory| Description |
| -------- | ---- | --- | --------------------------------- | ---- | -------------------- | | -------- | ---- | --- | --------------------------------- | ---- | -------------------- |
| callback | Yes | No | AsyncCallback\<[NotificationSlot](#notificationslot)\> | Yes | Callback used to return the result.| | callback | Yes | No | AsyncCallback\<Array\<[NotificationSlot](#notificationslot)\>\> | Yes | Callback used to return the result.|
**Example** **Example**
...@@ -3765,7 +3765,7 @@ Notification.subscribe(subscriber, subscribeCallback); ...@@ -3765,7 +3765,7 @@ Notification.subscribe(subscriber, subscribeCallback);
| desc | Yes | Yes | string | No | Notification slot description. | | desc | Yes | Yes | string | No | Notification slot description. |
| badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. | | badgeFlag | Yes | Yes | boolean | No | Whether to display the badge. |
| bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. | | bypassDnd | Yes | Yes | boolean | No | Whether to bypass the DND mode in the system. |
| lockscreenVisibility | Yes | Yes | boolean | No | Mode for displaying the notification on the lock screen. | | lockscreenVisibility | Yes | Yes | number | No | Mode for displaying the notification on the lock screen. |
| vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. | | vibrationEnabled | Yes | Yes | boolean | No | Whether vibration is supported for the notification. |
| sound | Yes | Yes | string | No | Notification alert tone. | | sound | Yes | Yes | string | No | Notification alert tone. |
| lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. | | lightEnabled | Yes | Yes | boolean | No | Whether the indicator blinks for the notification. |
......
# Pasteboard # Pasteboard
The **pasteboard** module provides the pasteboard management client and pasteboard server. The pasteboard management client manages pasteboard APIs. Specifically, it provides pasteboard APIs in JavaScript for applications, creates pasteboard data on the application framework side, and requests the pasteboard SA to create, delete, query, convert text, and configure pasteboards. The pasteboard server manages pasteboard events as well as the pasteboard SA lifecycle, providing support for the copy and paste functions of the system.
> **NOTE**<br>The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version. > **NOTE**
> >
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
## Modules to Import ## Modules to Import
...@@ -461,10 +463,10 @@ The pasteboard supports a maximum number of 128 data records. ...@@ -461,10 +463,10 @@ The pasteboard supports a maximum number of 128 data records.
**Example** **Example**
```js ```js
var pasteData = pasteboard.createPlainTextData("hello"); var pasteData = pasteboard.createPlainTextData("hello");
pasteData.addTextRecord("good"); pasteData.addTextRecord("good");
``` ```
### addHtmlRecord<sup>7+</sup> ### addHtmlRecord<sup>7+</sup>
...@@ -1037,13 +1039,13 @@ Checks whether the system pasteboard contains content. This API uses a promise t ...@@ -1037,13 +1039,13 @@ Checks whether the system pasteboard contains content. This API uses a promise t
**Example** **Example**
```js ```js
systemPasteboard.hasPasteData().then((data) => { systemPasteboard.hasPasteData().then((data) => {
console.info('Operation succeeded. ' + JSON.stringify(data)); console.info('success hasPasteData : ' + JSON.stringify(data));
}).catch((error) => { }).catch((error) => {
console.error('failed to hasPasteData because ' + JSON.stringify(error)); console.error('failed to hasPasteData because ' + JSON.stringify(error));
}); });
``` ```
### clear<sup>7+</sup> ### clear<sup>7+</sup>
......
# Wallpaper # Wallpaper
The **wallpaper** module is part of the theme framework and provides the system-level wallpaper management service in OpenHarmony. You can use the APIs of this module to show, set, and switch between wallpapers.
> **NOTE** > **NOTE**
> >
......
...@@ -49,7 +49,9 @@ RichText\(content:string\) ...@@ -49,7 +49,9 @@ RichText\(content:string\)
## Example ## Example
``` You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct RichTextExample { struct RichTextExample {
......
# Web # Web
> **NOTE**<br> > **NOTE**
>This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. >
> - 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. The **<Web\>** component can be used to display web pages.
## Required Permissions ## Required Permissions
ohos.permission.INTERNET, required only for accessing online web pages. ohos.permission.INTERNET, required only for accessing online web pages
## Child Components ## Child Components
...@@ -14,200 +16,1700 @@ Not supported ...@@ -14,200 +16,1700 @@ Not supported
## APIs ## APIs
- Web\(options: { src: string, controller?: WebController }\) Web(options: { src: string, controller?: WebController })
Table 1 options **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ---------- | ------------------------------- | ---- | ---- | ------- |
| ---------- | ------------------------------- | ---- | ---- | ------- | | src | string | Yes | - | Address of a web page resource.|
| src | string | Yes | - | Address of a web page resource.| | controller | [WebController](#webcontroller) | No | - | Controller. |
| controller | [WebController](#webcontroller) | No | - | Controller. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
}
}
}
```
> **NOTE**<br> > **NOTE**<br>
> >
> - Transition animation is not supported. > Transition animation is not supported.
> - Multi-instance is not supported.
> - Only local audio and video are supported for playback.
## Attributes ## Attributes
| Name | Type | Default Value | Description |
| ------------------ | ---------------------------------------- | ----------------- | ---------------------------------------- | The **\<Web>** component has network attributes.
| domStorageAccess | boolean | false | Whether to enable the DOM Storage API permission. By default, the permission is disabled.|
| fileAccess | boolean | false | Whether to enable in-application rawfile access through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md). By default, this feature is enabled. | ### domStorageAccess
| fileFromUrlAccess | boolean | true | Whether to allow JavaScript scripts on web pages to access the content in [$rawfile(filepath/filename)](../../ui/ts-resource-access.md). By default, this feature is disabled. |
| imageAccess | boolean | true | Whether to enable automatic image loading. By default, this feature is enabled. | domStorageAccess(domStorageAccess: boolean)
| javaScriptProxy | { <br> object: object, <br> name: string, <br> methodList: Array\<string\>, <br> controller: WebController <br>} | - | JavaScript object to be injected into the window. Methods of this object can be invoked in the window. The parameters in this attribute cannot be updated.<br> **object** indicates the object to be registered. Methods can be declared, but not attributes. The parameters and return value can only be of the string, number, or Boolean type.<br> **name** indicates the 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.<br> **methodList** indicates the methods of the JavaScript object to be registered at the application side.<br> **controller** indicates the controller.|
| javaScriptAccess | boolean | true | Whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed. | Sets whether to enable the DOM Storage API. By default, this feature is disabled.
| mixedMode | [MixedMode](#mixedmode) | MixedMode.None | Whether to enable loading of HTTP and HTTPS hybrid content can be loaded. By default, this feature is disabled.|
| onlineImageAccess | boolean | true | Whether to enable access to online images through HTTP and HTTPS. By default, this feature is enabled.| **Parameters**
| zoomAccess | boolean | true | Whether to enable zoom gestures. By default, zoom gestures are enabled. | | Name | Type | Mandatory | Default Value | Description |
| overviewModeAccess | boolean | true | Whether to use the overview mode to load web pages. By default, this mode is used. | | ---------------- | ------- | ---- | ---- | ------------------------------------ |
| databaseAccess | boolean | false | Whether to enable database access. By default, this feature is disabled. | | domStorageAccess | boolean | Yes | false | Whether to enable the DOM Storage API.|
| cacheMode | [CacheMode](#cachemode) | CacheMode.Default | Cache mode. |
| textZoomAtio | number | 100 | Text zoom ratio of the page. The default value is **100**, which indicates 100%. | **Example**
| userAgent | string | - | User agent. | ```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.domStorageAccess(true)
}
}
}
```
### fileAccess
fileAccess(fileAccess: boolean)
Sets whether to enable the access to the file system in the application. By default, this feature is disabled. Access to the files specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------- | ---- | ---- | ---------------------------------------- |
| fileAccess | boolean | Yes | true | Whether to enable the access to the file system in the application. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.fileAccess(true)
}
}
}
```
### 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 specified through [$rawfile(filepath/filename)](../../ui/ts-resource-access.md) are not affected by this attribute.
**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. |
**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)
Sets whether to enable automatic image loading. By default, this feature is enabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------- | ------- | ---- | ---- | --------------- |
| imageAccess | boolean | Yes | true | Whether to enable automatic image loading. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.imageAccess(true)
}
}
}
```
### javaScriptProxy
javaScriptProxy(javaScriptProxy: { object: object, name: string, methodList: Array\<string\>,
controller: WebController })
Injects a JavaScript object into the window. Methods of this object can 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 not attributes. |
| 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. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
testObj = {
test: (data1, data2, data3) => {
console.log("data1:" + data1);
console.log("data2:" + data2);
console.log("data3:" + data3);
return "AceString";
},
toString: () => {
console.log('toString' + "interface instead.");
}
}
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.javaScriptAccess(true)
.javaScriptProxy({
object: this.testObj,
name: "objName",
methodList: ["test", "toString"],
controller: this.controller,
})
}
}
}
```
### javaScriptAccess
javaScriptAccess(javaScriptAccess: boolean)
Sets whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------------- | ------- | ---- | ---- | ------------------- |
| javaScriptAccess | boolean | Yes | true | Whether JavaScript scripts can be executed.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.javaScriptAccess(true)
}
}
}
```
### mixedMode
mixedMode(mixedMode: MixedMode)
Sets whether to enable loading of HTTP and HTTPS hybrid content can be loaded. By default, this feature is disabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | --------------------------- | ---- | ---- | --------- |
| mixedMode | [MixedMode](#mixedmode)| Yes | - | Mixed content to load.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
@State mode:MixedMode = MixedMode.All;
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.mixedMode(this.mode)
}
}
}
```
### onlineImageAccess
onlineImageAccess(onlineImageAccess: boolean)
Sets whether to enable access to online images through HTTP and HTTPS. By default, this feature is enabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----------------- | ------- | ---- | ---- | ---------------- |
| onlineImageAccess | boolean | Yes | true | Whether to enable access to online images through HTTP and HTTPS.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.onlineImageAccess(true)
}
}
}
```
### zoomAccess
zoomAccess(zoomAccess: boolean)
Sets whether to enable zoom gestures. By default, this feature is enabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | ------- | ---- | ---- | ------------- |
| zoomAccess | boolean | Yes | true | Whether to enable zoom gestures.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.zoomAccess(true)
}
}
}
```
### overviewModeAccess
overviewModeAccess(overviewModeAccess: boolean)
Sets whether to load web pages by using the overview mode. By default, this feature is enabled.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------------ | ------- | ---- | ---- | --------------- |
| overviewModeAccess | boolean | Yes | true | Whether to load web pages by using the overview mode|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.overviewModeAccess(true)
}
}
}
```
### databaseAccess
databaseAccess(databaseAccess: boolean)
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**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.databaseAccess(true)
}
}
}
```
### geolocationAccess
geolocationAccess(geolocationAccess: boolean)
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**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.geolocationAccess(true)
}
}
}
```
### cacheMode
cacheMode(cacheMode: CacheMode)
Sets the cache mode.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | --------------------------- | ---- | ---- | --------- |
| cacheMode | [CacheMode](#cachemode)| Yes | CacheMode.Default | Cache mode to set.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
@State mode:CacheMode = CacheMode.None;
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.cacheMode(this.mode)
}
}
}
```
### textZoomRatio
textZoomRatio(textZoomRatio: number)
Sets the text zoom ratio of the page. The default value is **100**, which indicates 100%.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------------ | ------ | ---- | ---- | --------------- |
| textZoomRatio | number | Yes | 100 | Text zoom ratio to set.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
@State atio:number = 150;
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.textZoomRatio(this.atio)
}
}
}
```
### userAgent
userAgent(userAgent: string)
Sets the user agent.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| --------- | ------ | ---- | ---- | --------- |
| userAgent | string | Yes | - | User agent to set.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
@State userAgent:string = 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36';
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.userAgent(this.userAgent)
}
}
}
```
> **NOTE**<br> > **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). > 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 ## Events
The universal events are not supported. The universal events are not supported.
| Name | Description | ### onAlert
| ---------------------------------------- | ---------------------------------------- |
| onAlert(callback: (event?: { url: string; message: string; result: [JsResult](#jsresult) }) => boolean) | <p>Triggered when **alert()** is invoked to display an alert dialog box on the web page.<br>If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows only the confirm operation) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.<br>**url**: URL of the web page where the dialog box is displayed.<br>**message**: information displayed in the dialog box.<br>**JsResult**: the user's operation.</p> | onAlert(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
| onBeforeUnload(callback: (event?: { url: string; message: string; result: [JsResult](#jsresult) }) => boolean) | <p>Triggered when the current page is about to exit after the user refreshes or closes the page.<br>If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.<br>**url**: URL of the web page where the dialog box is displayed.<br>**message**: information displayed in the dialog box.<br>**JsResult**: the user's operation.</p> |
| onConfirm(callback: (event?: { url: string; message: string; result: [JsResult](#jsresult) }) => boolean) | <p>Triggered when **confirm()** is invoked by the web page.<br>If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.<br>**url**: URL of the web page where the dialog box is displayed.<br>**message**: information displayed in the dialog box.<br>**JsResult**: the user's operation.</p> | Triggered when **alert()** is invoked to display an alert dialog box on the web page.
| onPrompt<sup>9+</sup>(callback: (event?: { url: string; message: string; value: string; result: [JsResult](#jsresult) }) => boolean) | <p>Triggered when **prompt()** is invoked by the web page.<br>If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.<br>**url**: URL of the web page where the dialog box is displayed.<br>**message**: information displayed in the dialog box.<br>**value**: default value in the dialog box.<br>**JsResult**: the user's operation and dialog box content.</p> |
| onConsole(callback: (event?: { message: [ConsoleMessage](#consolemessage) }) => boolean) | <p>Triggered when the host application is notified of a JavaScript console message.<br>**message**: console message.</p> | **Parameters**
| onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) | <p>Triggered when a download task starts on the web page.<br>**url**: URL for the download task.<br>**userAgent**: name of the user agent (UA) for the download task.<br>**contentDisposition**: Content-Disposition response header returned by the server, which may be empty.<br>**mimetype**: content media type (MIME) returned by the server.<br>**contentLength**: length of the file returned by the server.</p> | | Name | Type | Description |
| onErrorReceive(callback: (event?: { request: [WebResourceRequest](#webresourceerror), error: [WebResourceError](#webresourceerror) }) => void) | <p>Triggered when an error occurs during web page loading.<br>For better results, simplify the implementation logic in the callback.<br>**request**: encapsulation of a web page request.<br>**error**: encapsulation of a web page resource loading error.</p> | | ------- | --------------------- | --------------- |
| onHttpErrorReceive(callback: (event?: { request: [WebResourceRequest](#webresourceerror), response: [WebResourceResponse](#webresourceresponse) }) => void) | <p>Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading.<br>**request**: encapsulation of a web page request.<br>**response**: encapsulation of a web page response.</p>| | url | string | URL of the web page where the dialog box is displayed.|
| onPageBegin(callback: (event?: { url: string }) => void) | <p>Triggered when the web page starts to be loaded. This API is triggered only for the main frame content, and not for the iframe or frameset content.<br>**url**: URL of the page.</p> | | message | string | Message displayed in the dialog box. |
| onPageEnd(callback: (event?: { url: string }) => void) | <p>Triggered when the web page loading is complete. This API is triggered only for the main frame content.<br>**url**: URL of the page.</p> | | result | [JsResult](#jsresult) | The user's operation. |
| onProgressChange(callback: (event?: { newProgress: number }) => void) | <p>Triggered when the web page loading progress changes.<br>**newProgress**: new loading progress. The value is an integer ranging from 0 to 100.</p> |
| onTitleReceive(callback: (event?: { title: string }) => void) | <p>Triggered when the document title of the web page is changed.<br>**title**: document title.</p> | **Return value**
| onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void) | <p>Triggered when loading of the web page is complete. This callback function is used by an application to update the historical link it accessed.<br>**url**: URL to be accessed.<br>**isRefreshed**: whether the page is reloaded. The value **true** means that the page is reloaded, and **false** means that the page is newly loaded.</p> | | Type | Description |
| onRenderExited(callback: (event?: { renderExitReason: [RenderExitReason](#renderexitreason) }) => void) | <p>Triggered when the rendering process exits abnormally.<br>**renderExitReason**: cause for the abnormal exit of the rendering process.</p> | | ------- | ---------------------------------------- |
| onShowFileSelector(callback: (event?: { result: [FileSelectorResult](#fileselectorresult), fileSelector: [FileSelectorParam](#fileselectorparam) }) => void) | <p>Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button.<br>**result**: file selection result to be sent to the web component.<br>**fileSelector**: information about the file selector.</p> | | boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
| onUrlLoadIntercept(callback: (event?: { data:string \| [WebResourceRequest](#webresourcerequest) }) => boolean) | <p>Triggered before the **\<Web>** component loads the URL to determine whether to block the access. The callback returns **true** if the access is blocked, and **false** otherwise.<br>**data**: URL information.</p> |
**Example**
### ConsoleMessage ```ts
// xxx.ets
- APIs @Entry
@Component
| Name | Description | struct WebComponent {
| ------------------------------- | ---------------------- | controller:WebController = new WebController();
| getLineNumber(): number | Obtains the number of rows in the **ConsoleMessage**. | build() {
| getMessage(): string | Obtains the log information of the **ConsoleMessage**.| Column() {
| getMessageLevel(): MessageLevel | Obtains the log information level of the **ConsoleMessage**.| Web({ src:'www.example.com', controller:this.controller })
| getSourceId(): string | Obtains the path and name of the web page source file. | .onAlert((event) => {
AlertDialog.show({
- MessageLevel enums title: 'title',
message: 'text',
| Name | Description | confirm: {
| ----- | :---- | value: 'onAlert',
| Debug | Debug level.| action: () => {
| Error | Error level.| event.result.handleConfirm()
| Info | Information level.| }
| Log | Log level.| },
| Warn | Warning level. | cancel: () => {
event.result.handleCancel()
### JsResult }
})
Provides the result returned to the **\<Web>** component to indicate the user operation performed in the dialog box. return true;
})
- APIs }
}
| Name | Description | }
| --------------------- | ----------------------- | ```
| handleCancel(): void | <p>The user's cancel operation in the dialog box.</p> |
| handleConfirm(): void | <p>The user's confirm operation in the dialog box.</p> | ### onBeforeUnload
| handlePromptConfirm<sup>9+</sup>(result: string): void | <p>The user's confirm operation in the dialog box as well as the dialog box content.</p>|
onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
### WebResourceError
Triggered when the current page is about to exit after the user refreshes or closes the page.
- APIs
**Parameters**
| Name | Description | | Name | Type | Description |
| ---------------------- | ------------ | | ------- | --------------------- | --------------- |
| getErrorCode(): number | Obtains the error code for resource loading. | | url | string | URL of the web page where the dialog box is displayed.|
| getErrorInfo(): string | Obtains error information about resource loading.| | message | string | Message displayed in the dialog box. |
| result | [JsResult](#jsresult) | The user's operation. |
### WebResourceRequest
**Return value**
- APIs | Type | Description |
| ------- | ---------------------------------------- |
| Name | Description | | boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
| ---------------------------------------- | -------------------- |
| getRequestHeader(): Array\<[Header](#header)\> | Obtains the information about the resource request header. | **Example**
| getRequestUrl(): string | Obtains the URL of the resource request. | ```ts
| isMainFrame(): boolean | Checks whether the resource request is in the main frame. | // xxx.ets
| isRedirect(): boolean | Checks whether the resource request is redirected by the server. | @Entry
| isRequestGesture(): boolean | Checks whether the resource request is associated with a gesture (for example, a tap).| @Component
struct WebComponent {
### Header controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onBeforeUnload((event) => {
console.log("event.url:" + event.url);
console.log("event.message:" + event.message);
console.log("event.result:" + event.result);
return false;
})
}
}
}
```
### onConfirm
onConfirm(callback: (event?: { url: string; message: string; result: JsResult }) => boolean)
Triggered when **confirm()** is invoked by the web page.
**Parameters**
| Name | Type | Description |
| ------- | --------------------- | --------------- |
| url | string | URL of the web page where the dialog box is displayed.|
| message | string | Message displayed in the dialog box. |
| result | [JsResult](#jsresult) | The user's operation. |
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onConfirm((event) => {
console.log("event.url:" + event.url);
console.log("event.message:" + event.message);
console.log("event.result:" + event.result);
AlertDialog.show({
title: 'title',
message: 'text',
confirm: {
value: 'onConfirm',
action: () => {
event.result.handleConfirm()
}
},
cancel: () => {
event.result.handleCancel()
}
})
return true;
})
}
}
}
```
### onPrompt<sup>9+</sup>
onPrompt(callback: (event?: { url: string; message: string; value: string; result: JsResult }) => boolean)
**Parameters**
| Name | Type | Description |
| ------- | --------------------- | --------------- |
| url | string | URL of the web page where the dialog box is displayed.|
| message | string | Message displayed in the dialog box. |
| result | [JsResult](#jsresult) | The user's operation. |
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | If the callback returns **false**, the default dialog box is displayed. If the callback returns **true**, a system application can use the system dialog box (allows the confirm and cancel operations) and invoke the **JsResult** API to notify the **\<Web>** component of the user's operation.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.onPrompt((event) => {
console.log("url:" + event.url);
console.log("message:" + event.message);
console.log("value:" + event.value);
console.log("result:" + event.result);
return true;
})
}
}
```
### onConsole
onConsole(callback: (event?: { message: ConsoleMessage }) => boolean)
Triggered to notify the host application of a JavaScript console message.
**Parameters**
| Name | Type | Description |
| ------- | --------------------------------- | --------- |
| message | [ConsoleMessage](#consolemessage) | Console message.|
**Return value**
| Type | Description |
| ------- | ----------------------------------- |
| boolean | Returns **true** if the message will not be printed to the console; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onConsole((event) => {
console.log('getMessage:' + event.message.getMessage());
console.log('getSourceId:' + event.message.getSourceId());
console.log('getLineNumber:' + event.message.getLineNumber());
console.log('getMessageLevel:' + event.message.getMessageLevel());
return false;
})
}
}
}
```
### onDownloadStart
onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void)
**Parameters**
| Name | Type | Description |
| ------------------ | ------------- | ----------------------------------- |
| url | string | URL for the download task. |
| contentDisposition | string | Content-Disposition response header returned by the server, which may be empty.|
| mimetype | string | MIME type of the content returned by the server. |
| contentLength | contentLength | Length of the content returned by the server. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onDownloadStart((event) => {
console.log('url:' + event.url);
console.log('userAgent:' + event.userAgent);
console.log('contentDisposition:' + event.contentDisposition);
console.log('contentLength:' + event.contentLength);
console.log('mimetype:' + event.mimetype);
})
}
}
}
```
### onErrorReceive
onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void)
Triggered when an error occurs during web page loading. For better results, simplify the implementation logic in the callback.
**Parameters**
| Name | Type | Description |
| ------- | ---------------------------------------- | --------------- |
| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. |
| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onErrorReceive((event) => {
console.log('getErrorInfo:' + event.error.getErrorInfo());
console.log('getErrorCode:' + event.error.getErrorCode());
console.log('url:' + event.request.getRequestUrl());
console.log('isMainFrame:' + event.request.isMainFrame());
console.log('isRedirect:' + event.request.isRedirect());
console.log('isRequestGesture:' + event.request.isRequestGesture());
console.log('getRequestHeader_headerKey:' + event.request.getRequestHeader().toString());
let result = event.request.getRequestHeader();
console.log('The request header result size is ' + result.length);
for (let i of result) {
console.log('The request header key is : ' + i.headerKey + ', value is : ' + i.headerValue);
}
})
}
}
}
```
### onHttpErrorReceive
onHttpErrorReceive(callback: (event?: { request: WebResourceRequest, response: WebResourceResponse }) => void)
Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading.
**Parameters**
| Name | Type | Description |
| ------- | ---------------------------------------- | --------------- |
| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. |
| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onHttpErrorReceive((event) => {
console.log('url:' + event.request.getRequestUrl());
console.log('isMainFrame:' + event.request.isMainFrame());
console.log('isRedirect:' + event.request.isRedirect());
console.log('isRequestGesture:' + event.request.isRequestGesture());
console.log('getResponseData:' + event.response.getResponseData());
console.log('getResponseEncoding:' + event.response.getResponseEncoding());
console.log('getResponseMimeType:' + event.response.getResponseMimeType());
console.log('getResponseCode:' + event.response.getResponseCode());
console.log('getReasonMessage:' + event.response.getReasonMessage());
let result = event.request.getRequestHeader();
console.log('The request header result size is ' + result.length);
for (let i of result) {
console.log('The request header key is : ' + i.headerKey + ' , value is : ' + i.headerValue);
}
let resph = event.response.getResponseHeader();
console.log('The response header result size is ' + resph.length);
for (let i of resph) {
console.log('The response header key is : ' + i.headerKey + ' , value is : ' + i.headerValue);
}
})
}
}
}
```
### onPageBegin
onPageBegin(callback: (event?: { url: string }) => void)
Triggered when the web page starts to be loaded. This API is triggered only for the main frame content, and not for the iframe or frameset content.
**Parameters**
| Name | Type | Description |
| ---- | ------ | --------- |
| url | string | URL of the page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onPageBegin((event) => {
console.log('url:' + event.url);
})
}
}
}
```
### onPageEnd
onPageEnd(callback: (event?: { url: string }) => void)
Triggered when the web page loading is complete. This API is triggered only for the main frame content.
**Parameters**
| Name | Type | Description |
| ---- | ------ | --------- |
| url | string | URL of the page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onPageEnd((event) => {
console.log('url:' + event.url);
})
}
}
}
```
### onProgressChange
onProgressChange(callback: (event?: { newProgress: number }) => void)
Triggered when the web page loading progress changes.
**Parameters**
| Name | Type | Description |
| ----------- | ------ | --------------------- |
| newProgress | number | New loading progress. The value is an integer ranging from 0 to 100.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onProgressChange((event) => {
console.log('newProgress:' + event.newProgress)
})
}
}
}
```
### onTitleReceive
onTitleReceive(callback: (event?: { title: string }) => void)
Triggered when the document title of the web page is changed.
**Parameters**
| Name | Type | Description |
| ----- | ------ | ------------- |
| title | string | Document title.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onTitleReceive((event) => {
console.log('title:' + event.title)
})
}
}
}
```
### onRefreshAccessedHistory
onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void)
Triggered when loading of the web page is complete. This API is used by an application to update the historical link it accessed.
**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, and **false** means that the page is newly loaded.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onRefreshAccessedHistory((event) => {
console.log('url:' + event.url + ' isReload:' + event.refreshed);
})
}
}
}
```
### onRenderExited
onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void)
Triggered when the rendering process exits abnormally.
**Parameters**
| Name | Type | Description |
| ---------------- | ---------------------------------------- | ---------------- |
| renderExitReason | [RenderExitReason](#renderexitreason)| Cause for the abnormal exit of the rendering process.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'chrome://crash/', controller: this.controller })
.onRenderExited((event) => {
console.log('reason:' + event.renderExitReason);
})
}
}
}
```
### onShowFileSelector<sup>9+</sup>
onShowFileSelector(callback: (event?: { result: FileSelectorResult, fileSelector: FileSelectorParam }) => void)
Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button.
**Parameters**
| Name | Type | Description |
| ------------ | ---------------------------------------- | ----------------- |
| result | [FileSelectorResult](#fileselectorresult9) | File selection result to be sent to the **\<Web>** component.|
| fileSelector | [FileSelectorParam](#fileselectorparam9) | Information about the file selector. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onShowFileSelector((event) => {
AlertDialog.show({
title: event.fileSelector.getTitle(),
message: 'isCapture:' + event.fileSelector.isCapture() + " mode:" + event.fileSelector.getMode() + 'acceptType:' + event.fileSelector.getAcceptType(),
confirm: {
value: 'upload',
action: () => {
let fileList: Array<string> = [
'/data/storage/el2/base/test',
]
event.result.handleFileList(fileList)
}
},
cancel: () => {
let fileList: Array<string> = []
event.result.handleFileList(fileList)
}
})
return true;
})
}
}
}
```
### onUrlLoadIntercept
onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean)
Triggered when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access.
**Parameters**
| Name | Type | Description |
| ---- | ---------------------------------------- | --------- |
| data | string / [WebResourceRequest](#webresourcerequest) | URL information.|
**Return value**
| Type | Description |
| ------- | ------------------------ |
| boolean | Returns **true** if the access is blocked; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.onUrlLoadIntercept((event) => {
console.log('onUrlLoadIntercept ' + event.data.toString())
return true;
})
}
}
}
```
### onInterceptRequest<sup>9+</sup>
onInterceptRequest9+(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse)
Triggered when the **\<Web>** component is about to access a URL. This API is used to block the URL and return the response data.
**Parameters**
| Name | Type | Description |
| ------- | ---------------------------------------- | ----------- |
| request | [WebResourceRequest](#webresourcerequest) | Information about the URL request.|
**Return value**
| Type | Description |
| ---------------------------------------- | --------------------------- |
| [WebResourceResponse](#webresourceresponse) | Returns null if the original loading mode is used; returns the response data otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
responseweb: WebResourceResponse = new WebResourceResponse();
heads:Header[] = new Array();
@State webdata: string = "<!DOCTYPE html>\n" +
"<html>\n"+
"<head>\n"+
"<title>intercept test</title>\n"+
"</head>\n"+
"<body>\n"+
"<h1>intercept test</h1>\n"+
"</body>\n"+
"</html>"
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.onInterceptRequest((event) => {
console.log('url:' + event.request.getRequestUrl());
var head1:Header = {
headerKey:"Connection",
headerValue:"keep-alive"
}
var head2:Header = {
headerKey:"Cache-Control",
headerValue:"no-cache"
}
var length = this.heads.push(head1);
length = this.heads.push(head2);
this.responseweb.setResponseHeader(this.heads);
this.responseweb.setResponseData(this.webdata);
this.responseweb.setResponseEncoding('utf-8');
this.responseweb.setResponseMimeType('text/html');
this.responseweb.setResponseCode(200);
this.responseweb.setReasonMessage('OK');
return this.responseweb;
})
}
}
}
```
### onHttpAuthRequest<sup>9+</sup>
onHttpAuthRequest(callback: (event?: { handler: HttpAuthHandler, host: string, realm: string}) => boolean)
Triggered when an HTTP authentication request is received.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. |
| host | string | Host to which HTTP authentication credentials apply.|
| realm | string | Realm to which HTTP authentication credentials apply. |
**Return value**
| Type | Description |
| ------- | --------------------- |
| boolean | Returns **true** if the authentication is successful; returns **false** otherwise. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
httpAuth:boolean = false;
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.onHttpAuthRequest((event) => {
AlertDialog.show({
title: 'title',
message: 'text',
confirm: {
value: 'onConfirm',
action: () => {
this.httpAuth = event.handler.isHttpAuthInfoSaved();
if (this.httpAuth == false) {
web.WebDataBase.saveHttpAuthCredentials(
event.host,
event.realm,
"2222",
"2222"
)
event.handler.cancel();
}
}
},
cancel: () => {
event.handler.cancel();
}
})
return true;
})
}
}
```
### onPermissionRequest<sup>9+</sup>
onPermissionRequest(callback: (event?: { request: PermissionRequest }) => void)
Invoked when a permission request is received.
**Parameters**
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
| request | [PermissionRequest](#permissionrequest9) | The user's operation. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Web({ src:'www.example.com', controller:this.controller })
.onPermissionRequest((event) => {
AlertDialog.show({
title: 'title',
message: 'text',
confirm: {
value: 'onConfirm',
action: () => {
event.request.grant(event.request.getAccessibleResource());
}
},
cancel: () => {
event.request.deny();
}
})
})
}
}
```
## ConsoleMessage
Implements the **ConsoleMessage** object. For details about the sample code, see [onConsole](#onconsole).
### getLineNumber
getLineNumber(): number
Obtains the number of rows in this console message.
**Return value**
| Type | Description |
| ------ | -------------------- |
| number | Number of rows in the console message.|
### getMessage
getMessage(): string
Obtains the log information of this console message.
**Return value**
| Type | Description |
| ------ | ---------------------- |
| string | Log information about this console message.|
### getMessageLevel
getMessageLevel(): MessageLevel
Obtains the level of this console message.
**Return value**
| Type | Description |
| --------------------------------- | ---------------------- |
| [MessageLevel](#messagelevel)| Level of the console message.|
### getSourceId
getSourceId(): string
Obtains the path and name of the web page source file.
**Return value**
| Type | Description |
| ------ | ------------- |
| string | Path and name of the web page source file.|
## JsResult
Implements the **JsResult** object, which indicates the result returned to the **\<Web>** component to indicate the user operation performed in the dialog box. For details about the sample code, see [onAlert Event](#onalert).
### handleCancel
handleCancel(): void
Notifies the **\<Web>** component of the user's cancel operation in the dialog box.
### handleConfirm
handleConfirm(): void
Notifies the **\<Web>** component of the user's confirm operation in the dialog box.
### handlePromptConfirm<sup>9+</sup>
handlePromptConfirm(result: string): void
Notifies the **\<Web>** component of the user's confirm operation in the dialog box as well as the dialog box content.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | ----------- |
| result | string | Yes | - | User input in the dialog box.|
## WebResourceError
Implements the **WebResourceError** object. For details about the sample code, see [onErrorReceive](#onerrorreceive).
### getErrorCode
getErrorCode(): number
Obtains the error code for resource loading.
**Return value**
| Type | Description |
| ------ | ----------- |
| number | Error code for resource loading.|
### getErrorInfo
getErrorInfo(): string
Obtains error information about resource loading.
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Error information about resource loading.|
## WebResourceRequest
Implements the **WebResourceRequest** object. For details about the sample code, see [onErrorReceive](#onerrorreceive).
### getRequestHeader
getResponseHeader() : Array\<Header\>
Obtains the information about the resource request header.
**Return value**
| Type | Description |
| -------------------------- | ---------- |
| Array\<[Header](#header)\> | Information about the resource request header.|
### getRequestUrl
getRequestUrl(): string
Obtains the URL of the resource request.
**Return value**
| Type | Description |
| ------ | ------------- |
| string | URL of the resource request.|
### isMainFrame
isMainFrame(): boolean
Checks whether the resource request is in the main frame.
**Return value**
| Type | Description |
| ------- | ---------------- |
| boolean | Whether the resource request is in the main frame.|
### isRedirect
isRedirect(): boolean
Checks whether the resource request is redirected by the server.
**Return value**
| Type | Description |
| ------- | ---------------- |
| boolean | Whether the resource request is redirected by the server. |
### isRequestGesture
isRequestGesture(): boolean
Checks whether the resource request is associated with a gesture (for example, a tap).
**Return value**
| Type | Description |
| ------- | -------------------- |
| boolean | Whether the resource request is associated with a gesture (for example, a tap). |
## Header
Describes the request/response header returned by the **\<Web>** component. Describes the request/response header returned by the **\<Web>** component.
- Parameters | Name | Type | Description |
| ----------- | ------ | ------------- |
| headerKey | string | Key of the request/response header. |
| headerValue | string | Value of the request/response header.|
| Name | Type | Description |
| ----------- | ------ | ------------- |
| headerKey | string | Key of the request/response header. |
| headerValue | string | Value of the request/response header.|
## WebResourceResponse
### WebResourceResponse Implements the **WebResourceResponse** object. For details about the sample code, see [onHttpErrorReceive](#onhttperrorreceive).
- APIs ### getReasonMessage
| Name | Description | getReasonMessage(): string
| ---------------------------------------- | ------------------ |
| getReasonMessage(): string | Obtains the status code description of the resource response. |
| getResponseCode(): number | Obtains the status code of the resource response. |
| getResponseData(): string | Obtains the data in the resource response. |
| getResponseEncoding(): string | Obtains the encoding of the resource response. |
| getResponseHeader(): Array\<[Header](#header)\> | Obtains the resource response header. |
| getResponseMimeType(): string | Obtains the media (MIME) type of the resource response.|
### RenderExitReason Obtains the status code description of the resource response.
Explains why the rendering process exits. **Return value**
| Type | Description |
| ------ | ------------- |
| string | Status code description of the resource response.|
| Name | Description | ### getResponseCode
| -------------------------- | ----------------- |
| ProcessAbnormalTermination | The rendering process exits abnormally. |
| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.|
| ProcessCrashed | The rendering process crashes due to a segmentation error or other errors. |
| ProcessOom | The program memory is running low. |
| ProcessExitUnknown | Other reason. |
### MixedMode getResponseCode(): number
| Name | Description | Obtains the status code of the resource response.
| ---------- | ---------------------------------- |
| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.|
| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. |
| None | HTTP and HTTPS hybrid content cannot be loaded. |
### CacheMode **Return value**
| Name | Description | | Type | Description |
| ------- | ------------------------------------ | | ------ | ----------- |
| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.| | number | Status code of the resource response.|
| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. |
| Online | The cache is not used to load the resources. All resources are obtained from the Internet. |
| Only | The cache alone is used to load the resources. |
### FileSelectorResult ### getResponseData
Notifies the **\<Web>** component of the file selection result.
- APIs getResponseData(): string
| Name | Description | Obtains the data in the resource response.
| ---------------------------------------------- | ------------------------------------------------------------ |
| handleFileList(fileList: Array\<string>): void | Instructs the **\<Web>** component to select a file.<br>**fileList**: list of files to operate. |
### FileSelectorParam **Return value**
- APIs | Type | Description |
| ------ | --------- |
| string | Data in the resource response.|
| Name | Description | ### getResponseEncoding
| -------------------------------- | ------------ |
| getTitle(): string | Obtains the title of the file selector. |
| getMode(): FileSelectorMode | Obtains the mode of the file selector. |
| getAcceptType(): Array\<string\> | Obtains the file filtering type. |
| isCapture(): boolean | Checks whether multimedia capabilities are invoked.|
### FileSelectorMode getResponseEncoding(): string
| Name | Description |
| -------------------- | ---------- | Obtains the encoding string of the resource response.
| FileOpenMode | Open and upload a file. |
| FileOpenMultipleMode | Open and upload multiple files. | **Return value**
| FileOpenFolderMode | Open and upload a folder.| | Type | Description |
| FileSaveMode | Save a file. | | ------ | ---------- |
| string | Encoding string of the resource response.|
### getResponseHeader
getResponseHeader() : Array\<Header\>
Obtains the resource response header.
**Return value**
| Type | Description |
| -------------------------- | -------- |
| Array\<[Header](#header)\> | Resource response header.|
### getResponseMimeType
getResponseMimeType(): string
Obtains the MIME type of the resource response.
**Return value**
| Type | Description |
| ------ | ------------------ |
| string | MIME type of the resource response.|
### setResponseData<sup>9+</sup>
setResponseData(data: string)
Sets the data in the resource response.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| data | string | Yes | - | Resource response data to set.|
### setResponseEncoding<sup>9+</sup>
setResponseEncoding(encoding: string)
Sets the encoding string of the resource response.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | ------------ |
| encoding | string | Yes | - | Encoding string to set.|
### setResponseMimeType<sup>9+</sup>
setResponseMimeType(mimeType: string)
Sets the MIME type of the resource response.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | -------------------- |
| mimeType | string | Yes | - | MIME type to set.|
### setReasonMessage<sup>9+</sup>
setReasonMessage(reason: string)
Sets the status code description of the resource response.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------ | ---- | ---- | --------------- |
| reason | string | Yes | - | Status code description to set.|
### setResponseHeader<sup>9+</sup>
setResponseHeader(header: Array\<Header\>)
Sets the resource response header.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | -------------------------- | ---- | ---- | ---------- |
| header | Array\<[Header](#header)\> | Yes | - | Resource response header to set.|
### setResponseCode<sup>9+</sup>
setResponseCode(code: number)
Sets the status code of the resource response.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ------------- |
| code | number | Yes | - | Status code to set.|
## FileSelectorResult<sup>9+</sup>
Notifies the **\<Web>** component of the file selection result. For details about the sample code, see [onShowFileSelector](#onshowfileselector9).
### handleFileList<sup>9+</sup>
handleFileList(fileList: Array\<string\>): void
Instructs the **\<Web>** component to select a file.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | --------------- | ---- | ---- | ------------ |
| fileList | Array\<string\> | Yes | - | List of files to operate.|
## FileSelectorParam<sup>9+</sup>
Implements the **FileSelectorParam** object. For details about the sample code, see [onShowFileSelector](#onshowfileselector9).
### getTitle<sup>9+</sup>
getTitle(): string
Obtains the title of the file selector.
**Return value**
| Type | Description |
| ------ | ---------- |
| string | Title of the file selector.|
### getMode<sup>9+</sup>
getMode(): FileSelectorMode
Obtains the mode of the file selector.
**Return value**
| Type | Description |
| ---------------------------------------- | ----------- |
| [FileSelectorMode](#fileselectormode)| Mode of the file selector.|
### getAcceptType<sup>9+</sup>
getAcceptType(): Array\<string\>
Obtains the file filtering type.
**Return value**
| Type | Description |
| --------------- | --------- |
| Array\<string\> | File filtering type.|
### isCapture<sup>9+</sup>
isCapture(): boolean
Checks whether multimedia capabilities are invoked.
**Return value**
| Type | Description |
| ------- | ------------ |
| boolean | Whether multimedia capabilities are invoked.|
## HttpAuthHandler<sup>9+</sup>
Implements the **HttpAuthHandler** object. For details about the sample code, see [onHttpAuthRequest](#onhttpauthrequest9).
### cancel<sup>9+</sup>
cancel(): void
Cancels HTTP authentication as requested by the user.
### confirm<sup>9+</sup>
confirm(userName: string, pwd: string): boolean
Performs HTTP authentication with the user name and password provided by the user.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------ | ---- | ---- | ---------- |
| userName | string | Yes | - | HTTP authentication user name.|
| pwd | string | Yes | - | HTTP authentication password. |
**Return value**
| Type | Description |
| ------- | --------------------- |
| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.|
### isHttpAuthInfoSaved<sup>9+</sup>
isHttpAuthInfoSaved(): boolean
Uses the password cached on the server for authentication.
**Return value**
| Type | Description |
| ------- | ------------------------- |
| boolean | Returns **true** if the authentication is successful; returns **false** otherwise.|
## PermissionRequest<sup>9+</sup>
Implements the **PermissionRequest** object. For details about the sample code, see [onPermissionRequest](#onpermissionrequest9).
### deny<sup>9+</sup>
deny(): void
Denies the permission requested by the web page.
### getOrigin<sup>9+</sup>
getOrigin(): string
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>
getAccessibleResource(): Array\<string\>
Obtains the list of accessible resources requested for the web page. For details about the resource types, see [ProtectedResourceType](#protectedresourcetype9).
**Return value**
| Type | Description |
| --------------- | ----------------------- |
| Array\<string\> | List of accessible resources requested by the web page.|
### grant<sup>9+</sup>
grant(resources: Array\<string\>): void
Grants the permission for resources requested by the web page.
**Parameters**
| Name | Type | Mandatory| Default Value| Description |
| --------- | --------------- | ---- | ----- | ---------------------- |
| resources | Array\<string\> | Yes | - | List of accessible resources requested by the web page.|
## WebController ## WebController
...@@ -219,35 +1721,134 @@ Defines a **WebController** to control the behavior of the **\<Web>** component. ...@@ -219,35 +1721,134 @@ Defines a **WebController** to control the behavior of the **\<Web>** component.
webController: WebController = new WebController() webController: WebController = new WebController()
``` ```
### requestFocus
requestFocus()
Requests focus for this web page.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('requestFocus')
.onClick(() => {
this.controller.requestFocus();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### accessBackward ### accessBackward
accessBackward(): boolean accessBackward(): boolean
Checks whether going to the previous page can be performed on the current page. Checks whether going to the previous page can be performed on the current page.
**Return value**
| Type | Description |
| ------- | --------------------- |
| boolean | Returns **true** if going to the previous page can be performed on the current page; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('accessBackward')
.onClick(() => {
let result = this.controller.accessBackward();
console.log('result:' + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### accessForward ### accessForward
accessForward(): boolean accessForward(): boolean
Checks whether going to the next page can be performed on the current page. Checks whether going to the next page can be performed on the current page.
**Return value**
| Type | Description |
| ------- | --------------------- |
| boolean | Returns **true** if going to the next page can be performed on the current page; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('accessForward')
.onClick(() => {
let result = this.controller.accessForward();
console.log('result:' + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### accessStep ### accessStep
accessStep(step: number): boolean accessStep(step: number): boolean
Indicates whether a specific number of steps forward or backward can be performed on the current page. Indicates whether a specific number of steps forward or backward can be performed on the current page.
- Parameters **Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | --------------------- | | ---- | ------ | ---- | ---- | --------------------- |
| step | number | Yes | - | Number of the steps to take. A positive number means to going forward, and a negative number means to going backward.| | step | number | Yes | - | Number of the steps to take. A positive number means to going forward, and a negative number means to going backward.|
- Return value **Return value**
| Type | Description |
| Type | Description | | ------- | --------- |
| ------- | --------- | | boolean | Whether to go forward or backward from the current page.|
| boolean | Whether to go forward or backward from the current page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
@State steps: number = 2;
build() {
Column() {
Button('accessStep')
.onClick(() => {
let result = this.controller.accessStep(this.steps);
console.log('result:' + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### backward ### backward
...@@ -255,17 +1856,25 @@ backward(): void ...@@ -255,17 +1856,25 @@ backward(): void
Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**.
### deleteJavaScriptRegister **Example**
```ts
deleteJavaScriptRegister(name: string): void // xxx.ets
@Entry
Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. @Component
struct WebComponent {
- Parameters controller: WebController = new WebController();
| Name | Type | Mandatory | Default Value | Description | build() {
| ---- | ------ | ---- | ---- | ---------------------------------------- | Column() {
| 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.| Button('backward')
.onClick(() => {
this.controller.backward();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### forward ### forward
...@@ -273,27 +1882,278 @@ forward(): void ...@@ -273,27 +1882,278 @@ forward(): void
Goes to the next page based on the history stack. This API is generally used together with **accessForward**. Goes to the next page based on the history stack. This API is generally used together with **accessForward**.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('forward')
.onClick(() => {
this.controller.forward();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### backOrForward<sup>9+</sup>
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.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---- | ------ | ---- | ---- | ----------- |
| step | number | Yes | - | Number of the steps to take.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller:WebController = new WebController();
build() {
Column() {
Button('backOrForward')
.onClick(() => {
this.controller.backOrForward();
})
Web({ src:'www.example.com', controller:this.controller })
}
}
```
### deleteJavaScriptRegister
deleteJavaScriptRegister(name: string)
Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. The deletion takes effect immediately, with no need for invoking the [refresh](#refresh) API.
**Parameters**
| Name | Type | Mandatory | Default Value | 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.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
@State name: string = 'Object';
build() {
Column() {
Button('deleteJavaScriptRegister')
.onClick(() => {
this.controller.deleteJavaScriptRegister(this.name);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getHitTest ### getHitTest
getHitTest(): HitTestType getHitTest(): HitTestType
Obtains the element type of the area being clicked. Obtains the element type of the area being clicked.
- HitTestType enums **Return value**
| Type | Description |
| Name | Description | | ------------------------------- | ----------- |
| ------------- | ------------------------ | | [HitTestType](#hittesttype)| Element type of the area being clicked.|
| EditText | Editable area. |
| Email | Email address. | **Example**
| HttpAnchor | Hyperlink where **src** is **http**. | ```ts
| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| // xxx.ets
| Img | HTML::img tag. | @Entry
| Map | Geographical address. | @Component
| Unknown | Unknown content. | struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getHitTest')
.onClick(() => {
let hitType = this.controller.getHitTest();
console.log("hitType: " + hitType);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getHitTestValue<sup>9+</sup>
getHitTestValue(): HitTestValue
Obtains the element information of the area being clicked.
**Return value**
| Type | Description |
| ------------------------------ | ---------- |
| [HitTestValue](#hittestvalue9) | Element information of the area being clicked.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getHitTestValue')
.onClick(() => {
let hitValue = this.controller.getHitTestValue();
console.log("hitType: " + hitValue.getType());
console.log("extra: " + hitValue.getExtra());
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getWebId<sup>9+</sup>
getWebId(): number
Obtains the index value of this **\<Web>** component, which can be used for **\<Web>** component management.
**Return value**
| Type | Description |
| ------ | ------------ |
| number | Index value of the current **\<Web>** component.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getWebId')
.onClick(() => {
let id = this.controller.getWebId();
console.log("id: " + id);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getTitle<sup>9+</sup>
getTitle(): string
Obtains the title of the current web page.
**Return value**
| Type | Description |
| ------ | -------- |
| string | Title of the current web page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getTitle')
.onClick(() => {
let title = this.controller.getTitle();
console.log("title: " + title);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getPageHeight<sup>9+</sup>
getPageHeight(): number
Obtains the height of the current web page.
**Return value**
| Type | Description |
| ------ | ---------- |
| number | Height of the current web page.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getPageHeight')
.onClick(() => {
let pageHeight = this.controller.getPageHeight();
console.log("pageHeight: " + pageHeight);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getDefaultUserAgent<sup>9+</sup>
getDefaultUserAgent(): string
Obtains the default user agent of the current web page.
**Return value**
| Type | Description |
| ------ | ------- |
| string | Default user agent.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getDefaultUserAgent')
.onClick(() => {
let userAgent = this.controller.getDefaultUserAgent();
console.log("userAgent: " + userAgent);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### loadData ### loadData
loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string }): void loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string })
Loads data. If **baseUrl** is empty, the specified character string will be loaded using the data protocol. Loads data. If **baseUrl** is empty, the specified character string will be loaded using the data protocol.
...@@ -301,32 +2161,74 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the ** ...@@ -301,32 +2161,74 @@ If **baseUrl** is set to a data URL, the encoded string will be loaded by the **
If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\<Web>** component as a non-encoded string in a manner similar to **loadUrl**. If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be processed by the **\<Web>** component as a non-encoded string in a manner similar to **loadUrl**.
- options **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ---------- | ------ | ---- | ---- | ---------------------------------------- |
| ---------- | ------ | ---- | ---- | ---------------------------------------- | | data | string | Yes | - | Character string obtained after being Base64 or URL encoded. |
| data | string | Yes | - | Character string obtained after being Base64 or URL encoded. | | mimeType | string | Yes | - | Media type (MIME). |
| mimeType | string | Yes | - | Media type (MIME). | | encoding | string | Yes | - | Encoding type, which can be Base64 or URL. |
| 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**.|
| baseUrl | string | No | - | URL (HTTP/HTTPS/data compliant), which is assigned by the **\<Web>** component to **window.origin**.| | historyUrl | string | No | - | Historical record URL. If this parameter is not empty, it can be managed in historical records to implement page going backward and forward. This parameter is invalid when **baseUrl** is left empty.|
| historyUrl | string | No | - | Historical record URL. If this parameter is not empty, it can be managed in historical records to implement page going backward and forward. This parameter is invalid when **baseUrl** is left empty.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('loadData')
.onClick(() => {
this.controller.loadData({
data: "<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>",
mimeType: "text/html",
encoding: "UTF-8"
});
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### loadUrl ### loadUrl
loadUrl(options:{ url: string, headers?: Array\<Header\> }): void loadUrl(options: { url: string | Resource, headers?: Array\<Header\> })
Loads a URL using the specified HTTP header. Loads a URL using the specified HTTP header.
The object injected through **loadUrl** is valid only in the current document. It will be invalid on a new page navigated to through **loadUrl**. The object injected through **loadUrl** is valid only in the current document. It will be invalid on a new page navigated to through **loadUrl**.
The object injected through **registerJavaScriptProxy** is still valid on a new page navigated to through **loadUrl**. The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**.
- options **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| Name | Type | Mandatory | Default Value | Description | | ------- | -------------------------- | ---- | ---- | -------------- |
| ------- | ------------------------------ | ---- | ---- | -------------- | | url | string | Yes | - | URL to load. |
| url | string | Yes | - | URL to load. | | headers | Array\<[Header](#header)\> | No | [] | Additional HTTP request header of the URL.|
| headers | Array\<[Header](#header)\> | No | [] | Additional HTTP request header of the URL.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
this.controller.loadUrl({ url: 'www.example.com' });
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onActive ### onActive
...@@ -334,130 +2236,994 @@ onActive(): void ...@@ -334,130 +2236,994 @@ onActive(): void
Invoked to instruct the **\<Web>** component to enter the foreground, active state. Invoked to instruct the **\<Web>** component to enter the foreground, active state.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('onActive')
.onClick(() => {
this.controller.onActive();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### onInactive ### onInactive
onInactive(): void onInactive(): void
Invoked to instruct the **\<Web>** component to enter the inactive state. Invoked to instruct the **\<Web>** component to enter the inactive state.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('onInactive')
.onClick(() => {
this.controller.onInactive();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### zoom
zoom(factor: number): void
Sets a zoom factor for the current web page.
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ------------------------------ |
| factor | number | Yes | Zoom factor to set. A positive value indicates zoom-in, and a negative value indicates zoom-out.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
@State factor: number = 1;
build() {
Column() {
Button('zoom')
.onClick(() => {
this.controller.zoom(this.factor);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### zoomIn<sup>9+</sup>
zoomIn(): boolean
Zooms in on the current web page by 20%.
**Return value**
| Type | Description |
| ------- | ----------- |
| boolean | Operation result.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('zoomIn')
.onClick(() => {
let result = this.controller.zoomIn();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### zoomOut<sup>9+</sup>
zoomOut(): boolean
Zooms out the current web page by 20%.
**Return value**
| Type | Description |
| ------- | ----------- |
| boolean | Operation result.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('zoomOut')
.onClick(() => {
let result = this.controller.zoomOut();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### refresh ### refresh
refresh(): void refresh()
Invoked to instruct the **\<Web>** component to refresh the web page. Invoked to instruct the **\<Web>** component to refresh the web page.
### registerJavaScriptProxy **Example**
```ts
registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\<string\> }): void // xxx.ets
@Entry
Injects a JavaScript object into the window and invokes the methods of the object in the window. After the registration, the **refresh** API must be invoked for the registration to take effect. @Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('refresh')
.onClick(() => {
this.controller.refresh();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
- options ### registerJavaScriptProxy
| Name | Type | Mandatory | Default Value | Description | registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\<string\> })
| ---------- | --------------- | ---- | ---- | ---------------------------------------- |
| object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return value can only be of the string, number, or Boolean type.| Registers a JavaScript object and invokes the methods of the object in the window. You must invoke the [refresh](#refresh) API for the registration to take effect.
| 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. | **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ---------- | --------------- | ---- | ---- | ---------------------------------------- |
| object | object | Yes | - | Application-side JavaScript object to be registered. Methods can be declared, but not attributes. The parameters and return value 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. |
**Example**
```ts
// xxx.ets
@Entry
@Component
struct Index {
controller: WebController = new WebController()
testObj = {
test: (data) => {
return "ArkUI Web Component";
},
toString: () => {
console.log('Web Component toString');
}
}
build() {
Column() {
Row() {
Button('Register JavaScript To Window').onClick(() => {
this.controller.registerJavaScriptProxy({
object: this.testObj,
name: "objName",
methodList: ["test", "toString"],
});
})
}
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
}
}
}
```
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
Hello world!
</body>
<script type="text/javascript">
function htmlTest() {
str = objName.test("test function");
console.log('objName.test result:'+ str);
}
</script>
</html>
```
### runJavaScript ### runJavaScript
runJavaScript(options: { script: string, callback?: (result: string) => void }): void 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**. 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**.
- options **Parameters**
| Name | Type | Mandatory | Default Value | Description |
| -------- | ------------------------ | ---- | ---- | ---------------------------------------- |
| script | string | Yes | - | JavaScript script. |
| callback | (result: string) => void | No | - | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
@State webResult: string = ''
build() {
Column() {
Text(this.webResult).fontSize(20)
Web({ src: $rawfile('index.html'), controller: this.controller })
.javaScriptAccess(true)
.onPageEnd(e => {
this.controller.runJavaScript({
script: 'test()',
callback: (result: string)=> {
this.webResult = result
console.info(`The test() return value is: ${result}`)
}});
console.info('url: ', e.url);
})
}
}
}
```
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<body>
Hello world!
</body>
<script type="text/javascript">
function test() {
console.log('Ark WebComponent');
return "This value is from index.html"
}
</script>
</html>
| Name | Type | Mandatory | Default Value | Description | ```
| -------- | ------------------------ | ---- | ---- | ---------------------------------------- |
| script | string | Yes | - | JavaScript script. |
| callback | (result: string) => void | No | - | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed or no value is returned.|
### stop ### stop
stop(): void stop()
Stops page loading. Stops page loading.
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('stop')
.onClick(() => {
this.controller.stop();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### clearHistory ### clearHistory
clearHistory(): void clearHistory(): void
Clears the browsing history. Clears the browsing history.
### getCookieManager **Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('clearHistory')
.onClick(() => {
this.controller.clearHistory();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getCookieManager<sup>9+</sup>
getCookieManager(): WebCookie getCookieManager(): WebCookie
Obtains the cookie management object of the **\<Web>** component. Obtains the cookie management object of the **\<Web>** component.
- Return value
| Type | Description | **Return value**
| --------- | ---------------------------------------- | | Type | Description |
| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).| | --------- | ---------------------------------------- |
| WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('getCookieManager')
.onClick(() => {
let cookieManager = this.controller.getCookieManager();
})
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).
### getType<sup>9+</sup>
getType(): HitTestType
Obtains the element type of the area being clicked.
**Return value**
| Type | Description |
| ------------------------------- | ------------- |
| [HitTestType](#hittesttype)| Element type of the area being clicked.|
### getExtra<sup>9+</sup>
getExtra(): string
Obtains the 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.
**Return value**
| Type | Description |
| ------ | ------------ |
| string | Extra information of the area being clicked.|
## WebCookie ## WebCookie
Manages behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. Manages behavior of cookies in **\<Web>** components. All **\<Web>** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management.
### setCookie
### setCookie<sup>9+</sup>
setCookie(url: string, value: string): boolean setCookie(url: string, value: string): boolean
Sets the cookie. This API is synchronous. Sets the cookie. This API returns the result synchronously.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie to set.|
| value | string | Yes | - | Value of the cookie to set. |
**Return value**
| Type | Description |
| ------- | ------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('setCookie')
.onClick(() => {
let result = this.controller.getCookieManager().setCookie("www.example.com", "a=b");
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
- Parameters ### saveCookieSync<sup>9+</sup>
saveCookieSync(): boolean
| Name | Type | Mandatory | Default Value | Description | Saves this cookie in the memory to the drive. This API returns the result synchronously.
| ----- | ------ | ---- | ---- | ----------------- |
| url | string | Yes | - | URL of the cookie to set.| **Return value**
| value | string | Yes | - | Value of the cookie to set. | | Type | Description |
- Return value | ------- | -------------------- |
| Type | Description | | boolean | Operation result.|
| ------- | ------------- |
| boolean | Returns **true** if the operation is successful; returns **false** otherwise.| **Example**
```ts
// xxx.ets
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('saveCookieSync')
.onClick(() => {
let result = this.controller.getCookieManager().saveCookieSync();
console.log("result: " + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebDataBase<sup>9+</sup>
Implements the **WebDataBase** object.
### existHttpAuthCredentials<sup>9+</sup>
static existHttpAuthCredentials(): boolean
Checks whether any HTTP authentication credentials exist in the cache. This API returns the result synchronously.
**Return value**
| Type | Description |
| ------- | ---------------------------------------- |
| boolean | Returns **true** if any HTTP authentication credentials exist in the cache; returns **false** otherwise.|
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('existHttpAuthCredentials')
.onClick(() => {
let result = web.WebDataBase.existHttpAuthCredentials();
console.log('result: ' + result);
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### deleteHttpAuthCredentials<sup>9+</sup>
static deleteHttpAuthCredentials(): void
Deletes all HTTP authentication credentials saved in the cache. This API returns the result synchronously.
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('deleteHttpAuthCredentials')
.onClick(() => {
web.WebDataBase.deleteHttpAuthCredentials();
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### getHttpAuthCredentials<sup>9+</sup>
static getHttpAuthCredentials(host: string, realm: string): Array\<string\>
Obtains the HTTP authentication credentials for a given host and realm. This API returns the result synchronously.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ----- | ------ | ---- | ---- | ---------------- |
| host | string | Yes | - | Host for which you want to obtain the HTTP authentication credentials.|
| realm | string | Yes | - | Realm for which you want to obtain the HTTP authentication credentials. |
**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 from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
host: string = "www.spincast.org";
realm: string = "protected example";
username_password: string[];
build() {
Column() {
Button('getHttpAuthCredentials')
.onClick(() => {
this.username_password = web.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)
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
### saveHttpAuthCredentials<sup>9+</sup>
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.
**Parameters**
| Name | Type | Mandatory | Default Value | 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 from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
host: string = "www.spincast.org";
realm: string = "protected example";
build() {
Column() {
Button('saveHttpAuthCredentials')
.onClick(() => {
web.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche");
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## WebStorage<sup>9+</sup>
Implements the **WebStorage** object, which can be used to manage the Web SQL and the HTML5 Web Storage API. All **\<Web>** components in an application share one **WebStorage**.
### deleteAllData<sup>9+</sup>
static deleteAllData(): void
Deletes all data in the Web SQL database.
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
build() {
Column() {
Button('deleteAllData')
.onClick(() => {
web.WebStorage.deleteAllData();
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### deleteOrigin<sup>9+</sup>
static deleteOrigin(origin : string): void
Deletes all data in the specified origin.
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- |
| origin | string | Yes | Index of the origin.|
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "origin";
build() {
Column() {
Button('getHttpAuthCredentials')
.onClick(() => {
web.WebStorage.deleteOrigin(this.origin);
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### 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.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
| callback | AsyncCallback<Array<[WebStorageOrigin](#webstorageorigin9)>> | Yes | Callback used to return the information about the origins. For details, see **WebStorageOrigin**.|
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "origin";
build() {
Column() {
Button('getOrigins')
.onClick(() => {
web.WebStorage.getOrigins((error, origins) => {
if (error) {
console.log('error: ' + 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);
}
})
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### saveCookieSync ### getOrigins<sup>9+</sup>
saveCookieSync(): boolean static getOrigins() : Promise<Array<[WebStorageOrigin]>>
Saves this cookie in the memory to the disk. This API is synchronous. Obtains information about all origins that are currently using the Web SQL database. This API uses a promise to return the result.
- Return value
| Type | Description | **Return value**
| ------- | -------------------- |
| boolean | Returns the operation result.| | Type | Description |
## Example | ---------------------------------------- | ---------------------------------------- |
| Promise<Array<[WebStorageOrigin](#webstorageorigin9)>> | Promise used to return the information about the origins. For details, see **WebStorageOrigin**.|
```ts
// webComponent.ets **Example**
@Entry ```ts
@Component // xxx.ets
struct WebComponent { import web from '@ohos.web';
@State javaScriptAccess: boolean = true; @Entry
@State fileAccess: boolean = true; @Component
controller: WebController = new WebController(); struct WebComponent {
build() { controller: WebController = new WebController();
Column() { origin: string = "origin";
Web({ src: $rawfile('index.html'), controller: this.controller }) build() {
.javaScriptAccess(this.javaScriptAccess) Column() {
.fileAccess(this.fileAccess) Button('getOrigins')
.onPageEnd(e => { .onClick(() => {
// test() has been defined in index.html. web.WebStorage.getOrigins()
this.controller.runJavaScript({ script: 'test()' }); .then(origins => {
console.log("url: ", e.url); 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);
} }
``` })
```html .catch(error => {
<!-- index.html --> console.log('error: ' + error);
<!DOCTYPE html> })
<html> })
<meta charset="utf-8"> Web({ src: 'www.example.com', controller: this.controller })
<body> .databaseAccess(true)
Hello world! }
</body> }
<script type="text/javascript"> }
function test() { ```
console.log('Ark WebComponent');
} ### getOriginQuota<sup>9+</sup>
</script> static getOriginQuota(origin : string, callback : AsyncCallback\<number>) : void
</html>
``` 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**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | --------- |
| origin | string | Yes | Index of the origin.|
| callback | AsyncCallback\<number> | Yes | Callback used to return the storage quota of the origin.|
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "origin";
build() {
Column() {
Button('getOriginQuota')
.onClick(() => {
web.WebStorage.getOriginQuota(this.origin, (error, quota) => {
if (error) {
console.log('error: ' + error);
return;
}
console.log('quota: ' + quota);
})
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### 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.
**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.|
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "origin";
build() {
Column() {
Button('getOriginQuota')
.onClick(() => {
web.WebStorage.getOriginQuota(this.origin)
.then(quota => {
console.log('quota: ' + quota);
})
.catch(error => {
console.log('error: ' + error);
})
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### 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.
**Parameters**
| Name | Type | Mandatory | Description |
| -------- | ---------------------- | ---- | ---------- |
| origin | string | Yes | Index of the origin.|
| callback | AsyncCallback\<number> | Yes | Callback used to return the storage usage of the origin. |
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "origin";
build() {
Column() {
Button('getOriginUsage')
.onClick(() => {
web.WebStorage.getOriginUsage(this.origin, (error, usage) => {
if (error) {
console.log('error: ' + error);
return;
}
consloe.log('usage: ' + usage);
})
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
### 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.
**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.|
**Example**
```ts
// xxx.ets
import web from '@ohos.web';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController();
origin: string = "origin";
build() {
Column() {
Button('getOriginQuota')
.onClick(() => {
web.WebStorage.getOriginUsage(this.origin)
.then(usage => {
console.log('usage: ' + usage);
})
.catch(error => {
console.log('error: ' + error);
})
})
Web({ src: 'www.example.com', controller: this.controller })
.databaseAccess(true)
}
}
}
```
## WebStorageOrigin<sup>9+</sup>
Provides usage information about the Web SQL database.
**Parameters**
| Name | Type | Mandatory | Description |
| ------ | ------ | ---- | ---------- |
| origin | string | Yes | Index of the origin.|
| usage | number | Yes | Storage usage of the origin. |
| quota | number | Yes | Storage quota of the origin. |
## MessageLevel enums
| Name | Description |
| ----- | :---- |
| Debug | Debug level.|
| Error | Error level.|
| Info | Information level.|
| Log | Log level.|
| Warn | Warning level. |
## RenderExitReason
Explains why the rendering process exits.
| Name | Description |
| -------------------------- | ----------------- |
| ProcessAbnormalTermination | The rendering process exits abnormally. |
| ProcessWasKilled | The rendering process receives a SIGKILL message or is manually terminated.|
| ProcessCrashed | The rendering process crashes due to segmentation or other errors. |
| ProcessOom | The program memory is running low. |
| ProcessExitUnknown | Other reason. |
## MixedMode
| Name | Description |
| ---------- | ---------------------------------- |
| All | HTTP and HTTPS hybrid content can be loaded. This means that all insecure content can be loaded.|
| Compatible | HTTP and HTTPS hybrid content can be loaded in compatibility mode. This means that some insecure content may be loaded. |
| None | HTTP and HTTPS hybrid content cannot be loaded. |
## CacheMode
| Name | Description |
| ------- | ------------------------------------ |
| Default | The cache that has not expired is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet.|
| None | The cache is used to load the resources. If the resources do not exist in the cache, they will be obtained from the Internet. |
| Online | The cache is not used to load the resources. All resources are obtained from the Internet. |
| Only | The cache alone is used to load the resources. |
## FileSelectorMode
| Name | Description |
| -------------------- | ---------- |
| FileOpenMode | Open and upload a file. |
| FileOpenMultipleMode | Open and upload multiple files. |
| FileOpenFolderMode | Open and upload a folder.|
| FileSaveMode | Save a file. |
## HitTestType
| Name | Description |
| ------------- | ------------------------ |
| EditText | Editable area. |
| Email | Email address. |
| HttpAnchor | Hyperlink whose **src** is **http**. |
| HttpAnchorImg | Image with a hyperlink, where **src** is **http**.|
| Img | HTML::img tag. |
| Map | Geographical address. |
| Unknown | Unknown content. |
## ProtectedResourceType<sup>9+</sup>
![](figures/Web.png) | Name | Description | Remarks |
| --------- | -------------- | -------------- |
| MidiSysex | MIDI SYSEX resources| Currently, only permission events can be reported. MIDI devices are not yet supported.|
# XComponent # XComponent
> **NOTE**<br> > **NOTE**<br>
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. > This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
The **\<XComponent>** can accept and display the EGL/OpenGLES and media data input. The **\<XComponent>** can accept and display the EGL/OpenGL ES and media data input.
## Required Permissions ## Required Permissions
...@@ -17,22 +18,34 @@ ...@@ -17,22 +18,34 @@
XComponent\(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}\) XComponent\(value: {id: string, type: string, libraryname?: string, controller?: XComponentController}\)
- Name **Parameters**
| Name | Type | Mandatory | Description |
| ----------- | --------------------------------------- | --------- | ------------------------------------------------------------ |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters. |
| type | string | Yes | Type of the component. The options are as follows:<br>- **surface**: The content of this component is displayed individually, without being combined with that of other components.<br>- **component**: The content of this component is displayed after having been combined with that of other components. |
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer. |
| controller | [XComponentController](#XComponentController) | No | Controller bound to the component, which can be used to invoke methods of the component. |
| Name | Type | Mandatory | Description |
| --------- | ------ | ---- | ----- |
| id | string | Yes | Unique ID of the component. The value can contain a maximum of 128 characters.|
| type | string | Yes | Type of the component. The options are as follows:<br>-**surface**: The content of this component is displayed individually, without being combined with that of other components.<br>-**component**: The content of this component is displayed after having been combined with that of other components.|
| libraryname | string | No | Name of the dynamic library generated after compilation at the application native layer.|
| controller | [XComponentcontroller](#xcomponentcontroller) | No | Controller bound to the component, which can be used to invoke methods of the component.|
## Events ## Events
| Name | Description | ### onLoad
| ------------------------------- | ------------------------ |
| onLoad(context?: object) => void | Triggered when the plug-in is loaded. | onLoad(callback: (event?: object) => void )
| onDestroy() => void | Triggered when the plug-in is destroyed. |
Triggered when the plug-in is loaded.
**Parameters**
| Name | Type | Mandatory | Description |
| ------------- | ------ | ---- | ----------------------- |
| event | object | No | Context of the **\<XComponent>** object. The APIs contained in the context are defined at the C++ layer by developers.|
### onDestroy
onDestroy(event: () => void )
Triggered when the plug-in is destroyed.
## XComponentController ## XComponentController
...@@ -50,11 +63,13 @@ getXComponentSurfaceId(): string ...@@ -50,11 +63,13 @@ getXComponentSurfaceId(): string
Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used for @ohos interfaces, such as camera-related interfaces. Obtains the ID of the surface held by the **\<XComponent>**. The ID can be used for @ohos interfaces, such as camera-related interfaces.
- Return value **System API**: This is a system API.
| Type | Description | **Return value**
| ------ | --------------------------- |
| string | ID of the surface held by the **\<XComponent>**. | | Type | Description |
| ------ | ----------------------- |
| string | ID of the surface held by the **\<XComponent>**.|
### setXComponentSurfaceSize ### setXComponentSurfaceSize
...@@ -62,12 +77,14 @@ setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}): ...@@ -62,12 +77,14 @@ setXComponentSurfaceSize(value: {surfaceWidth: number, surfaceHeight: number}):
Sets the width and height of the surface held by the **\<XComponent>**. Sets the width and height of the surface held by the **\<XComponent>**.
- Parameters **System API**: This is a system API.
**Parameters**
| Name | Type | Mandatory | Default Value | Description | | Name | Type | Mandatory | Description |
| ------------- | -------- | ---- | ------ | ----------------------------- | | ------------- | ------ | ---- | ----------------------- |
| surfaceWidth | number | Yes | - | Width of the surface held by the **\<XComponent>**. | | surfaceWidth | number | Yes | Width of the surface held by the **\<XComponent>**.|
| surfaceHeight | number | Yes | - | Height of the surface held by the **\<XComponent>**. | | surfaceHeight | number | Yes | Height of the surface held by the **\<XComponent>**.|
### getXComponentContext ### getXComponentContext
...@@ -75,15 +92,16 @@ getXComponentContext(): Object ...@@ -75,15 +92,16 @@ getXComponentContext(): Object
Obtains the context of an **\<XComponent>** object. Obtains the context of an **\<XComponent>** object.
- Return value **Return value**
| Type | Description | | Type | Description |
| ------ | ------------------------------------------------------------ | | ------ | ---------------------------------------- |
| Object | Context of an **\<XComponent>** object. The APIs contained in the context are defined by developers. | | Object | Context of the **\<XComponent>** object. The APIs contained in the context are defined by developers.|
## Example ## Example
Provide a surface-type **\<XComponent>** to support capabilities such as camera preview. Provide a surface-type **\<XComponent>** to support capabilities such as camera preview.
You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer.
```ts ```ts
// xxx.ets // xxx.ets
......
# Component ID # Component ID
**id** identifies a component uniquely within an application. This module provides APIs for obtaining the attributes of or sending events to the component with the specified ID.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. >
> The APIs of this module are supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version.
## Required Permissions ## Required Permissions
...@@ -12,93 +14,250 @@ None ...@@ -12,93 +14,250 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name| Type| Default Value| Description|
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| id | string | '' | Unique ID of the component. The uniqueness is ensured by the user. | | id | string | '' | Unique ID you assigned to the component.|
## APIs ## APIs
### getInspectorByKey ### getInspectorByKey<sup>9+</sup>
getInspectorByKey(id: string): string getInspectorByKey(id: string): string
Obtains all attributes of the component with the specified ID, excluding the information about child components. Obtains all attributes of the component with the specified ID, excluding the information about child components.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| id | string | Yes | - | ID of the component whose attributes are to be obtained. | | id | string | Yes| - | ID of the component whose attributes are to be obtained.|
- Return value - Return value
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| string | JSON string of the component attribute list. | | string | JSON string of the component attribute list.|
### getInspectorTree<sup>9+</sup>
### sendEventByKey getInspectorTree(): string
Obtains the component tree and component attributes.
- Return value
| Type | Description |
| ------ | ---------------------------------- |
| string | JSON string of the component tree and component attribute list.|
### sendEventByKey<sup>9+</sup>
sendEventByKey(id: string, action: number, params: string): boolean sendEventByKey(id: string, action: number, params: string): boolean
Sends an event to the component with the specified ID. Sends an event to the component with the specified ID.
- Parameters - Parameters
| Name | Type | Mandatory | Default Value | Description | | Name| Type| Mandatory| Default Value| Description|
| -------- | -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- | -------- |
| id | string | Yes | - | ID of the component for which the event is to be sent. | | id | string | Yes| - | ID of the component to which the event is to be sent.|
| action | number | Yes | - | Type of the event to be sent. The options are as follows:<br/>- Click event: 10.<br/>- LongClick: 11. | | action | number | Yes| - | Type of the event to be sent. The options are as follows:<br>- **10**: click event.<br>- **11**: long-click event.|
| params | string | Yes | - | Event parameters. If there is no parameter, pass an empty string **""**. | | params | string | Yes| - | Event parameters. If there is no parameter, pass an empty string **""**.|
- Return value - Return value
| Type | Description | | Type| Description|
| -------- | -------- | | -------- | -------- |
| boolean | Returns **false** if the component with the specified ID cannot be found; returns **true** otherwise. | | boolean | Returns **true** if the component with the specified ID is found; returns **false** otherwise.|
### sendTouchEvent<sup>9+</sup>
sendTouchEvent(event: TouchObject): boolean
Sends a touch event.
- Parameters
| Name | Type | Mandatory| Default Value| Description |
| ----- | ----------- | ---- | ------ | ------------------------------------------------------------ |
| event | TouchObject | Yes | - | Location where a touch event is triggered. For details, see [TouchEvent](ts-universal-events-touch.md#touchevent).|
- Return value
| Type | Description |
| ------- | ------------------------------------------- |
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
### sendKeyEvent<sup>9+</sup>
sendKeyEvent(event: KeyEvent): boolean
Sends a key event.
- Parameters
| Name | Type | Mandatory| Default Value| Description |
| ----- | -------- | ---- | ------ | ------------------------------------------------------------ |
| event | KeyEvent | Yes | - | Key event. For details, see [KeyEvent](ts-universal-events-key.md#keyevent).|
- Return value
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
### sendMouseEvent<sup>9+</sup>
sendMouseEvent(event: MouseEvent): boolean
Sends a mouse event.
- Parameters
| Name | Type | Mandatory| Default Value| Description |
| ----- | ---------- | ---- | ------ | ------------------------------------------------------------ |
| event | MouseEvent | Yes | - | Mouse event. For details, see [MouseEvent](ts-universal-mouse-key.md#mouseevent).|
- Return value
| Type | Description |
| ------- | --------------------------------------------- |
| boolean | Returns **true** if the event is sent successfully; returns **false** otherwise.|
## Example ## Example
```ts
``` // xxx.ets
class Utils {
static rect_left;
static rect_top;
static rect_right;
static rect_bottom;
static rect_value;
static getComponentRect(key) {
let strJson = getInspectorByKey(key);
let obj = JSON.parse(strJson);
console.info("[getInspectorByKey] current component obj is: " + JSON.stringify(obj));
let rectInfo = JSON.parse('[' + obj.$rect + ']')
console.info("[getInspectorByKey] rectInfo is: " + rectInfo);
this.rect_left = JSON.parse('[' + rectInfo[0] + ']')[0]
this.rect_top = JSON.parse('[' + rectInfo[0] + ']')[1]
this.rect_right = JSON.parse('[' + rectInfo[1] + ']')[0]
this.rect_bottom = JSON.parse('[' + rectInfo[1] + ']')[1]
return this.rect_value = {
"left": this.rect_left, "top": this.rect_top, "right": this.rect_right, "bottom": this.rect_bottom
}
}
}
@Entry @Entry
@Component @Component
struct IdExample { struct IdExample {
@State text: string = ''
build() { build() {
Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) { Flex({ direction: FlexDirection.Column, alignItems: ItemAlign.Center, justifyContent: FlexAlign.Center }) {
Button() { Button() {
Text('click') Text('onKeyTab').fontSize(25).fontWeight(FontWeight.Bold)
.fontSize(25) }.margin({ top: 20 }).backgroundColor('#0D9FFB')
.fontWeight(FontWeight.Bold) .onKeyEvent(() => {
} this.text = "onKeyTab"
.type(ButtonType.Capsule) })
.margin({
top: 20 Button() {
}).onClick(() => { Text('click to start').fontSize(25).fontWeight(FontWeight.Bold)
}.margin({ top: 20 })
.onClick(() => {
console.info(getInspectorByKey("click")) console.info(getInspectorByKey("click"))
console.info(getInspectorTree()) console.info(getInspectorTree())
this.text = "Button 'click to start' is clicked"
setTimeout(() => { setTimeout(() => {
sendEventByKey("longclick", 11, "") sendEventByKey("longClick", 11, "")
}, 2000) }, 2000)
}).id('click') }).id('click')
Button() { Button() {
Text('longclick') Text('longClick').fontSize(25).fontWeight(FontWeight.Bold)
.fontSize(25) }.margin({ top: 20 }).backgroundColor('#0D9FFB')
.fontWeight(FontWeight.Bold)
}
.type(ButtonType.Capsule)
.margin({
top: 20
})
.backgroundColor('#0D9FFB')
.gesture( .gesture(
LongPressGesture().onActionEnd(() => { LongPressGesture().onActionEnd(() => {
console.info('long clicked') console.info('long clicked')
})) this.text = "Button 'longClick' is longclicked"
.id('longclick') setTimeout(() => {
let rect = Utils.getComponentRect('onTouch')
let touchPoint: TouchObject = {
id: 1,
x: rect.left + (rect.right - rect.left) / 2,
y: rect.top + (rect.bottom - rect.top) / 2,
type: TouchType.Down,
screenX: rect.left + (rect.right - rect.left) / 2,
screenY: rect.left + (rect.right - rect.left) / 2,
}
sendTouchEvent(touchPoint)
touchPoint.type = TouchType.Up
sendTouchEvent(touchPoint)
}, 2000)
})).id('longClick')
Button() {
Text('onTouch').fontSize(25).fontWeight(FontWeight.Bold)
}.type(ButtonType.Capsule).margin({ top: 20 })
.onClick(() => {
console.info('onTouch is clicked')
this.text = "Button 'onTouch' is clicked"
setTimeout(() => {
let rect = Utils.getComponentRect('onMouse')
let mouseEvent: MouseEvent = {
button: MouseButton.Left,
action: MouseAction.Press,
x: rect.left + (rect.right - rect.left) / 2,
y: rect.top + (rect.bottom - rect.top) / 2,
screenX: rect.left + (rect.right - rect.left) / 2,
screenY: rect.top + (rect.bottom - rect.top) / 2,
timestamp: 1,
target: {
area: {
width: 1,
height: 1,
position: {
x: 1,
y: 1
},
globalPosition: {
x: 1,
y: 1
}
}
},
source: SourceType.Mouse
}
sendMouseEvent(mouseEvent)
}, 2000)
}).id('onTouch')
Button() {
Text('onMouse').fontSize(25).fontWeight(FontWeight.Bold)
}.margin({ top: 20 }).backgroundColor('#0D9FFB')
.onMouse(() => {
console.info('onMouse')
this.text = "Button 'onMouse' in onMouse"
setTimeout(() => {
let keyEvent: KeyEvent = {
type: KeyType.Down,
keyCode: 2049,
keyText: 'tab',
keySource: 4,
deviceId: 0,
metaKey: 0,
timestamp: 0
}
sendKeyEvent(keyEvent)
}, 2000)
}).id('onMouse')
Text(this.text).fontSize(25).padding(15)
} }
.width('100%') .width('100%').height('100%')
.height('100%')
} }
} }
``` ```
# Z-order Control # Z-order Control
The **zIndex** attribute sets the z-order of a component in the stacking context.
> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE** > **NOTE**
> This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. > This attribute is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version.
...@@ -13,15 +14,16 @@ None ...@@ -13,15 +14,16 @@ None
## Attributes ## Attributes
| Name | Type | Default Value | Description | | Name | Type | Default Value | Description |
| -------- | -------- | -------- | -------- | | -------- | -------- | -------- | -------- |
| zIndex | number | 0 | Hierarchy of sibling components in a container. A larger z-order value indicates a higher display level. | | zIndex | number | 0 | Hierarchy of sibling components in a container. A larger value indicates a higher display level. |
## Example ## Example
``` ```ts
// xxx.ets
@Entry @Entry
@Component @Component
struct ZIndexExample { struct ZIndexExample {
...@@ -38,7 +40,7 @@ struct ZIndexExample { ...@@ -38,7 +40,7 @@ struct ZIndexExample {
Text('third child, zIndex(1)') Text('third child, zIndex(1)')
.size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart) .size({width: '70%', height: '50%'}).backgroundColor(0xc1cbac).align(Alignment.TopStart)
.zIndex(1) .zIndex(1)
} }.width('100%').height(200)
}.width('100%').height(200) }.width('100%').height(200)
} }
} }
......
# Event Configuration # Event Configuration
You can use event methods to configure events supported by components. Since API version 9, you can obtain the context associated with the current component from the callback. For details, see [Obtaining the Context on an eTS Page](../ability/context-userguide.md).
You can use event methods to configure events supported by components.
- Example of using a lambda expression to configure the event of a component: - Example of using a lambda expression to configure the event of a component:
```ts ```ts
// Counter is a private data variable defined in the component. // Counter is a private data variable defined in the component.
Button('add counter') Button('add counter')
...@@ -15,8 +13,7 @@ You can use event methods to configure events supported by components. ...@@ -15,8 +13,7 @@ You can use event methods to configure events supported by components.
``` ```
- When using an anonymous function expression to configure the event of a component, bind must be used to ensure that the contained components are referenced by this in the function body. - When using an anonymous function expression to configure the event of a component, **bind** must be used to ensure that the contained components are referenced by **this** in the function body.
```ts ```ts
// Counter is a private data variable defined in the component. // Counter is a private data variable defined in the component.
Button('add counter') Button('add counter')
...@@ -27,14 +24,13 @@ You can use event methods to configure events supported by components. ...@@ -27,14 +24,13 @@ You can use event methods to configure events supported by components.
- Example of using a component's member function to configure the event of the component: - Example of using a component's member function to configure the event of the component:
```ts ```ts
myClickHandler(): void { myClickHandler(): void {
// do something // do something
} }
... ...
Button('add counter') Button('add counter')
.onClick(this.myClickHandler) .onClick(this.myClickHandler)
``` ```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册