diff --git a/en/application-dev/ability/fa-dataability.md b/en/application-dev/ability/fa-dataability.md index d291124c123f0f8e30ef344179a8891c67972b81..36eda5d9210681106a9476bdc87de28f4d06406c 100644 --- a/en/application-dev/ability/fa-dataability.md +++ b/en/application-dev/ability/fa-dataability.md @@ -23,12 +23,10 @@ Example URIs: - Cross-device communication: **dataability://***device_id***/***com.domainname.dataability.persondata***/***person***/***10* - Local-device communication: **dataability:///***com.domainname.dataability.persondata***/***person***/***10* - > **NOTE** -> +> > In the case of local-device communication, **device_id** is empty, and therefore, there are three slashes (/) after **dataability:**. - ## Available APIs **Table 1** Data ability lifecycle APIs @@ -140,7 +138,7 @@ Import the basic dependency packages and obtain the URI string for communicating The basic dependency packages include: - @ohos.ability.featureAbility -- @ohos.data.dataability +- @ohos.data.dataAbility - @ohos.data.rdb #### Data Ability API Development @@ -154,7 +152,7 @@ The basic dependency packages include: import featureAbility from '@ohos.ability.featureAbility' import ohos_data_ability from '@ohos.data.dataAbility' import ohos_data_rdb from '@ohos.data.rdb' - + var urivar = "dataability:///com.ix.DataAbility" var DAHelper = featureAbility.acquireDataAbilityHelper( urivar diff --git a/en/application-dev/ability/stage-ability.md b/en/application-dev/ability/stage-ability.md index e1d67a295b673453d7340fb20a40c81d8c7a7855..97e6caee0ca331c4fbc3ca6af309f006c5e4a325 100644 --- a/en/application-dev/ability/stage-ability.md +++ b/en/application-dev/ability/stage-ability.md @@ -42,6 +42,7 @@ The table below describes the APIs provided by the `AbilityStage` class, which h The table below describes the APIs provided by the `Ability` class. For details about the APIs, see [Ability](../reference/apis/js-apis-application-ability.md). **Table 2** Ability APIs + |API|Description| |:------|:------| |onCreate(want: Want, param: AbilityConstant.LaunchParam): void|Called when an ability is created.| @@ -58,7 +59,7 @@ To create Page abilities for an application in the stage model, you must impleme ``` import AbilityStage from "@ohos.application.AbilityStage" ``` -2. Implement the `AbilityStage` class. +2. Implement the `AbilityStage` class. The default relative path generated by the APIs is **entry\src\main\ets\Application\AbilityStage.ts**. ```ts export default class MyAbilityStage extends AbilityStage { onCreate() { @@ -70,9 +71,9 @@ To create Page abilities for an application in the stage model, you must impleme ```js import Ability from '@ohos.application.Ability' ``` -4. Implement the lifecycle callbacks of the `Ability` class. +4. Implement the lifecycle callbacks of the `Ability` class. The default relative path generated by the APIs is **entry\src\main\ets\MainAbility\MainAbility.ts**. - In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/window-guidelines.md). + In the `onWindowStageCreate(windowStage)` API, use `loadContent` to set the application page to be loaded. For details about how to use the `Window` APIs, see [Window Development](../windowmanager/application-window-stage.md). ```ts export default class MainAbility extends Ability { onCreate(want, launchParam) { @@ -87,7 +88,7 @@ To create Page abilities for an application in the stage model, you must impleme console.log("MainAbility onWindowStageCreate") windowStage.loadContent("pages/index").then((data) => { - console.log("MainAbility load content succeed with data: " + JSON.stringify(data)) + console.log("MainAbility load content succeed") }).catch((error) => { console.error("MainAbility load content failed with error: " + JSON.stringify(error)) }) @@ -107,7 +108,10 @@ To create Page abilities for an application in the stage model, you must impleme } ``` ### Obtaining AbilityStage and Ability Configurations -Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: +Both the `AbilityStage` and `Ability` classes have the `context` attribute. An application can obtain the context of an `Ability` instance through `this.context` to obtain the configuration details. + +The following example shows how an application obtains the bundle code directory, HAP file name, ability name, and system language through the `context` attribute in the `AbilityStage` class. The sample code is as follows: + ```ts import AbilityStage from "@ohos.application.AbilityStage" export default class MyAbilityStage extends AbilityStage { @@ -140,7 +144,7 @@ export default class MainAbility extends Ability { console.log("MainAbility ability name" + abilityInfo.name) let config = this.context.config - console.log("MyAbilityStage config language" + config.language) + console.log("MainAbility config language" + config.language) } } ``` diff --git a/en/application-dev/connectivity/socket-connection.md b/en/application-dev/connectivity/socket-connection.md index 15f38e97a75585520cf60534d03a4c1812001716..da5bea318e2b60da5641b9cf01ee73c926802c16 100644 --- a/en/application-dev/connectivity/socket-connection.md +++ b/en/application-dev/connectivity/socket-connection.md @@ -74,7 +74,7 @@ The implementation is similar for UDPSocket and TCPSocket. The following uses th console.log("on close") }); - // Bind the IP address and port number. + // Bind the local IP address and port number. let bindAddress = { address: '192.168.xx.xx', port: 1234, // Bound port, for example, 1234. diff --git a/en/application-dev/database/database-mdds-overview.md b/en/application-dev/database/database-mdds-overview.md index 2262558e38e892854b4de12cf124a88569cabf84..26efa7491805e871017db3593f5fa50d947717f5 100644 --- a/en/application-dev/database/database-mdds-overview.md +++ b/en/application-dev/database/database-mdds-overview.md @@ -1,8 +1,12 @@ -# Distributed Data Service Overview +# Distributed Data Service Overview -The distributed data service \(DDS\) implements distributed database collaboration across devices for applications. Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. +The distributed data service (DDS) implements distributed database collaboration across devices for applications. -## Basic Concepts +Applications save data to distributed databases by calling the DDS APIs. The DDS isolates data of different applications based on a triplet of account, application, and database to ensure secure data access. The DDS synchronizes application data between trusted devices to provide users with consistent data access experience on different devices. + +You do not need to care about the implementation of the database locking mechanism. + +## Basic Concepts - **KV data model** @@ -54,7 +58,7 @@ The distributed data service \(DDS\) implements distributed database collaborati The DDS provides the database backup capability. You can set **backup** to **true** to enable daily backup. If a distributed database is damaged, the DDS deletes the database and restores the most recent data from the backup database. If no backup database is available, the DDS creates one. The DDS can also back up encrypted databases. -## Working Principles +## Working Principles The DDS supports distributed management of application database data in the OpenHarmony system. Data can be synchronized between multiple devices with the same account, delivering a consistent user experience across devices. The DDS consists of the following: @@ -86,7 +90,7 @@ Applications call the DDS APIs to create, access, and subscribe to distributed d ![](figures/en-us_image_0000001183386164.png) -## Constraints +## Constraints - The DDS supports the KV data model only. It does not support foreign keys or triggers of the relational database. - The KV data model specifications supported by the DDS are as follows: diff --git a/en/application-dev/database/database-preference-guidelines.md b/en/application-dev/database/database-preference-guidelines.md index b65916cdd157419ef44b821c423a33ce272f9da0..fdb69297523057f5530ef2f885fbe3e0b5cbf5cf 100644 --- a/en/application-dev/database/database-preference-guidelines.md +++ b/en/application-dev/database/database-preference-guidelines.md @@ -2,45 +2,48 @@ > **NOTE** > -> This feature is supported since API Version 9. For the versions earlier than API Version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. +> This feature is supported since API Version 9. For the versions earlier than API version 9, use [Lightweight Storage](../reference/apis/js-apis-data-storage.md) APIs. ## When to Use -Preferences are ideal for storing data frequently used by applications, but not for storing a large amount of data or data with frequent changes. The application data is persistently stored on a device in the form of files. Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can perform data operations using the **Preferences** APIs. +Preferences are used for storing the data that is frequently used by applications, but not for storing a large amount of data or data frequently changed. The application data is persistently stored on a device in the form of files. -## Available APIs +Note that the instance accessed by an application contains all data of the file. The data is always loaded to the memory of the device until the application removes it from the memory. The application can call the **Preferences** APIs to manage data. -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support data persistence, modification, and query. In KV pairs, keys are of the string type, and values can be of the number, string, or Boolean type. For more APIs related to preferences, see [Preferences](../reference/apis/js-apis-data-preferences.md). +## Available APIs -### Creating a Preferences Instance +The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. -Create a **Preferences** instance for data operations. A **Preferences** instance is created after data is read from a specified file and loaded to the instance. +The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. -**Table 1** API for creating a **Preferences** instance +For details about **Preferences** APIs, see [Preferences](../reference/apis/js-apis-data-preferences.md). -| Package | API | Description | -| ----------------- | ------------------------------------------- | ------------------------------------------- | -| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\ | Obtains a **Preferences** instance for data operations.| +### Obtaining a **Preferences** Instance -### Writing Data +Obtain a **Preferences** instance for data operations. A **Preferences** instance is obtained after data is read from a specified file and loaded to the instance. -Call the **put()** method to add or modify data in a **Preferences** instance. +**Table 1** API for obtaining a **Preferences** instance -**Table 2** API for writing data +| Package | API | Description | +| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.data.preferences | getPreferences(context: Context, name: string): Promise\ | Obtains a **Preferences** instance.| -| Class | API | Description | -| ------- | -------------------------------------------------- | ----------------------------------------------- | -| Preferences | put(key: string, value: ValueType): Promise\ | Writes data with the value type of number, string, boolean, Array\, Array\, or Array\.| +### Accessing Data -### Reading Data +Call the **put()** method to add or modify data in a **Preferences** instance. Call the **get()** method to read data from a **Preferences** instance. -**Table 3** API for reading data +Call **getAll()** to obtain an **Object** instance that contains all KV pairs in a **Preferences** instance. + +**Table 2** APIs for accessing **Preferences** data + +| Class | API | Description | +| ----------- | ---------------------------------------------------------- | ------------------------------------------------------------ | +| Preferences | put(key: string, value: ValueType): Promise\ | Writes data to the **Preferences** instance. The value to write can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| Preferences | get(key: string, defValue: ValueType): Promise\ | Obtains data from the **Preferences** instance. The value to read can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| Preferences | getAll(): Promise | Obtains an **Object** instance that contains all KV pairs in the **Preferences** instance. | -| Class | API | Description | -| ------- | ---------------------------------------------------------- | ----------------------------------------------- | -| Preferences | get(key: string, defValue: ValueType): Promise\ | Obtains data with the value type of number, string, boolean, Array\, Array\, or Array\.| ### Storing Data Persistently @@ -48,18 +51,18 @@ Call the **flush()** method to write the cached data back to its text file for p **Table 4** API for data persistence -| Class | API | Description | -| ------- | ----------------------- | --------------------------------------- | -| Preferences | flush(): Promise\ | Writes data from the **Preferences** instance back to its file through an asynchronous thread.| +| Class | API | Description | +| ----------- | ----------------------- | ------------------------------------------- | +| Preferences | flush(): Promise\ | Flushes data from the **Preferences** instance to its file through an asynchronous thread.| ### Observing Data Changes -You can subscribe to data changes. When the value of the subscribed key is changed by **flush()**, a callback will be invoked to return the new data. +You can subscribe to data changes. When the value of the subscribed key is changed and saved by **flush()**, a callback will be invoked to return the new data. **Table 5** APIs for observing **Preferences** changes -| Class | API | Description | -| ------- | ------------------------------------------------------------ | -------------- | +| Class | API | Description | +| ----------- | ------------------------------------------------------------ | -------------- | | Preferences | on(type: 'change', callback: Callback<{ key : string }>): void | Subscribes to data changes.| | Preferences | off(type: 'change', callback: Callback<{ key : string }>): void | Unsubscribes from data changes. | @@ -69,57 +72,58 @@ Use the following APIs to delete a **Preferences** instance or data file. **Table 6** APIs for deleting **Preferences** -| Package | API | Description | -| ----------------- | ---------------------------------------------------- | ------------------------------------------------------------ | -| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\; | Deletes a **Preferences** instance from the cache and deletes its file from the device.| -| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\; | Removes a **Preferences** instance from the memory to release memory. +| Package | API | Description | +| --------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | +| ohos.data.preferences | deletePreferences(context: Context, name: string): Promise\ | Deletes a **Preferences** instance from the memory and its files from the device.| +| ohos.data.preferences | removePreferencesFromCache(context: Context, name: string): Promise\ | Removes a **Preferences** instance from the memory to release memory. | ## How to Develop 1. Import @ohos.data.preferences and related modules to the development environment. ```js - import data_preferences from '@ohos.data.preferences' + import data_preferences from '@ohos.data.preferences'; ``` -2. Create a **Preferences** instance. +2. Obtain a **Preferences** instance. Read the specified file and load its data to the **Preferences** instance for data operations. ```js - let promise = data_preferences.getPreferences(this.context, 'mystore') + let promise = data_preferences.getPreferences(this.context, 'mystore'); ``` 3. Write data. - Use the **put()** method of the **Preferences** class to write data to the cached **Preferences** instance. + Use the **preferences.put()** method to write data to the **Preferences** instance. ```js promise.then((preferences) => { - let putPromise = preferences.put('startup', 'auto') + let putPromise = preferences.put('startup', 'auto'); putPromise.then(() => { - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); }).catch((err) => { - console.info("Failed to put the value of startup with err: " + err) + console.info("Failed to put the value of 'startup'. Cause: " + err); }) }).catch((err) => { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences."); }) ``` 4. Read data. - Use the **get()** method of the **Preferences** class to read data. + Use the **preferences.get()** method to read data. ```js promise.then((preferences) => { - let getPromise = preferences.get('startup', 'default') + let getPromise = preferences.get('startup', 'default'); getPromise.then((value) => { - console.info("The value of startup is " + value) + console.info("The value of 'startup' is " + value); }).catch((err) => { - console.info("Failed to get the value of startup with err: " + err) + console.info("Failed to get the value of 'startup'. Cause: " + err); }) }).catch((err) => { - console.info("Failed to get the preferences")}) + console.info("Failed to get the preferences.") + }); ``` 5. Store data persistently. @@ -132,38 +136,38 @@ Use the following APIs to delete a **Preferences** instance or data file. 6. Observe data changes. - Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and the **flush()** method is executed, the observe callback will be invoked to return the change. + Specify an observer as the callback to subscribe to data changes for an application. When the value of the subscribed key is changed and saved by **flush()**, the observer callback will be invoked to return the new data. ```js var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key" + key + " changed."); } - preferences.on('change', observer) + preferences.on('change', observer); preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup with err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file with err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed to file successfully.") // Observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) }) ``` 7. Delete the specified file. - Use the **deletePreferences** method to delete the **Preferences** singleton of the specified file from the memory, and delete the specified file, its backup file, and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will occur. The deleted data and files cannot be restored. + Use the **deletePreferences** method to delete the **Preferences** instance and its persistent file and backup and corrupted files. After the specified files are deleted, the application cannot use that instance to perform any data operation. Otherwise, data inconsistency will be caused. The deleted data and files cannot be restored. ```js - let proDelete = data_preferences.deletePreferences(context, 'mystore') + let proDelete = data_preferences.deletePreferences(context, 'mystore'); proDelete.then(() => { - console.info("Data deleted successfully.") + console.info("Deleted data successfully."); }).catch((err) => { - console.info("Failed to delete data with err: " + err) + console.info("Failed to delete data. Cause: " + err); }) ``` diff --git a/en/application-dev/database/database-preference-overview.md b/en/application-dev/database/database-preference-overview.md index b26943b6109818b1ca9d74038f9df4471f69531e..4987b6e8494c738ef29e2f362b2acda43528bbb6 100644 --- a/en/application-dev/database/database-preference-overview.md +++ b/en/application-dev/database/database-preference-overview.md @@ -1,29 +1,34 @@ # Preferences Overview -Preferences are used for access and persistence operations on the data in the key-value structure. When an application accesses a **Preferences** instance, the data in the instance will be cached in the memory for faster access. The cached data can also be written back to the text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing persistent files. +Preferences are used to implement quick access and persistence of the data in the `key-value` structure. + +After an application obtains a **Preferences** instance, the data in the instance will be cached in the memory for faster access. + +The cached data can also be written to a text file for persistent storage. Since file read and write consume system resources, you are advised to minimize the frequency of reading and writing files. + +You do not need to care about the implementation of the database locking mechanism. ## Basic Concepts -- **Key-value data structure** +- **Key-value structure** - A type of data structure. The key is the unique identifier for a piece of data, and the value is the specific data being identified. + A type of data structure. The `Key` is the unique identifier for a piece of data, and the `Value` is the specific data being identified. - **Non-relational database** - A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) database management properties of relational data transactions. The data in a non-relational database is independent. + A database not in compliance with the atomicity, consistency, isolation, and durability (ACID) properties of relational data transactions. The data in a non-relational database is independent. The database that organizes data in the `key-value` structure is a non-relational database. ## Working Principles -When an application loads data from a **Preferences** file to a **Preferences** instance, the system stores the instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** file. - -When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the instance can be flushed to its **Preferences** file by calling the **flush()** method. +1. An application can load data from a **Preferences** persistent file to a **Preferences** instance. The system stores the **Preferences** instance in the memory through a static container. Each file of an application or process has only one **Preferences** instance in the memory, till the application removes the instance from the memory or deletes the **Preferences** persistent file. +2. When obtaining a **Preferences** instance, the application can read data from or write data to the instance. The data in the `Preferences` instance can be flushed to its **Preferences** persistent file by calling the **flush()** method. -**Figure 1** How **Preferences** work +**Figure 1** Working mechanism ![](figures/preferences.png) ## Constraints - **Preferences** instances are loaded to the memory. To minimize non-memory overhead, the number of data records stored in a **Preferences** instance cannot exceed 10,000. Delete the instances that are no longer used in a timely manner. -- The key in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes. -- The value of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty. +- The `Key` in key-value pairs is of the string type. It cannot be empty or exceed 80 bytes. +- The `Value` of the string type in key-value pairs can be empty, but cannot exceed 8192 bytes if not empty. diff --git a/en/application-dev/database/database-relational-overview.md b/en/application-dev/database/database-relational-overview.md index 2363e12b7c389845ba9586cf332080e8600e58c0..c78034c76f63fe1f6e8bd338f9595206f8c5eea0 100644 --- a/en/application-dev/database/database-relational-overview.md +++ b/en/application-dev/database/database-relational-overview.md @@ -2,6 +2,8 @@ The relational database (RDB) manages data based on relational models. With the underlying SQLite database, the RDB provides a complete mechanism for managing local databases. To satisfy different needs in complicated scenarios, the RDB offers a series of methods for performing operations such as adding, deleting, modifying, and querying data, and supports direct execution of SQL statements. +You do not need to care about the implementation of the database locking mechanism. + ## Basic concepts - **RDB** diff --git a/en/application-dev/database/figures/preferences.png b/en/application-dev/database/figures/preferences.png index ab91e2d4fb3019ca3f48a195041c9b19bdaec830..be3c6feef3c1f8d9da83e5d3c0065655bd07cb57 100644 Binary files a/en/application-dev/database/figures/preferences.png and b/en/application-dev/database/figures/preferences.png differ diff --git a/en/application-dev/dfx/hiappevent-guidelines.md b/en/application-dev/dfx/hiappevent-guidelines.md index 54199719cd93a523d8f2b0af14c12578997a02a2..48f725e080441281cd2e88820eeacc6032a2dbab 100644 --- a/en/application-dev/dfx/hiappevent-guidelines.md +++ b/en/application-dev/dfx/hiappevent-guidelines.md @@ -2,89 +2,164 @@ ## When to Use -The event logging function helps applications to log various information generated during running. +The event logging function helps applications log various information generated during running. ## Available APIs JS application event logging APIs are provided by the **hiAppEvent** module. -**Table 1** APIs for event logging +The following table provides only a brief description of related APIs. For details, see [HiAppEvent](../reference/apis/js-apis-hiappevent.md). -| API | Return Value | Description | -| ------------------------------------------------------------ | -------------- | ------------------------------------------------------------ | -| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | void | Logs application events in asynchronous mode. This method uses an asynchronous callback to return the result. | -| write(string eventName, EventType type, object keyValues): Promise\ | Promise\ | Logs application events in asynchronous mode. This method uses a promise to return the result. | +**Table 1** APIs for application event logging -When an asynchronous callback is used, the return value can be processed directly in the callback. When a promise is used, the return value can also be processed in the promise in a similar way. For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes). +| API | Description | +| ------------------------------------------------------------ | ------------------------------------------------------------ | +| write(string eventName, EventType type, object keyValues, AsyncCallback\ callback): void | Logs application events in asynchronous mode. This API uses an asynchronous callback to return the result. | +| write(string eventName, EventType type, object keyValues): Promise\ | Logs application events in asynchronous mode. This API uses a promise to return the result. | +| write(AppEventInfo info, AsyncCallback\ callback): void | Logs application events by domain in asynchronous mode. This API uses an asynchronous callback to return the result.| +| write(AppEventInfo info): Promise\ | Logs application events by domain in asynchronous mode. This API uses a promise to return the result.| -**Table 2** APIs for event logging configuration +When an asynchronous callback is used, the return value can be processed directly in the callback. -| API | Return Value | Description | -| ------------------------------ | ------------ | ------------------------------------------------------------ | -| configure(ConfigOption config) | boolean | Sets the configuration options for application event logging.
The value **true** indicates that the operation is successful, and value **false** indicates the opposite. | +If a promise is used, the return value can also be processed in the promise in a similar way. -## Event Verification Result Codes +For details about the result codes, see [Event Verification Result Codes](#event-verification-result-codes). -| Result Code | Cause | Check Rule | Processing Method | -| ----------- | ---------------------------------- | ------------------------------------------------------------ | ------------------------------------------------------------ | -| 0 | None | Event verification is successful. | Event logging is normal. No action is required. | -| -1 | Invalid event name | The event name is not empty and contains a maximum of 48 characters.
The event name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The event name does not start with a digit or underscore (_). | Ignore this event and do not perform logging. | -| -2 | Invalid event parameter type | The event name must be a string.
The event type must be a number.
The key value must be an object. | Ignore this event and do not perform logging. | -| -99 | Application event logging disabled | The application event logging function is disabled. | Ignore this event and do not perform logging. | -| -100 | Unknown error | None | Ignore this event and do not perform logging. | -| 1 | Invalid key name | The key name is not empty and contains a maximum of 16 characters.
The key name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore (\_).
The key name does not start with a digit or underscore (\_).
The key name does not end with an underscore (_). | Ignore the key-value pair and continue to perform logging. | -| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. | -| 3 | Invalid value type | The supported value types vary depending on the programming language:
boolean, number, string, or Array [basic element] | Ignore the key-value pair and continue to perform logging. | -| 4 | Value too long | The value can contain a maximum of 8*1024 characters. | Ignore the key-value pair and continue to perform logging. | -| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. | -| 6 | Excess elements in a list value | The number of elements in a list value must be less than or equal to 100. | Truncate the list with only the first 100 elements retained, and continue to perform logging. | -| 7 | Invalid list value | A list value can only be a basic element.
The elements in a list value must be of the same type. | Ignore the key-value pair and continue to perform logging. | +**Table 2** APIs for event logging configuration +| API | Description | +| --------------------------------------- | ---------------------------------------------------- | +| configure(ConfigOption config): boolean | Sets the configuration options for application event logging.| -## How to Develop +**Table 3** APIs for watcher management -In this example, an application event is logged after the application startup execution page is loaded. +| API | Description | +| -------------------------------------------------- | -------------------- | +| addWatcher(Watcher watcher): AppEventPackageHolder | Adds an event watcher.| +| removeWatcher(Watcher watcher): void | Removes an event watcher.| -1. Create a JS application project. In the displayed Project window, choose **entry > src > main** > **js** > **default** > **pages > index**, and double-click index.js. Add the code to log the initial application event after page loading. The sample code is as follows: +**Table 4** APIs for clearing logging data - ```js - import hiAppEvent from '@ohos.hiAppEvent' +| API | Description | +| ----------------- | -------------------- | +| clearData(): void | Clears local logging data.| + +### Event Verification Result Codes + +| Result Code| Cause | Verification Rules | Handling Method | +| ------ | ----------------------------- | ------------------------------------------------------------ | ---------------------------------------------------------- | +| 0 | N/A | Event verification is successful. | Event logging is normal. No action is required. | +| -1 | Invalid event name | The name is not empty and contains a maximum of 48 characters.
The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).
The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. | +| -2 | Invalid event parameter type | The event name must be a string.
The event type must be a number.
The event parameter must be an object.| Ignore this event and do not perform logging. | +| -4 | Invalid event domain name | The name is not empty and contains a maximum of 32 characters.
The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).
The name does not start with a digit or underscore \(_).| Ignore this event and do not perform logging. | +| -99 | Application event logging disabled | Application event logging is disabled. | Ignore this event and do not perform logging. | +| -100 | Unknown error | None. | Ignore this event and do not perform logging. | +| 1 | Invalid key name | The name is not empty and contains a maximum of 16 characters.
The name consists of only the following characters: digits (0 to 9), letters (a to z), and underscore \(_).
The name does not start with a digit or underscore \(_).
The name does not end with an underscore \(_).| Ignore the key-value pair and continue to perform logging. | +| 2 | Invalid key type | The key must be a string. | Ignore the key-value pair and continue to perform logging. | +| 3 | Invalid value type | The supported value types vary depending on the programming language:
boolean, number, string, or Array [basic element]| Ignore the key-value pair and continue to perform logging. | +| 4 | Invalid length for values of the string type| For a value of the string type, the maximum length is 8*1024 characters. | Truncate the value with the first 8*1024 characters retained, and continue to perform logging.| +| 5 | Excess key-value pairs | The number of key-value pairs must be less than or equal to 32. | Ignore the excess key-value pairs and continue to perform logging. | +| 6 | Invalid number of elements in values of the array type | For a value of the array type, the number of elements must be less than or equal to 100. | Truncate the array with the first 100 elements retained, and continue to perform logging. | +| 7 | Invalid parameters in values of the array type | For a value of the array type, all the parameters must be of the same type, which can only be boolean, number, or string.| Ignore the key-value pair and continue to perform logging. | + +## Development Procedure + +The following uses a one-time event watcher as an example to illustrate the development procedure. + +1. Create an eTS application project. In the displayed **Project** window, choose **entry** > **src** > **main** > **ets** > **pages** > **index.ets**, and double-click **index.ets**. Then, add three buttons to simulate the process of watching for application events. Wherein, button 1 is used to invoke application event logging, button 2 to add an event watcher that automatically triggers a callback, and button 3 to remove the watcher. The complete sample code is as follows: + + ```ts + import hiAppEvent from '@ohos.hiAppEvent'; - export default { - data: { - title: "" - }, - onInit() { - this.title = this.$t('strings.world'); + @Entry + @Component + struct Index { + @State message: string = 'Hello World' - // 1. Callback mode - hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}, (err, value) => { - if (err) { - console.error(`failed to write event because ${err.code}`); - return; + build() { + Row() { + Column() { + Text(this.message) + .fontSize(50) + .fontWeight(FontWeight.Bold) + + Button("1 writeTest").onClick(()=>{ + hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" } - console.log(`success to write event: ${value}`); - }); + }).then((value) => { + console.log(`HiAppEvent success to write event: ${value}`); + }).catch((err) => { + console.error(`HiAppEvent failed to write event because ${err.code}`); + }); + }) - // 2. Promise mode - hiAppEvent.write("start_event", hiAppEvent.EventType.BEHAVIOR, {"int_data":100, "str_data":"strValue"}) - .then((value) => { - console.log(`success to write event: ${value}`); - }).catch((err) => { - console.error(`failed to write event because ${err.code}`); - }); - - // 3. Set the application event logging switch. - hiAppEvent.configure({ - disable: true - }); + Button("2 addWatcherTest").onClick(()=>{ + hiAppEvent.addWatcher({ + name: "watcher1", + appEventFilters: [{ domain: "test_domain" }], + triggerCondition: { + row: 2, + size: 1000, + timeOut: 2 + }, + onTrigger: function (curRow, curSize, holder) { + if (holder == null) { + console.error("HiAppEvent holder is null"); + return; + } + let eventPkg = null; + while ((eventPkg = holder.takeNext()) != null) { + console.info("HiAppEvent eventPkg.packageId=" + eventPkg.packageId); + console.info("HiAppEvent eventPkg.row=" + eventPkg.row); + console.info("HiAppEvent eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("HiAppEvent eventPkg.data=" + eventInfo); + } + } + } + }); + }) - // 4. Set the maximum size of the event file storage directory. The default value is 10M. - hiAppEvent.configure({ - maxStorage: '100M' - }); + Button("3 removeWatcherTest").onClick(()=>{ + hiAppEvent.removeWatcher({ + name: "watcher1" + }) + }) + } + .width('100%') } + .height('100%') + } } ``` -2. Tap the run button on the application UI to run the project. +2. Touch the run button on the IDE to run the project. + +3. Touch button 1 on the application UI to start application event logging. If the logging is successful, you'll see the following message in the **Log** window: + + ``` + success to write event: 0 + ``` + +4. On the application UI, touch button 2 to add an event watcher, and touch button 1 for multiple times to perform application event logging. If any callback trigger condition (event count, event data size, and timeout duration) is met, the event watcher will invoke a callback and the event package obtained through the callback will be displayed in the **Log** window. + + ``` + HiAppEvent eventPkg.packageId=0 + HiAppEvent eventPkg.row=2 + HiAppEvent eventPkg.size=308 + HiAppEvent eventPkg.data={"domain_":"test_domain","name_":"test_event","type_":1,"time_":1502096107556,"tz_":"+0000","pid_":4204,"tid_":4223,"int_data":100,"str_data":"strValue"} + ``` + +5. On the application UI, touch button 3 to remove the event watcher. Then, touch button 1 for multiple times to perform application event logging. In such a case, there will be no log information about the callback invoked by the event watcher. + +## Samples + +The following sample is provided to help you better understand how to develop the application event logging feature: + +- [`JsDotTest` (JS) (API8)](https://gitee.com/openharmony/applications_app_samples/tree/master/DFX/JsDotTest) diff --git a/en/application-dev/dfx/hiappevent-overview.md b/en/application-dev/dfx/hiappevent-overview.md index 2a5e36f879a922f3d6bf845e700068c2a299b337..088f3624b0c9638dd5137e1460b3cc832c290de9 100644 --- a/en/application-dev/dfx/hiappevent-overview.md +++ b/en/application-dev/dfx/hiappevent-overview.md @@ -2,10 +2,10 @@ HiAppEvent provides event logging APIs for applications to log the fault, statistical, security, and user behavior events reported during running. Based on event information, you will be able to analyze the running status of your application. -The HiAppEvent module of OpenHarmony can be used to develop application event services and provide functions related to application events, including flushing application events to a disk and querying historical application event data. +The HiAppEvent module can be used to develop application event-related functions, including flushing application events to a disk and querying historical application events. ## Basic Concepts -- **Logging** +**Logging** - Logs changes caused by user operations to provide service data for development, product, and O&M analysis. + A function that logs changes caused by user operations to provide service data for development, product, and O&M analysis. \ No newline at end of file diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png index d044d5d829ab1ad805f4ffcda19837f867b976fc..a044e797ef1429b5ef5cf8cf99950697e7bb1e98 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655128998.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png index 2dd664a2b25751cc32bd81927b30036d5cc4f351..408bf7d9864352d03f1603b0e1c68741401e016f 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129041.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png index 7d3222667d7bffe89a148dc3b08861a86c43713e..6f5469a6374e6da2ca48c03708fc59c74f556adb 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129232.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png index b42f2e3896d334d86e89b867cf3428782f88d600..d4197e195f3b4f8ca0fc05965af7457ece28decc 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129333.png differ diff --git a/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png index 2dda1a5cfca8d75d70e40b8bc0d555faade04583..b106ff353bddede943257f62a0a71403b1b5db4d 100644 Binary files a/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png and b/en/application-dev/quick-start/figures/en-us_image_0000001655129398.png differ diff --git a/en/application-dev/quick-start/full-sdk-switch-guide.md b/en/application-dev/quick-start/full-sdk-switch-guide.md index 4c20e429bdef97ab0503614d01f1807e56eedb13..a687d69b739e12893aff91fb2e6939eb1b32aad0 100644 --- a/en/application-dev/quick-start/full-sdk-switch-guide.md +++ b/en/application-dev/quick-start/full-sdk-switch-guide.md @@ -1,23 +1,22 @@ # Guide to Switching to Full SDK -Both the public SDK and full SDK are toolkits for application development. - -The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications. +Both the public SDK and full SDK are toolkits for application development.
The public SDK is intended for application developers and provided as standard in DevEco Studio. It does not contain system APIs – APIs required by system applications. The full SDK is intended for original equipment manufacturers (OEMs) and provided separately. It contains system APIs. The SDK of API version 8 provided in DevEco Studio is a public SDK. If your project depends on any system API, such as the **animator** component, **xcomponent** component, or APIs in **@ohos.application.abilityManager.d.ts**, **@ohos.application.formInfo.d.ts**, or **@ohos.bluetooth.d.ts**, switch to the full SDK by performing the following steps. -## Downloading the Full SDK (of 3.1.1 Release in this example) - -Manually download the full SDK. For details, see the source code acquisition section in [OpenHarmony 3.1.1 Release](https://gitee.com/openharmony/docs/blob/master/en/release-notes/OpenHarmony-v3.1.1-release.md). - -![image-20220613161049897](figures/en-us_image_0000001655128646.png) +> **NOTE** +> +> The screenshots in this document are for reference only. +## Downloading the Full SDK +Manually download the system-specific full SDK package from the mirror. For details, see [Release Notes](../../release-notes/OpenHarmony-v3.2-beta2.md). +## Checking the Local SDK Location -## Checking the Local SDK Location
In this example, an eTS project is used. For a JS project, replace **ets** with **js**. +In this example, an eTS project is used. For a JS project, replace **ets** with **js**. In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the location of the local SDK. @@ -38,61 +37,58 @@ In DevEco Studio, choose **Tools** > **OpenHarmony SDK Manager** to check the lo Note: The criteria for identifying system APIs are subject to the released API documentation. - - -2. Replace the SDK. The following uses full SDK 3.1.6.6 for Windows as an example. +2. Replace the SDK. The following uses public-SDK-3.x.x.x for Windows as an example. - - - a. Decompress the downloaded full SDK file: `ets-windows-3.1.6.5-Release.zip` + a. Decompress the downloaded full SDK file: `ets-windows-3.x.x.x-Release.zip` ![image-20220613165018184](figures/en-us_image_0000001655129264.png) b. Replace the SDK files. - Back up the local SDK files. (Copy and rename the version number directory in the **ets** directory, or copy the entire **ets** directory to another local path.) + Back up the local SDK files. (Copy and rename the version directory in the **ets** directory, or copy the entire **ets** directory to another local path.) Go to the obtained location of the local installed SDK and back up the files therein. ![image-20220613161352157](figures/en-us_image_0000001655129041.png) - Note: The name of the backup version number directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version number directory is **3.1.6.6_backup**. + Note: The name of the backup version directory must be different from the value of **version** field in the **oh-uni-package.json** file. In the example below, the name of the backup version directory is **3.x.x.x_backup**. ![image-20220613165018184](figures/en-us_image_0000001655129398.png) - The configuration in the **oh-uni-package.json** file is as follows: + The configuration in the **oh-uni-package.json** file is as follows, where the value of `apiVersion` is subject to the API version of the SDK, and the value of `version` is subject to the version number in the SDK file. ``` { - "apiVersion": "8", + "apiVersion": "X", "displayName": "Ets", "meta": { "metaVersion": "3.0.0" }, "path": "ets", "releaseType": "Release", - "version": "3.1.6.6" + "version": "3.x.x.x" } ``` + - **Delete all files in the original SDK (3.1.6.6) directory.** Failure to do so may result in some files being unable to be overwritten. + Delete all files in the original SDK (3.x.x.x) directory. Failure to do so may result in some files being unable to be overwritten. Copy the full SDK to the location of the local SDK. - Copy all files in the **ets** directory in the full SDK to the **ets\3.1.6.6** directory in the location of the local SDK. + Copy all files in the **ets** directory in the full SDK to the **ets\*3.x.x.x*** directory in the location of the local SDK. Change the value of **version** in the **oh-uni-package.json** file to the current SDK version number. - In the **3.1.6.6\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the **npm install** command to download the **node_modules** dependency package. + In the ***3.x.x.x*\build-tools\ets-loader** directory, open the **cmd/powerShell** window and run the `npm install` command to download the **node_modules** dependency package. ![image-20220613171111405](figures/en-us_image_0000001655129333.png) c. Check for system APIs. - + ![image-20220613213038104](figures/en-us_image_0000001655129372.png) diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md index 3f1c11258560d916d54490ff4e2c0c23becdd410..09a65cea53e545c3afb58924b498512242a9285f 100644 --- a/en/application-dev/reference/apis/Readme-EN.md +++ b/en/application-dev/reference/apis/Readme-EN.md @@ -216,6 +216,7 @@ - [@ohos.pasteboard](js-apis-pasteboard.md) - [@ohos.screenLock](js-apis-screen-lock.md) - [@ohos.systemTime](js-apis-system-time.md) + - [@ohos.systemTimer](js-apis-system-timer.md) - [@ohos.wallpaper](js-apis-wallpaper.md) - [Timer](js-apis-timer.md) diff --git a/en/application-dev/reference/apis/js-apis-data-preferences.md b/en/application-dev/reference/apis/js-apis-data-preferences.md index 560696c1ca48cb404aa0a29e95f8c3c1a1841198..6803d4edf50fc219bc37c4be79fc71687dd91457 100644 --- a/en/application-dev/reference/apis/js-apis-data-preferences.md +++ b/en/application-dev/reference/apis/js-apis-data-preferences.md @@ -1,15 +1,18 @@ # Preferences -Preferences provide capabilities for processing data in the form of key-value (KV) pairs and support lightweight data persistence, modification, and query. In KV pairs, the keys are of the string type, and the values can be of the number, string, Boolean, Array\, Array\, or Array\ type. +The **Preferences** module provides APIs for processing data in the form of key-value (KV) pairs and supports persistence of the KV pairs when required. + +The key is of the string type, and the value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values. > **NOTE**
+> > The initial APIs of this module are supported since API version 9. Newly added APIs will be marked with a superscript to indicate their earliest API version. ## Modules to Import -```ts +```js import data_preferences from '@ohos.data.preferences'; ``` @@ -17,36 +20,39 @@ import data_preferences from '@ohos.data.preferences'; **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Name| Type| Readable| Writable| Description| -| -------- | -------- | -------- | -------- | -------- | -| MAX_KEY_LENGTH | string | Yes| No| Maximum length of a key. It must be less than 80 bytes.| -| MAX_VALUE_LENGTH | string | Yes| No| Maximum length of a value. It must be less than 8192 bytes.| +| Name | Type| Readable| Writable| Description | +| ---------------- | -------- | ---- | ---- | --------------------------------------- | +| MAX_KEY_LENGTH | string | Yes | No | Maximum length of a key. The key must be less than 80 bytes. | +| MAX_VALUE_LENGTH | string | Yes | No | Maximum length of a value. The value must be less than 8192 bytes.| ## data_preferences.getPreferences getPreferences(context: Context, name: string, callback: AsyncCallback<Preferences>): void -Reads a **Preferences** persistence file and loads data to the **Preferences** instance for data operations. This API uses an asynchronous callback to return the result. - +Obtains a **Preferences** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<[Preferences](#preferences)> | Yes| Callback used to return the result.| + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------------------ | ---- | ------------------------------------------------------------ | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance. | +| callback | AsyncCallback<[Preferences](#preferences)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **object** is the **Preferences** instance obtained. Otherwise, **err** is an error code.| **Example** -```ts -data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { + +```js +var preferences = null; +data_preferences.getPreferences(this.context, 'mystore', function (err, object) { if (err) { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences. Cause: " + err); return; } - console.info("Got preferences successfully.") + preferences = object; + console.info("Got the preferences successfully."); }) ``` @@ -55,28 +61,31 @@ data_preferences.getPreferences(this.context, 'mystore', function (err, preferen getPreferences(context: Context, name: string): Promise<Preferences> -Reads a **Preferences** persistence file and loads data to the **Preferences** instance for data operations. This API uses a promise to return the result. +Obtains a **Preferences** instance. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | -------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<[Preferences](#preferences)> | Promise used to return the result.| +| Type | Description | +| ------------------------------------------ | ---------------------------------- | +| Promise<[Preferences](#preferences)> | Promise used to return the **Preferences** instance obtained.| **Example** -```ts + +```js +var preferences = null; let promise = data_preferences.getPreferences(this.context, 'mystore') -promise.then((preferences) => { - console.info("Got preferences successfully.") +promise.then((object) => { + preferences = object; + console.info("Got the preferences successfully."); }).catch((err) => { - console.info("Failed to get the preferences") + console.info("Failed to get the preferences. Cause: " + err); }) ``` @@ -85,26 +94,29 @@ promise.then((preferences) => { deletePreferences(context: Context, name: string, callback: AsyncCallback<void>): void -Deletes a **Preferences** singleton instance, the persistence file and backup file, and corrupted files from the memory. -Once a **Preferences** persistence file is deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result. +Deletes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result. + +If the **Preferences** instance has a persistent file, this API also deletes the persistent file. + +The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to delete. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js data_preferences.deletePreferences(this.context, 'mystore', function (err) { if (err) { - console.info("Failed to delete data, err: " + err) + console.info("Failed to delete the preferences. Cause: " + err); return } - console.info("Deleted preferences successfully.") + console.info("Deleted the preferences successfully." ); }) ``` @@ -113,29 +125,32 @@ data_preferences.deletePreferences(this.context, 'mystore', function (err) { deletePreferences(context: Context, name: string): Promise<void> -Deletes a **Preferences** singleton instance, the persistence file and backup file, and corrupted files from the memory. -Once a **Preferences** persistence file is deleted, the **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the result. +Deletes a **Preferences** instance from the memory. This API uses a promise to return the result. + +If the **Preferences** instance has a persistent file, this API also deletes the persistent file. + +The deleted **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | -------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to delete.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts +```js let promise = data_preferences.deletePreferences(this.context, 'mystore') promise.then(() => { - console.info("Deleted preferences successfully.") + console.info("Deleted the preferences successfully."); }).catch((err) => { - console.info("Failed to delete preferences, err: " + err) + console.info("Failed to delete the preferences. Cause: " + err); }) ``` @@ -144,27 +159,27 @@ promise.then(() => { removePreferencesFromCache(context: Context, name: string, callback: AsyncCallback<void>): void -Removes a **Preferences** singleton instance from the memory. +Removes a **Preferences** instance from the memory. This API uses an asynchronous callback to return the result. -When a **Preferences** singleton instance is removed, this instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses an asynchronous callback to return the result. +The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------------------- | ---- | ---------------------------------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to remove. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js data_preferences.removePreferencesFromCache(this.context, 'mystore', function (err) { if (err) { - console.info("Failed to remove preferences from cache, err: " + err) - return + console.info("Failed to remove the preferences. Cause: " + err); + return; } - console.info("Removed preferences from cache successfully.") + console.info("Removed the preferences successfully."); }) ``` @@ -173,62 +188,65 @@ data_preferences.removePreferencesFromCache(this.context, 'mystore', function (e removePreferencesFromCache(context: Context, name: string): Promise<void> -Removes a **Preferences** singleton instance from the memory. +Removes a **Preferences** instance from the memory. This API uses a promise to return the result. -When a **Preferences** singleton instance is removed, this instance cannot be used for data operations. Otherwise, data inconsistency will occur. This API uses a promise to return the execution result. +The removed **Preferences** instance cannot be used for data operations. Otherwise, data inconsistency will be caused. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | context | [Context](js-apis-ability-context.md) | Yes| Context of the application or function.| - | name | string | Yes| Name of the **Preferences** instance persistence file.| +| Name | Type | Mandatory| Description | +| ------- | ------------------------------------- | ---- | -------------------------- | +| context | [Context](js-apis-ability-context.md) | Yes | Application context. | +| name | string | Yes | Name of the **Preferences** instance to remove.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts +```js let promise = data_preferences.removePreferencesFromCache(this.context, 'mystore') promise.then(() => { - console.info("Removed preferences from cache successfully.") + console.info("Removed the preferences successfully."); }).catch((err) => { - console.info("Failed to remove preferences from cache, err: " + err) + console.info("Failed to remove the preferences. Cause: " + err); }) ``` ## Preferences -Provides APIs for obtaining and modifying storage data. +Provides methods for obtaining and modifying data. + +Before calling any method of **Preferences**, you must obtain a **Preferences** instance by using [data_preferences.getPreferences](#data_preferencesgetpreferences). ### get get(key: string, defValue: ValueType, callback: AsyncCallback<ValueType>): void -Obtains the value of a key. If the value is null or a non-default value, the default data is returned. This API uses an asynchronous callback to return the result. +Obtains the value of a key. This API uses an asynchronous callback to return the result. If the value is **null** or is not the type of the default value, the default value is returned. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| key | string | Yes| Key of the data to obtain. It cannot be empty.| -| defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array. -| callback | AsyncCallback<ValueType> | Yes| Callback used to return the result.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| callback | AsyncCallback<[ValueType](#valuetype)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is** undefined** and **data** is the value obtained. Otherwise, **err** is an error code.| **Example** -```ts -preferences.get('startup', 'default', function(err, value) { + +```js +preferences.get('startup', 'default', function(err, data) { if (err) { - console.info("Failed to get the value of startup, err: " + err) - return + console.info("Failed to get the value of 'startup'. Cause: " + err); + return; } - console.info("The value of startup is " + value) + console.info("Got the value of 'startup'. Data: " + data); }) ``` @@ -237,28 +255,29 @@ preferences.get('startup', 'default', function(err, value) { get(key: string, defValue: ValueType): Promise<ValueType> -Obtains the value of a key. If the value is null or a non-default value, the default data is returned. This API uses a promise to return the result. +Obtains the value of a key. This API uses a promise to return the result. If the value is **null** or is not the type of the default value, the default value is returned. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -- **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to obtain. It cannot be empty.| - | defValue | [ValueType](#valuetype) | Yes| Default value to be returned. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array. + **Parameters** +| Name | Type | Mandatory| Description | +| -------- | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to obtain. It cannot be empty. | +| defValue | [ValueType](#valuetype) | Yes | Default value to be returned. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<ValueType> | Promise used to return the result.| + +| Type | Description | +| ----------------------------------- | ----------------------------- | +| Promise<[ValueType](#valuetype)> | Promise used to return the value obtained.| **Example** -```ts -let promise = preferences.get('startup', 'default') -promise.then((value) => { - console.info("The value of startup is " + value) +```js +let promise = preferences.get('startup', 'default'); +promise.then((data) => { + console.info("Got the value of 'startup'. Data: " + data); }).catch((err) => { - console.info("Failed to get the value of startup, err: " + err) + console.info("Failed to get the value of 'startup'. Cause: " + err); }) ``` @@ -266,25 +285,26 @@ promise.then((value) => { getAll(callback: AsyncCallback<Object>): void; -Obtains the **Object** instance that contains all KV pairs. +Obtains an **Object** instance that contains all KV pairs. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<Object> | Yes| Callback used to return the **Object** instance obtained.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| callback | AsyncCallback<Object> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **value** is the **Object** instance obtained. Otherwise, **err** is an error code.| **Example** -```ts + +```js preferences.getAll(function (err, value) { if (err) { - console.info("getAll failed, err: " + err) - return + console.info("Failed to get all KV pairs. Cause: " + err); + return; } - let keys = Object.keys(value) - console.info('getAll keys = ' + keys) - console.info("getAll object = " + JSON.stringify(value)) + let allKeys = Object.keys(value); + console.info("getAll keys = " + allKeys); + console.info("getAll object = " + JSON.stringify(value)); }); ``` @@ -293,24 +313,24 @@ preferences.getAll(function (err, value) { getAll(): Promise<Object> -Obtains the **Object** instance that contains all KV pairs. +Obtains an **Object** instance that contains all KV pairs. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<Object> | Promise used to return the **Object** instance obtained.| +| Type | Description | +| --------------------- | ------------------------------------------- | +| Promise<Object> | Promise used to return the **Object** instance obtained.| **Example** -```ts -let promise = preferences.getAll() +```js +let promise = preferences.getAll(); promise.then((value) => { - let keys = Object.keys(value) - console.info('getAll keys = ' + keys) - console.info("getAll object = " + JSON.stringify(value)) + let allKeys = Object.keys(value); + console.info('getAll keys = ' + allKeys); + console.info("getAll object = " + JSON.stringify(value)); }).catch((err) => { - console.info("getAll failed, err: " + err) + console.info("Failed to get all KV pairs. Cause: " + err); }) ``` @@ -318,25 +338,25 @@ promise.then((value) => { put(key: string, value: ValueType, callback: AsyncCallback<void>): void -Puts a new value to this **Preferences** instance and its persistence file. This API uses an asynchronous callback to return the result. +Writes data to this **Preferences** instance. This API uses an asynchronous callback to return the result. You can use [flush](#flush) to make the **Preferences** instance persistent. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is undefined. Otherwise, **err** is an error code. | **Example** -```ts +```js preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); }) ``` @@ -345,28 +365,28 @@ preferences.put('startup', 'auto', function (err) { put(key: string, value: ValueType): Promise<void> -Puts a new value to this **Preferences** instance and its persistence file. This API uses a promise to return the result. +Writes data to this **Preferences** instance. This API uses a promise to return the result. You can use [flush](#flush) to make the **Preferences** instance persistent. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data. It cannot be empty.| - | value | [ValueType](#valuetype) | Yes| New value to store. It can be a number, a string, a Boolean value, an array of numbers, an array of strings, or a Boolean array.| +| Name| Type | Mandatory| Description | +| ------ | ----------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data. It cannot be empty. | +| value | [ValueType](#valuetype) | Yes | Value to write. The value can be a number, a string, a Boolean value, or an array of numbers, strings, or Boolean values.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts -let promise = preferences.put('startup', 'auto') +```js +let promise = preferences.put('startup', 'auto'); promise.then(() => { - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); }).catch((err) => { - console.info("Failed to put the value of startup, err: " + err) + console.info("Failed to put the value of 'startup'. Cause: " + err); }) ``` @@ -375,27 +395,27 @@ promise.then(() => { has(key: string, callback: AsyncCallback<boolean>): void -Checks whether this **Preferences** instance contains data with a given key. This API uses an asynchronous callback to return the result. +Checks whether this **Preferences** instance contains a KV pair of the given key. This API uses an asynchronous callback to return the result.. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| - | callback | AsyncCallback<boolean> | Yes| Callback used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| +| Name | Type | Mandatory| Description | +| -------- | ---------------------------- | ---- | ------------------------------------------------------------ | +| key | string | Yes | Key of the data to check. It cannot be empty. | +| callback | AsyncCallback<boolean> | Yes | Callback invoked to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** -```ts +```js preferences.has('startup', function (err, isExist) { if (err) { - console.info("Failed to check the key of startup, err: " + err) - return + console.info("Failed to check the key 'startup'. Cause: " + err); + return; } if (isExist) { - console.info("The key of startup is contained.") + console.info("The key 'startup' is contained."); } else { - console.info("The key of startup is not contained.") + console.info("The key 'startup' is not contained."); } }) ``` @@ -405,31 +425,32 @@ preferences.has('startup', function (err, isExist) { has(key: string): Promise<boolean> -Checks whether this **Preferences** instance contains data with a given key. This API uses a promise to return the result. +Checks whether this **Preferences** instance contains data with the given key. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the data to check. It cannot be empty.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the data to check. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<boolean> | Promise used to return the result. It returns **true** if the **Preferences** instance contains data with the given key and returns **false** otherwise.| +| Type | Description | +| ---------------------- | ------------------------------------------------------------ | +| Promise<boolean> | Promise used to return the result. If the **Preferences** instance contains the KV pair, **true** will be returned. Otherwise, **false** will be returned.| **Example** -```ts -let promise = preferences.has('startup') + +```js +let promise = preferences.has('startup'); promise.then((isExist) => { if (isExist) { - console.info("The key of startup is contained.") + console.info("The key 'startup' is contained."); } else { - console.info("The key of startup is not contained.") + console.info("The key 'startup' is not contained."); } }).catch((err) => { - console.info("Failed to check the key of startup, err: " + err) + console.info("Failed to check the key 'startup'. Cause: " + err); }) ``` @@ -438,24 +459,24 @@ promise.then((isExist) => { delete(key: string, callback: AsyncCallback<void>): void -Deletes a KV pair of the specified key from this **Preferences** instance. This API uses an asynchronous callback to return the result. +Deletes a KV pair from this **Preferences** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty. | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js preferences.delete('startup', function (err) { if (err) { - console.info("Failed to delete startup key, err: " + err) - return + console.info("Failed to delete the key 'startup'. Cause: " + err); + return; } - console.info("Deleted startup key successfully.") + console.info("Deleted the key 'startup'."); }) ``` @@ -464,27 +485,27 @@ preferences.delete('startup', function (err) { delete(key: string): Promise<void> -Deletes a KV pair of the specified key from this **Preferences** instance. This API uses a promise to return the result. +Deletes a KV pair from this **Preferences** instance. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | key | string | Yes| Key of the KV pair to delete. It cannot be empty.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------------------- | +| key | string | Yes | Key of the KV pair to delete. It cannot be empty.| **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts -let promise = preferences.delete('startup') +```js +let promise = preferences.delete('startup'); promise.then(() => { - console.info("Deleted startup key successfully.") + console.info("Deleted the key 'startup'."); }).catch((err) => { - console.info("Failed to delete startup key, err: " + err) + console.info("Failed to delete the key 'startup'. Cause: " + err); }) ``` @@ -493,23 +514,23 @@ promise.then(() => { flush(callback: AsyncCallback<void>): void -Saves the modification to this **Preferences** instance and synchronizes the modification to the **Preferences** persistence file. This API uses an asynchronous callback to return the result. +Saves the data of the **Preferences** instance to a file asynchronously. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed data to file successfully.") + console.info("Flushed data successfully."); }) ``` @@ -518,22 +539,22 @@ preferences.flush(function (err) { flush(): Promise<void> -Saves the modification to this **Preferences** instance and synchronizes the modification to the **Preferences** persistence file. This API uses a promise to return the result. +Saves the data of the **Preferences** instance to a file asynchronously. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts -let promise = preferences.flush() +```js +let promise = preferences.flush(); promise.then(() => { console.info("Flushed data to file successfully.") }).catch((err) => { - console.info("Failed to flush data to file, err: " + err) + console.info("Failed to flush data. Cause: " + err); }) ``` @@ -542,23 +563,23 @@ promise.then(() => { clear(callback: AsyncCallback<void>): void -Clears data of this **Preferences** instance. This API uses an asynchronous callback to return the result. +Clears this **Preferences** instance. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | callback | AsyncCallback<void> | Yes| Callback that returns no value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------------------------------- | +| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**. Otherwise, **err** is an error code.| **Example** -```ts +```js preferences.clear(function (err) { if (err) { - console.info("Failed to clear data, err: " + err) - return + console.info("Failed to clear data. Cause: " + err); + return; } - console.info("Cleared to file successfully.") + console.info("Cleared data successfully."); }) ``` @@ -567,22 +588,22 @@ preferences.clear(function (err) { clear(): Promise<void> -Clears data of this **Preferences** instance. This API uses a promise to return the result. +Clears this **Preferences** instance. This API uses a promise to return the result. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Return value** - | Type| Description| - | -------- | -------- | - | Promise<void> | Promise that returns no value.| +| Type | Description | +| ------------------- | ------------------------- | +| Promise<void> | Promise that returns no value.| **Example** -```ts +```js let promise = preferences.clear() promise.then(() => { - console.info("Cleared to file successfully.") + console.info("Cleared data successfully."); }).catch((err) => { - console.info("Failed to clear data, err: " + err) + console.info("Failed to clear data. Cause: " + err); }) ``` @@ -591,40 +612,40 @@ promise.then(() => { on(type: 'change', callback: Callback<{ key : string }>): void -Subscribes to data changes. When the value of the subscribed key changes, a callback will be invoked after **flush()** is executed. +Subscribes to data changes. A callback will be triggered to return the new value if the value of the subscribed key is changed and [flushed](#flush). **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | Yes| Callback used to return data changes.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ---------------------------------------- | +| type | string | Yes | Event type to subscribe to. The value **change** indicates data change events.| +| callback | Callback<{ key : string }> | Yes | Callback invoked to return data changes. | **Example** -```ts +```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to get preferences.") + console.info("Failed to get the preferences."); return; } var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key " + key + " changed."); } - preferences.on('change', observer) + preferences.on('change', observer); preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed data to file successfully.") // The observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) }) }) @@ -640,37 +661,37 @@ Unsubscribes from data changes. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core **Parameters** - | Name| Type| Mandatory| Description| - | -------- | -------- | -------- | -------- | - | type | string | Yes| Event type. The value **change** indicates data change events.| - | callback | Callback<{ key : string }> | No| Callback used to return data changes. If this parameter is left empty, all callbacks for data changes will be canceled.| +| Name | Type | Mandatory| Description | +| -------- | -------------------------------- | ---- | ------------------------------------------ | +| type | string | Yes | Event type to unsubscribe from. The value **change** indicates data change events. | +| callback | Callback<{ key : string }> | No | Callback to unregister. If this parameter is left blank, the callbacks used to subscribing to all data changes will be unregistered.| **Example** -```ts +```js data_preferences.getPreferences(this.context, 'mystore', function (err, preferences) { if (err) { - console.info("Failed to get preferences.") + console.info("Failed to get preferences."); return; } var observer = function (key) { - console.info("The key of " + key + " changed.") + console.info("The key " + key + " changed."); } - preferences.on('change', observer) + preferences.on('change', observer); preferences.put('startup', 'auto', function (err) { if (err) { - console.info("Failed to put the value of startup, err: " + err) - return + console.info("Failed to put the value of 'startup'. Cause: " + err); + return; } - console.info("Put the value of startup successfully.") + console.info("Put the value of 'startup' successfully."); preferences.flush(function (err) { if (err) { - console.info("Failed to flush data to file, err: " + err) - return + console.info("Failed to flush data. Cause: " + err); + return; } - console.info("Flushed data to file successfully.") // The observer will be called. + console.info("Flushed data successfully."); // The observer will be called. }) - preferences.off('change', observer) + preferences.off('change', observer); }) }) ``` @@ -681,11 +702,11 @@ Enumerates the value types. **System capability**: SystemCapability.DistributedDataManager.Preferences.Core -| Type | Description | -| -------------- | ------------------------------ | -| number | The value is a number. | -| string | The value is a string. | -| boolean | The value is of Boolean type. | +| Type | Description | +| --------------- | ------------------------------ | +| number | The value is a number. | +| string | The value is a string. | +| boolean | The value is of Boolean type. | | Array\ | The value is an array of numbers. | | Array\ | The value is a Boolean array. | | Array\ | The value is an array of the strings.| diff --git a/en/application-dev/reference/apis/js-apis-device-manager.md b/en/application-dev/reference/apis/js-apis-device-manager.md index b2dbdfdccbb0b42259da73235976a6cd320daba7..9d51475957c8e9c891980c0d42880a6b1db649de 100644 --- a/en/application-dev/reference/apis/js-apis-device-manager.md +++ b/en/application-dev/reference/apis/js-apis-device-manager.md @@ -89,9 +89,9 @@ Enumerates the device states. | Name | Default Value | Description | | ------- | ---- | --------------- | -| ONLINE | 0 | The device is online. | -| READY | 1 | The device is ready, and the device information has been synchronized.| -| OFFLINE | 2 | The device is offline. | +| ONLINE | 0 | The device is physically online. | +| READY | 1 | The information between devices has been synchronized in the Distributed Data Service (DDS) module, and the device is ready for running distributed services.| +| OFFLINE | 2 | The device is physically offline. | | CHANGE | 3 | The device information is changed. | ## SubscribeInfo diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md index c684f0ea4f3c4cdd77de4e189b00e15f41a82855..9f1110f241e37530914961c21f688e67d44b05af 100644 --- a/en/application-dev/reference/apis/js-apis-hiappevent.md +++ b/en/application-dev/reference/apis/js-apis-hiappevent.md @@ -2,7 +2,7 @@ This module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** > The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -12,75 +12,210 @@ This module provides the application event logging functions, such as writing ap import hiAppEvent from '@ohos.hiAppEvent'; ``` +## How to Use -## hiAppEvent.write +Before using application event logging, you need to understand the requirements for related parameters. + +**Event Domain** + +An event domain is a string that contains a maximum of 32 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). + +**Event Name** + +An event name is a string that contains a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start with an underscore (_). + +**Event Type** + +An event type is an enumerated value of [EventType](#eventtype). + +**Event Parameter** + +An event parameter is an object in key-value pair format, where the key is the parameter name and the value is the parameter value. The requirements are as follows: + +- The parameter name is a string that contains a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (_). It cannot start or end with an underscore (_). +- The parameter value is a string, number, boolean, or array. +- When the parameter value is a string, its maximum length is 8*1024 characters. If this limit is exceeded, excess characters will be truncated. +- When the parameter value is an array, the elements in the array must be of the same type, which can only be string, number, or boolean. In addition, the number of elements must be less than 100. If this limit is exceeded, excess elements will be discarded. +- The maximum number of parameters is 32. If this limit is exceeded, excess parameters will be discarded. + +**Event Callback** + +Event callback can be a callback or promise that carries the return value obtained by invoking the event logging API. You can add the processing of the return value in the event callback as follows: + +- If the return value is **0**, the event verification is successful, and the event will be directly written to the event file. +- If the return value is greater than **0**, invalid parameters are present in the event, and the event will be written to the event file after the invalid parameters are ignored. +- If the return value is smaller than **0**, the event parameter verification fails, and the event will not be written to the event file. + +**Subscription Callback** + +A subscription callback carries the subscription data obtained by invoking the watcher API. The input parameters are defined as follows: + +- **curRow**: number of events. +- **curSize**: event data size, in bytes. +- **holder**: event data holder, which can be used for processing subscription events. + +## hiAppEvent.write(deprecated) write(eventName: string, eventType: EventType, keyValues: object, callback: AsyncCallback<void>): void -Writes event information to the event file of the current day. This API supports JSON parameters and uses an asynchronous callback to return the result. +> **NOTE**
This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9) instead. + +Writes event information to the event file of the current day. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ------------------------- | ---- | ------------------------------------------------------------ | -| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. | -| eventType | [EventType](#eventtype) | Yes | Application event type. | -| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated. | -| callback | AsyncCallback<void> | No | Callback used to process the received return value.
-  Value **0** indicates that the event verification is successful, and the event will be written to the event file asynchronously.
-  A value greater than **0** indicates that invalid parameters are present in the event, and the event will be written to the event file asynchronously after the invalid parameters are ignored.
-  A value smaller than **0** indicates that the event verification fails, and the event will not be written to the event file. | +| Name | Type | Mandatory| Description | +| --------- | ------------------------- | ---- | -------------- | +| eventName | string | Yes | Event name. | +| eventType | [EventType](#eventtype) | Yes | Event type. | +| keyValues | object | Yes | Event parameters. | +| callback | AsyncCallback<void> | No | Event callback.| **Example** ```js hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}, (err, value) => { if (err) { - // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. console.error(`failed to write event because ${err.code}`); return; } - // Event writing succeeded. + // Event writing success console.log(`success to write event: ${value}`); }); ``` -## hiAppEvent.write +## hiAppEvent.write(deprecated) write(eventName: string, eventType: EventType, keyValues: object): Promise<void> -Writes event information to the event file of the current day. This API supports JSON parameters and uses a promise to return the result. +> **NOTE**
This API is discarded since API version 9. You are advised to use [hiAppEvent.write](#hiappeventwrite9-1) instead. + +Writes event information to the event file of the current day. This API uses a promise to return the result. **System capability**: SystemCapability.HiviewDFX.HiAppEvent **Parameters** -| Name | Type | Mandatory| Description | -| --------- | ----------------------- | ---- | ------------------------------------------------------------ | -| eventName | string | Yes | App event name.
You need to customize the event name. It can contain a maximum of 48 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter. | -| eventType | [EventType](#eventtype) | Yes | Application event type. | -| keyValues | object | Yes | Parameter key-value pair. For a variable-length parameter, enter each pair of parameter name and value in sequence. For a JSON parameter, enter the parameter name as the key and parameter value as the value.
- A key must be a string, and a value must be a string, number, boolean, or Array (which can only be a string, number, or boolean).
- The number of event parameters must be less than or equal to 32.
- The parameter name can contain a maximum of 16 characters, including digits (0 to 9), letters (a to z), and underscores (\_). It must start with a letter and cannot end with an underscore (\_).
- A string value can contain a maximum of 8*1024 characters.
- An array value can contain a maximum of 100 elements. Excess elements will be truncated. | +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------- | +| eventName | string | Yes | Event name.| +| eventType | [EventType](#eventtype) | Yes | Event type.| +| keyValues | object | Yes | Event parameters.| **Return value** | Type | Description | | ------------------- | ------------------------------------------------------------ | -| Promise<void> | Promise used to process the callback in the then() and catch() methods when event writing succeeded or failed. | +| Promise<void> | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.| **Example** ```js hiAppEvent.write("test_event", hiAppEvent.EventType.FAULT, {"int_data":100, "str_data":"strValue"}) .then((value) => { - // Event writing succeeded. + // Event writing success console.log(`success to write event: ${value}`); }).catch((err) => { - // Event writing exception: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. console.error(`failed to write event because ${err.code}`); }); ``` +## hiAppEvent.write9+ + +write(info: [AppEventInfo](#appeventinfo9), callback: AsyncCallback<void>): void + +Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.| +| callback | AsyncCallback<void> | No | Event callback.| + +**Example** + +```js +hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" + } +}, (err, value) => { + if (err) { + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); + return; + } + + // Event writing success + console.log(`success to write event: ${value}`); +}); +``` + +## hiAppEvent.write9+ + +write(info: [AppEventInfo](#appeventinfo9)): Promise<void> + +Writes events to the event file of the current day through [AppEventInfo](#appeventinfo9) objects. This API uses a promise to return the result. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------------------------------ | ---- | -------------- | +| info | [AppEventInfo](#appeventinfo9) | Yes | Application event object.| + +**Return value** + +| Type | Description | +| ------------------- | ------------------------------------------------------------ | +| Promise<void> | Promise used to asynchronously process the callback in the **then()** and **catch()** methods when event writing succeeded or failed.| + +**Example** + +```js +hiAppEvent.write({ + domain: "test_domain", + name: "test_event", + eventType: hiAppEvent.EventType.FAULT, + params: { + int_data: 100, + str_data: "strValue" + } +}).then((value) => { + // Event writing success + console.log(`success to write event: ${value}`); +}).catch((err) => { + // Event writing error: Write the event to the event file after the invalid parameters in the event are ignored, or stop writing the event if the event verification fails. + console.error(`failed to write event because ${err.code}`); +}); +``` + +## AppEventInfo9+ + +Defines parameters for an **AppEventInfo** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| --------- | ----------------------- | ---- | ---------- | +| domain | string | Yes | Event domain.| +| name | string | Yes | Event name.| +| eventType | [EventType](#eventtype) | Yes | Event type.| +| params | object | Yes | Event parameters.| ## hiAppEvent.configure @@ -94,15 +229,16 @@ Configures the application event logging function, such as setting the event log | Name| Type | Mandatory| Description | | ------ | ----------------------------- | ---- | ------------------------ | -| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging. | +| config | [ConfigOption](#configoption) | Yes | Configuration items for application event logging.| **Return value** | Type | Description | | ------- | ----------------------------------------------------------- | -| boolean | Returns **true** if the configuration is successful; returns **false** otherwise. | +| boolean | Returns **true** if the configuration is successful; returns **false** otherwise.| **Example** + ```js // Set the application event logging switch. hiAppEvent.configure({ @@ -115,7 +251,6 @@ hiAppEvent.configure({ }); ``` - ## ConfigOption Provides the configuration items for application event logging. @@ -124,8 +259,205 @@ Provides the configuration items for application event logging. | Name | Type | Mandatory| Description | | ---------- | ------- | ---- | ------------------------------------------------------------ | -| disable | boolean | No | Application event logging switch. The value true means to disable the application event logging function, and the value false means the opposite. | -| maxStorage | string | No | Maximum size of the event file storage directory. The default value is **10M**. If the specified size is exceeded, the oldest event logging files in the storage directory will be deleted to free up space. | +| disable | boolean | No | Application event logging switch. The value **true** means to disable the application event logging function, and the value **false** means the opposite.| +| maxStorage | string | No | Maximum size of the event file storage directory. The default value is 10M. If the specified size is exceeded, the oldest event logging files in the directory will be deleted to free up space.| + +## hiAppEvent.addWatcher9+ + +addWatcher(watcher: [Watcher](#watcher9)): [AppEventPackageHolder](#appeventpackageholder9) + +Adds an event watcher. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher9) | Yes | Event watcher.| + +**Return value** + +| Type | Description | +| ------------------------------------------------ | ------------------------------------ | +| [AppEventPackageHolder](#appeventpackageholder9) | Subscription data holder. If the subscription fails, **null** will be returned.| + +**Example** + +```js +// 1. If callback parameters are passed to the watcher, you can have subscription events processed in the callback that is automatically triggered. +hiAppEvent.addWatcher({ + name: "watcher1", + appEventFilters: [ + { + domain: "domain_test1", + eventTypes: [hiAppEvent.EventType.FAULT, hiAppEvent.EventType.BEHAVIOR] + } + ], + triggerCondition: { + row: 10, + size: 1000, + timeOut: 1 + }, + onTrigger: function (curRow, curSize, holder) { + if (holder == null) { + console.error("holder is null"); + return; + } + while (true) { + let eventPkg = holder.takeNext(); + if (eventPkg == null) { + return; + } + console.info("eventPkg.packageId=" + eventPkg.packageId); + console.info("eventPkg.row=" + eventPkg.row); + console.info("eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("eventPkg.data=" + eventInfo); + } + } + } +}); + +// 2. If no callback parameters are passed to the watcher, you can have subscription events processed manually through the subscription data holder. +let holder = hiAppEvent.addWatcher({ + name: "watcher2", +}); +if (holder != null) { + let eventPkg = holder.takeNext(); + if (eventPkg == null) { + return; + } + console.info("eventPkg.packageId=" + eventPkg.packageId); + console.info("eventPkg.row=" + eventPkg.row); + console.info("eventPkg.size=" + eventPkg.size); + for (const eventInfo of eventPkg.data) { + console.info("eventPkg.data=" + eventInfo); + } +} +``` + +## hiAppEvent.removeWatcher9+ + +removeWatcher(watcher: [Watcher](#watcher9)): void + +Removes an event watcher. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Parameters** + +| Name | Type | Mandatory| Description | +| ------- | -------------------- | ---- | ---------------- | +| watcher | [Watcher](#watcher9) | Yes | Event watcher.| + +**Example** + +```js +// 1. Define a watcher. +let watcher = { + name: "watcher1", +} + +// 2. Add the watcher to subscribe to application events. +hiAppEvent.addWatcher(watcher); + +// 3. Remove the watcher to unsubscribe from application events. +hiAppEvent.removeWatcher(watcher); +``` + +## Watcher9+ + +Defines parameters for a **Watcher** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------------- | ------------------------------------------------------------ | ---- | -------------------------------- | +| name | string | Yes | Unique watcher name.| +| triggerCondition | [TriggerCondition](#triggercondition9) | No | Subscription callback trigger condition. | +| appEventFilters | [AppEventFilter](#appeventfilter9)[] | No | Application event filter criteria. | +| onTrigger | (curRow: number, curSize: number, holder: [AppEventPackageHolder](#appeventpackageholder9)) => void | No | Subscription callback. | + +## TriggerCondition9+ + +Defines parameters for a **TriggerCondition** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Mandatory| Description | +| ------- | -------- | ---- | -------------------------------------- | +| row | number | No | Number of events. | +| size | number | No | Event data size, in bytes.| +| timeOut | number | No | Timeout interval, in unit of 30s. | + +## AppEventFilter9+ + +Defines parameters for an **AppEventFilter** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type | Mandatory| Description | +| ---------- | ------------------------- | ---- | ------------------------ | +| domain | string | Yes | Event domain. | +| eventTypes | [EventType](#eventtype)[] | No | Event types.| + +## AppEventPackageHolder9+ + +Defines a subscription data holder for processing subscription events. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +### setSize9+ + +setSize(size: number): void + +Sets the data size threshold for fetching an application event package. The default value is **512*1024**, in bytes. + +**Example** + +```js +holder.setSize(1000); +``` + +### takeNext9+ + +takeNext(): [AppEventPackage](#appeventpackage9) + +Extracts subscription event data based on the configured data size threshold. If all subscription event data has been extracted, **null** will be returned. + +**Example** + +```js +let eventPkg = holder.takeNext(); +``` + +## AppEventPackage9+ + +Defines parameters for an **AppEventPackage** object. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +| Name | Type| Description | +| --------- | -------- | ------------------------------ | +| packageId | number | Event package ID, which is named from **0** in ascending order. | +| row | number | Number of events in the event package. | +| size | number | Data size of the event package, in bytes.| +| data | string[] | Event data in the event package. | + +## hiAppEvent.clearData9+ + +clearData(): void + +Clears local logging data. + +**System capability**: SystemCapability.HiviewDFX.HiAppEvent + +**Example** + +```js +hiAppEvent.clearData(); +``` ## EventType @@ -136,10 +468,10 @@ Enumerates event types. | Name | Default Value| Description | | --------- | ------ | -------------- | -| FAULT | 1 | Fault event| -| STATISTIC | 2 | Statistical event| -| SECURITY | 3 | Security event| -| BEHAVIOR | 4 | Behavior event| +| FAULT | 1 | Fault event.| +| STATISTIC | 2 | Statistical event.| +| SECURITY | 3 | Security event.| +| BEHAVIOR | 4 | Behavior event.| ## Event @@ -152,7 +484,7 @@ Provides constants that define the names of all predefined events. | ------------------------- | -------- | ---- | ---- | -------------------- | | USER_LOGIN | string | Yes | No | User login event. | | USER_LOGOUT | string | Yes | No | User logout event. | -| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event. | +| DISTRIBUTED_SERVICE_START | string | Yes | No | Distributed service startup event.| ## Param @@ -161,8 +493,8 @@ Provides constants that define the names of all predefined event parameters. **System capability**: SystemCapability.HiviewDFX.HiAppEvent -| Name | Type | Readable | Writable | Description | +| Name | Type| Readable| Writable| Description | | ------------------------------- | -------- | ---- | ---- | ------------------ | | USER_ID | string | Yes | No | Custom user ID. | -| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | -| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID. | \ No newline at end of file +| DISTRIBUTED_SERVICE_NAME | string | Yes | No | Distributed service name. | +| DISTRIBUTED_SERVICE_INSTANCE_ID | string | Yes | No | Distributed service instance ID.| diff --git a/en/application-dev/reference/apis/js-apis-hitracemeter.md b/en/application-dev/reference/apis/js-apis-hitracemeter.md index e856ee20a4c8956ff0f05707b596935b68ca9e7a..04a9db2a0e7bc00cb9ff8a017eb6e39c47d97f30 100644 --- a/en/application-dev/reference/apis/js-apis-hitracemeter.md +++ b/en/application-dev/reference/apis/js-apis-hitracemeter.md @@ -1,8 +1,9 @@ # Performance Tracing -This module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. +The Performance Tracing module provides the functions of tracing service processes and monitoring the system performance. It provides the data needed for hiTraceMeter to carry out performance analysis. -> ![icon-note.gif](public_sys-resources/icon-note.gif) **NOTE**
+> **NOTE** +> > The initial APIs of this module are supported since API version 8. Newly added APIs will be marked with a superscript to indicate their earliest API version. @@ -17,7 +18,7 @@ import hiTraceMeter from '@ohos.hiTraceMeter'; startTrace(name: string, taskId: number): void -Starts a trace task. **expectedTime** is an optional parameter, which specifies the expected duration of the trace. +Starts a trace task. If multiple trace tasks with the same name need to be performed at the same time or a trace task needs to be performed multiple times concurrently, different task IDs must be specified in **startTrace**. diff --git a/en/application-dev/reference/apis/js-apis-i18n.md b/en/application-dev/reference/apis/js-apis-i18n.md index a21e4ddb660cba43fef79e5e509464eca986aea9..b68a5b15487f310dd6b05058c68af75840098062 100644 --- a/en/application-dev/reference/apis/js-apis-i18n.md +++ b/en/application-dev/reference/apis/js-apis-i18n.md @@ -676,7 +676,7 @@ Formats a phone number. ### getLocationName9+ -static getLocationName(number: string, locale: string): string +getLocationName(number: string, locale: string): string Obtains the home location of a phone number. diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md index 6e3ee3ab521fd77e73a8085002296cd6b5883430..ee61f71f78a97411006f72225f5ac4a65e09e300 100644 --- a/en/application-dev/reference/apis/js-apis-radio.md +++ b/en/application-dev/reference/apis/js-apis-radio.md @@ -389,7 +389,7 @@ promise.then(data => { isNrSupported\(slotId: number\): boolean -Checks whether the current device supports 5G \(NR\). +Checks whether the current device supports 5G \(NR\) for the SIM card in the specified slot. **System capability**: SystemCapability.Telephony.CoreService @@ -470,7 +470,7 @@ radio.isRadioOn(slotId, (err, data) => { isRadioOn\(slotId?: number\): Promise -Checks whether the radio service is enabled. This API uses a promise to return the result. +Checks whether the radio service is enabled on the SIM card in the specified slot. This API uses a promise to return the result. **Required permission**: ohos.permission.GET_NETWORK_INFO @@ -505,7 +505,7 @@ promise.then(data => { getOperatorName\(slotId: number, callback: AsyncCallback\): void -Obtains the carrier name. This API uses an asynchronous callback to return the result. +Obtains the carrier name for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -530,7 +530,7 @@ radio.getOperatorName(slotId, (err, data) => { getOperatorName\(slotId: number\): Promise -Obtains the carrier name. This API uses a promise to return the result. +Obtains the carrier name for the SIM card in the specified slot. This API uses a promise to return the result. **System capability**: SystemCapability.Telephony.CoreService @@ -905,7 +905,29 @@ sendUpdateCellLocationRequest\(callback: AsyncCallback\): void Sends a cell location update request. This API uses an asynchronous callback to return the result. +This is a system API. + +**System capability**: SystemCapability.Telephony.CoreService + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------- | ---- | ---------- | +| callback | AsyncCallback\ | Yes | Callback used to return the result.| + +**Example** + +```js +radio.sendUpdateCellLocationRequest((err, data) => { + console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); +}); +``` + +## radio.sendUpdateCellLocationRequest8+ + +sendUpdateCellLocationRequest\(slotId: number, callback: AsyncCallback\): void +Sends a cell location update request for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -915,26 +937,34 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | --------------------- | ---- | ---------- | +| slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| | callback | AsyncCallback\ | Yes | Callback used to return the result.| **Example** ```js -radio.sendUpdateCellLocationRequest((err, data) => { +let slotId = 0; +radio.sendUpdateCellLocationRequest(slotId, (err, data) => { console.log(`callback: err->${JSON.stringify(err)}, data->${JSON.stringify(data)}`); }); ``` ## radio.sendUpdateCellLocationRequest8+ -sendUpdateCellLocationRequest\(\): Promise +sendUpdateCellLocationRequest\(slotId?: number): Promise -Sends a cell location update request. This API uses a promise to return the result. +Sends a cell location update request for the SIM card in the specified slot.This API uses a promise to return the result. This is a system API. **System capability**: SystemCapability.Telephony.CoreService +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | -------------------------------------- | +| slotId | number | No | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2| + **Return value** | Type | Description | @@ -944,7 +974,8 @@ This is a system API. **Example** ```js -let promise = radio.sendUpdateCellLocationRequest(); +let slotId = 0; +let promise = radio.sendUpdateCellLocationRequest(slotId); promise.then(data => { console.log(`sendUpdateCellLocationRequest success, promise: data->${JSON.stringify(data)}`); }).catch(err => { @@ -983,7 +1014,7 @@ radio.getCellInformation((err, data) => { getCellInformation(slotId: number, callback: AsyncCallback\>): void -Obtains cell information. This API uses an asynchronous callback to return the result. +Obtains cell information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1012,7 +1043,7 @@ radio.getCellInformation(slotId, (err, data) => { getCellInformation(slotId?: number): Promise\> -Obtains cell information. This API uses a promise to return the result. +Obtains cell information for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1134,7 +1165,7 @@ promise.then(data => { getNetworkSearchInformation\(slotId: number, callback: AsyncCallback\): void -Obtains network search information. This API uses an asynchronous callback to return the result. +Obtains network search information for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1161,7 +1192,7 @@ radio.getNetworkSearchInformation(0, (err, data) => { getNetworkSearchInformation\(slotId: number\): Promise -Obtains network search information. This API uses a promise to return the result. +Obtains network search information for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1221,7 +1252,7 @@ radio.getNrOptionMode((err, data) => { getNrOptionMode(slotId: number, callback: AsyncCallback): void -Obtains the NR option mode. This API uses an asynchronous callback to return the result. +Obtains the NR option mode for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1248,7 +1279,7 @@ radio.getNrOptionMode(slotId, (err, data) => { getNrOptionMode(slotId?: number): Promise -Obtains the NR option mode. This API uses a promise to return the result. +Obtains the NR option mode for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1466,7 +1497,7 @@ promise.then(data => { setPreferredNetwork\(slotId: number, networkMode: PreferredNetworkMode, callback: AsyncCallback\): void -Sets the preferred network. This API uses an asynchronous callback to return the result. +Sets the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1494,7 +1525,7 @@ radio.setPreferredNetwork(0, 1, (err, data) => { setPreferredNetwork(slotId: number, networkMode: PreferredNetworkMode): Promise -Sets the preferred network. This API uses a promise to return the result. +Sets the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1530,7 +1561,7 @@ promise.then(data => { getPreferredNetwork\(slotId: number, callback: AsyncCallback\): void -Obtains the preferred network. This API uses an asynchronous callback to return the result. +Obtains the preferred network for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1557,7 +1588,7 @@ radio.getPreferredNetwork(0, (err, data) => { getPreferredNetwork(slotId: number): Promise -Obtains the preferred network. This API uses a promise to return the result. +Obtains the preferred network for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1592,7 +1623,7 @@ promise.then(data => { getImsRegInfo(slotId: number, imsType: ImsServiceType, callback: AsyncCallback): void -Obtains the IMS registration status of the specified IMS service type. This API uses an asynchronous callback to return the result. +Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1620,7 +1651,7 @@ radio.getImsRegInfo(0, 1, (err, data) => { getImsRegInfo(slotId: number, imsType: ImsServiceType): Promise -Obtains the IMS registration status of the specified IMS service type. This API uses a promise to return the result. +Obtains the IMS registration status of the specified IMS service type for the SIM card in the specified slot. This API uses a promise to return the result. This is a system API. @@ -1656,7 +1687,7 @@ promise.then(data => { on(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback: Callback): void -Enables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result. +Enables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. @@ -1685,7 +1716,7 @@ radio.on('imsRegStateChange', 0, 1, (err, data) => { off(type: 'imsRegStateChange', slotId: number, imsType: ImsServiceType, callback?: Callback): void -Disables listening for **imsRegStateChange** events. This API uses an asynchronous callback to return the result. +Disables listening for **imsRegStateChange** events for the SIM card in the specified slot. This API uses an asynchronous callback to return the result. This is a system API. diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md index 681e5cdc6ac3dea7924feb25752e017052bef23e..f9475d2e7d76b6ccf20f6b0f32d01969fdccfbbb 100644 --- a/en/application-dev/reference/apis/js-apis-sim.md +++ b/en/application-dev/reference/apis/js-apis-sim.md @@ -64,7 +64,7 @@ let promise = sim.isSimActive(0); promise.then(data => { console.log(`isSimActive success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`isSimActive fail, promise: err->${JSON.stringify(err)}`); + console.log(`isSimActive failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -113,7 +113,7 @@ let promise = sim.getDefaultVoiceSlotId(); promise.then(data => { console.log(`getDefaultVoiceSlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getDefaultVoiceSlotId fail, promise: err->${JSON.stringify(err)}`); + console.log(`getDefaultVoiceSlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -167,7 +167,7 @@ let promise = sim.hasOperatorPrivileges(0); promise.then(data => { console.log(`hasOperatorPrivileges success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`hasOperatorPrivileges fail, promise: err->${JSON.stringify(err)}`); + console.log(`hasOperatorPrivileges failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -222,7 +222,7 @@ let promise = sim.getISOCountryCodeForSim(0); promise.then(data => { console.log(`getISOCountryCodeForSim success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getISOCountryCodeForSim fail, promise: err->${JSON.stringify(err)}`); + console.log(`getISOCountryCodeForSim failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -278,7 +278,7 @@ let promise = sim.getSimOperatorNumeric(0); promise.then(data => { console.log(`getSimOperatorNumeric success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimOperatorNumeric fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimOperatorNumeric failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -334,7 +334,7 @@ let promise = sim.getSimSpn(0); promise.then(data => { console.log(`getSimSpn success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimSpn fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimSpn failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -390,7 +390,7 @@ let promise = sim.getSimState(0); promise.then(data => { console.log(`getSimState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimState fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -445,7 +445,7 @@ let promise = sim.getCardType(0); promise.then(data => { console.log(`getCardType success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getCardType fail, promise: err->${JSON.stringify(err)}`); + console.log(`getCardType failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -501,7 +501,7 @@ let promise = sim.hasSimCard(0); promise.then(data => { console.log(`hasSimCard success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`hasSimCard fail, promise: err->${JSON.stringify(err)}`); + console.log(`hasSimCard failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -564,7 +564,7 @@ let promise = sim.getSimAccountInfo(0); promise.then(data => { console.log(`getSimAccountInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimAccountInfo fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimAccountInfo failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -620,7 +620,7 @@ let promise = sim.getActiveSimAccountInfoList(); promise.then(data => { console.log(`getActiveSimAccountInfoList success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getActiveSimAccountInfoList fail, promise: err->${JSON.stringify(err)}`); + console.log(`getActiveSimAccountInfoList failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -683,7 +683,7 @@ let promise = sim.setDefaultVoiceSlotId(0); promise.then(data => { console.log(`setDefaultVoiceSlotId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setDefaultVoiceSlotId fail, promise: err->${JSON.stringify(err)}`); + console.log(`setDefaultVoiceSlotId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -749,7 +749,7 @@ let promise = sim.setShowName(0, name); promise.then(data => { console.log(`setShowName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setShowName fail, promise: err->${JSON.stringify(err)}`); + console.log(`setShowName failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -812,7 +812,7 @@ let promise = sim.getShowName(0); promise.then(data => { console.log(`getShowName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getShowName fail, promise: err->${JSON.stringify(err)}`); + console.log(`getShowName failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -879,7 +879,7 @@ let promise = sim.setShowNumber(0, number); promise.then(data => { console.log(`setShowNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setShowNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`setShowNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -942,7 +942,7 @@ let promise = sim.getShowNumber(0); promise.then(data => { console.log(`getShowNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getShowNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`getShowNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1005,7 +1005,7 @@ let promise = sim.activateSim(0); promise.then(data => { console.log(`activateSim success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`activateSim fail, promise: err->${JSON.stringify(err)}`); + console.log(`activateSim failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1068,7 +1068,7 @@ let promise = sim.deactivateSim(0); promise.then(data => { console.log(`deactivateSim success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`deactivateSim fail, promise: err->${JSON.stringify(err)}`); + console.log(`deactivateSim failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1090,7 +1090,7 @@ This is a system API. | -------- | ----------------------------------------------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | | callback | AsyncCallback\<[LockStatusResponse](#lockstatusresponse7)\> | Yes | Callback used to return the result. | -| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- **lockType**: [LockType](#locktype8)
- **password**: string
- **state**: [LockState](#lockstate8) | **Example** @@ -1123,7 +1123,7 @@ This is a system API. | Name | Type | Mandatory| Description | | ------- | ---------------------- | ---- | ------------------------------------------------------------ | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| options | [LockInfo](#lockinfo8) | Yes | Lock information.
lockType: [LockType](#locktype8)
password: string
state: [LockState](#lockstate8) | +| options | [LockInfo](#lockinfo8) | Yes | Lock information.
- **lockType**: [LockType](#locktype8)
- **password**: string
- **state**: [LockState](#lockstate8) | **Return value** @@ -1143,7 +1143,7 @@ let promise = sim.setLockState(0, lockInfo); promise.then(data => { console.log(`setLockState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setLockState fail, promise: err->${JSON.stringify(err)}`); + console.log(`setLockState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1204,7 +1204,7 @@ let promise = sim.getLockState(0, 1); promise.then(data => { console.log(`getLockState success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getLockState fail, promise: err->${JSON.stringify(err)}`); + console.log(`getLockState failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1271,7 +1271,7 @@ let promise = sim.alterPin(0, "1234", "0000"); promise.then(data => { console.log(`alterPin success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`alterPin fail, promise: err->${JSON.stringify(err)}`); + console.log(`alterPin failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1338,7 +1338,7 @@ let promise = sim.alterPin2(0, "1234", "0000"); promise.then(data => { console.log(`alterPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`alterPin2 fail, promise: err->${JSON.stringify(err)}`); + console.log(`alterPin2 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1405,7 +1405,7 @@ let promise = sim.unlockPin(0, pin); promise.then(data => { console.log(`unlockPin success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPin fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPin failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1476,7 +1476,7 @@ let promise = sim.unlockPuk(0, newPin, puk); promise.then(data => { console.log(`unlockPuk success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPuk fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPuk failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1543,7 +1543,7 @@ let promise = sim.unlockPin2(0,pin2); promise.then(data => { console.log(`unlockPin2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPin2 fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPin2 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1614,7 +1614,7 @@ let promise = sim.unlockPuk2(0, newPin2, puk2); promise.then(data => { console.log(`unlockPuk2 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockPuk2 fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockPuk2 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1697,7 +1697,7 @@ let promise = sim.getSimIccId(0); promise.then(data => { console.log(`getSimIccId success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimIccId fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimIccId failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1760,7 +1760,7 @@ let promise = sim.getVoiceMailIdentifier(0); promise.then(data => { console.log(`getVoiceMailIdentifier success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getVoiceMailIdentifier fail, promise: err->${JSON.stringify(err)}`); + console.log(`getVoiceMailIdentifier failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1823,7 +1823,7 @@ let promise = sim.getVoiceMailNumber(0); promise.then(data => { console.log(`getVoiceMailNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getVoiceMailNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`getVoiceMailNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1890,7 +1890,7 @@ let promise = sim.setVoiceMailInfo(0, "mail", "xxx@xxx.com"); promise.then(data => { console.log(`setVoiceMailInfo success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`setVoiceMailInfo fail, promise: err->${JSON.stringify(err)}`); + console.log(`setVoiceMailInfo failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -1953,7 +1953,7 @@ let promise = sim.getSimTelephoneNumber(0); promise.then(data => { console.log(`getSimTelephoneNumber success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimTelephoneNumber fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimTelephoneNumber failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2016,7 +2016,7 @@ let promise = sim.getSimGid1(0); promise.then(data => { console.log(`getSimGid1 success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getSimGid1 fail, promise: err->${JSON.stringify(err)}`); + console.log(`getSimGid1 failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2079,7 +2079,7 @@ let promise = sim.getIMSI(0); promise.then(data => { console.log(`getIMSI success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getIMSI fail, promise: err->${JSON.stringify(err)}`); + console.log(`getIMSI failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2142,7 +2142,7 @@ let promise = sim.getOperatorConfigs(0); promise.then(data => { console.log(`getOperatorConfigs success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOperatorConfigs fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOperatorConfigs failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2163,7 +2163,7 @@ This is a system API. | Name | Type | Mandatory| Description | | -------- | ------------------------------------------------------------ | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | callback | AsyncCallback> | Yes | Callback used to return the result. | **Example** @@ -2192,7 +2192,7 @@ This is a system API. | Name| Type | Mandatory| Description | | ------ | ----------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
1 : GENERAL_CONTACT
2 : FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | **Return value** @@ -2207,7 +2207,7 @@ let promise = sim.queryIccDiallingNumbers(0, 1); promise.then(data => { console.log(`queryIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`queryIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`queryIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2228,7 +2228,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2264,7 +2264,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | **Return value** @@ -2286,7 +2286,7 @@ let promise = sim.addIccDiallingNumbers(0, 1, diallingNumbersInof); promise.then(data => { console.log(`addIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`addIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`addIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2307,7 +2307,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2343,7 +2343,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | **Return value** @@ -2365,7 +2365,7 @@ let promise = sim.delIccDiallingNumbers(0, 1, diallingNumbersInof); promise.then(data => { console.log(`delIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`delIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`delIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2386,7 +2386,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | | callback | AsyncCallback | Yes | Callback used to return the result. | @@ -2422,7 +2422,7 @@ This is a system API. | Name | Type | Mandatory| Description | | --------------- | -------------------------------------------- | ---- | ---------------------------------------------------------- | | slotId | number | Yes | Card slot ID.
- **0**: card slot 1
- **1**: card slot 2 | -| type | [ContactType](#contacttype8) | Yes | Contact type.
**1**: GENERAL_CONTACT
**2**: FIXED_DIALING | +| type | [ContactType](#contacttype8) | Yes | Contact type.
- **1**: GENERAL_CONTACT
- **2**: FIXED_DIALING | | diallingNumbers | [DiallingNumbersInfo](#diallingnumbersinfo8) | Yes | Contact number information. | **Return value** @@ -2444,7 +2444,7 @@ let promise = sim.updateIccDiallingNumbers(0, 1, diallingNumbersInof); promise.then(data => { console.log(`updateIccDiallingNumbers success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`updateIccDiallingNumbers fail, promise: err->${JSON.stringify(err)}`); + console.log(`updateIccDiallingNumbers failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2509,7 +2509,7 @@ let promise = sim.sendEnvelopeCmd(0, "ls"); promise.then(data => { console.log(`sendEnvelopeCmd success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`sendEnvelopeCmd fail, promise: err->${JSON.stringify(err)}`); + console.log(`sendEnvelopeCmd failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2574,7 +2574,7 @@ let promise = sim.sendTerminalResponseCmd(0, "ls"); promise.then(data => { console.log(`sendTerminalResponseCmd success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`sendTerminalResponseCmd fail, promise: err->${JSON.stringify(err)}`); + console.log(`sendTerminalResponseCmd failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2647,7 +2647,7 @@ let promise = sim.unlockSimLock(0, persoLockInfo); promise.then(data => { console.log(`unlockSimLock success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`unlockSimLock fail, promise: err->${JSON.stringify(err)}`); + console.log(`unlockSimLock failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2706,7 +2706,7 @@ let promise = sim.getOpKey(0); promise.then(data => { console.log(`getOpKey success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOpKey fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOpKey failed, promise: err->${JSON.stringify(err)}`); }); ``` @@ -2765,7 +2765,7 @@ let promise = sim.getOpName(0); promise.then(data => { console.log(`getOpName success, promise: data->${JSON.stringify(data)}`); }).catch(err => { - console.log(`getOpName fail, promise: err->${JSON.stringify(err)}`); + console.log(`getOpName failed, promise: err->${JSON.stringify(err)}`); }); ``` diff --git a/en/application-dev/reference/apis/js-apis-system-time.md b/en/application-dev/reference/apis/js-apis-system-time.md index a89640acc11ba359dfdf6011bbd4766cdd42b5ec..ec32f9279c250a823484d0894e5ce56c82386601 100644 --- a/en/application-dev/reference/apis/js-apis-system-time.md +++ b/en/application-dev/reference/apis/js-apis-system-time.md @@ -1,9 +1,10 @@ -# Setting the System Time +# System Time and Time Zone -This module provides the time, time zone, and timing services. Use the time and time zone services to set and obtain the system time and time zone, and use the timing service to manage and use the system time and time zone to implement alarms or other timing functions. - -> **NOTE**
The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +The **systemTime** module provides system time and time zone features. You can use the APIs of this module to set and obtain the system time and time zone. +> **NOTE** +>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs of this module are system APIs and cannot be called by third-party applications. ## Modules to Import @@ -25,15 +26,15 @@ Sets the system time. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| time | number | Yes| Timestamp to set, in milliseconds.| -| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| time | number | Yes | Timestamp to set, in milliseconds. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** ```js -// Set the system time to 2021-01-20 02:36:25. + // Set the system time to 2021-01-20 02:36:25. var time = 1611081385000; systemTime.setTime(time, (error, data) => { if (error) { @@ -57,26 +58,26 @@ Sets the system time. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| time | number | Yes| Timestamp to set, in milliseconds.| +| Name| Type | Mandatory| Description | +| ------ | ------ | ---- | ------------------ | +| time | number | Yes | Timestamp to set, in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | -------------------- | | Promise<void> | Promise used to return the result.| **Example** ```js -// Set the system time to 2021-01-20 02:36:25. -var time = 1611081385000; -systemTime.setTime(time).then((data) => { - console.log(`systemTime.setTime success data : ` + JSON.stringify(data)); -}).catch((error) => { - console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); -}); + // Set the system time to 2021-01-20 02:36:25. + var time = 1611081385000; + systemTime.setTime(time).then((data) => { + console.log(`systemTime.setTime success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.setTime because ` + JSON.stringify(error)); + }); ``` @@ -90,10 +91,10 @@ Obtains the time elapsed since the Unix epoch. This API uses an asynchronous cal **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| -| callback | AsyncCallback<number> | Yes| Callback used to return the time.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -118,14 +119,14 @@ Obtains the time elapsed since the Unix epoch. This API uses a promise to return **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the time.| **Example** @@ -149,10 +150,10 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| -| callback | AsyncCallback<number> | Yes| Callback used to return the time.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| callback | AsyncCallback<number> | Yes | Callback used to return the time.| **Example** @@ -177,14 +178,14 @@ Obtains the time elapsed since system start, excluding the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the time.| **Example** @@ -208,10 +209,10 @@ Obtains the time elapsed since system start, including the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| -| callback | AsyncCallback<number> | Yes| Callback used to return the time.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | +| callback | AsyncCallback<number> | Yes | Callback used to return the time. | **Example** @@ -236,14 +237,14 @@ Obtains the time elapsed since system start, including the deep sleep time. This **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| isNano | boolean | No| Whether nanoseconds or milliseconds will be returned. If the value is **true**, nanoseconds will be returned. Otherwise, milliseconds will be returned.| +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| isNano | boolean | No | Whether the time to return is in nanoseconds.
- **true**: in nanoseconds.
- **false**: in milliseconds. | **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------------------------------ | | Promise<number> | Promise used to return the time.| **Example** @@ -269,10 +270,10 @@ Sets the system date. This API uses an asynchronous callback to return the resul **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| date | Date | Yes| Target date to set.| -| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| date | Date | Yes | Target date to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -300,14 +301,14 @@ Sets the system date. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| date | Date | Yes| Target date to set.| +| Name| Type| Mandatory| Description | +| ------ | ---- | ---- | ---------- | +| date | Date | Yes | Target date to set.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | -------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -332,9 +333,9 @@ Obtains the current system date. This API uses an asynchronous callback to retur **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<Date> | Yes| Callback used to return the current system date.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ---------------------------- | +| callback | AsyncCallback<Date> | Yes | Callback used to return the current system date.| **Example** @@ -359,8 +360,8 @@ Obtains the current system date. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | ----------------------------------------- | | Promise<Date> | Promise used to return the current system date.| **Example** @@ -386,10 +387,10 @@ Sets the system time zone. This API uses an asynchronous callback to return the **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timezone | string | Yes| System time zone to set.| -| callback | AsyncCallback<void> | Yes| Callback used to process the received return value.| +| Name | Type | Mandatory| Description | +| -------- | ------------------------- | ---- | ------------------------------------------ | +| timezone | string | Yes | System time zone to set. | +| callback | AsyncCallback<void> | Yes | Callback used to return the result.| **Example** @@ -416,14 +417,14 @@ Sets the system time zone. This API uses a promise to return the result. **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| timezone | string | Yes| System time zone to set.| +| Name | Type | Mandatory| Description | +| -------- | ------ | ---- | ---------- | +| timezone | string | Yes | System time zone to set.| **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| ------------------- | -------------------- | | Promise<void> | Promise used to return the result.| **Example** @@ -447,9 +448,9 @@ Obtains the system time zone. This API uses an asynchronous callback to return t **Parameters** -| Name| Type| Mandatory| Description| -| -------- | -------- | -------- | -------- | -| callback | AsyncCallback<string> | Yes| Callback used to return the system time zone.| +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------ | +| callback | AsyncCallback<string> | Yes | Callback used to return the system time zone.| **Example** @@ -474,8 +475,8 @@ Obtains the system time zone. This API uses a promise to return the result. **Return value** -| Type| Description| -| -------- | -------- | +| Type | Description | +| --------------------- | ------------------------------------- | | Promise<string> | Promise used to return the system time zone.| **Example** diff --git a/en/application-dev/reference/apis/js-apis-system-timer.md b/en/application-dev/reference/apis/js-apis-system-timer.md new file mode 100644 index 0000000000000000000000000000000000000000..f952b38c3de656864d42ad8c2c42b108b0c53f3d --- /dev/null +++ b/en/application-dev/reference/apis/js-apis-system-timer.md @@ -0,0 +1,319 @@ +# System Timer + +The **systemTimer** module provides system timer features. You can use the APIs of this module to implement the alarm clock and other timer services. + +> **NOTE**
+>- The initial APIs of this module are supported since API version 7. Newly added APIs will be marked with a superscript to indicate their earliest API version. +>- The APIs of this module are system APIs and cannot be called by third-party applications. + +## Modules to Import + + +``` +import systemTimer from '@ohos.systemTimer'; +``` + + +## systemTime.createTimer + +createTimer(options: TimerOptions, callback: AsyncCallback<number>): void + +Creates a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | +| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | +| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | + +**Return value** + +| Type | Description | +| ------------------------- | ------------------------------------------------------------ | +| syncCallback<number>| Callback used to return the timer ID. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat: false + } + systemTimer.createTimer(options, (error, data) => { + if (error) { + console.error(`failed to systemTime.createTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.createTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + + +## systemTime.createTimer + +createTimer(options: TimerOptions): Promise<number> + +Creates a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | ------------------ | ---- | --------------------------------------------------------------------------------------- | +| options | TimerOptions | Yes | Timer options.
**TIMER_TYPE_REALTIME**: sets the timer to the real-time type. If it is not specified, the timer is of the non-real-time type.
**TIMER_TYPE_WAKEUP**: sets the timer to the wakeup type. If it is not specified, the timer is of the non-wakeup type.
**TIMER_TYPE_EXACT**: sets the timer to the exact type. If it is not specified, the timer is of the non-exact type.
**TIMER_TYPE_IDLE: number**: sets the timer to the idle type. If it is not specified, the timer is of the non-idle type (not yet supported).| +| repeat | boolean | Yes | Whether the timer is a repeating timer. The value **true** means that the timer is a repeating timer, and **false** means that the timer is a one-shot timer. | +| interval | number | No | Repeat interval. For a repeating timer, the value must be greater than 5000 ms. For a one-shot timer, the value is **0**. | +| wantAgent| wantAgent | No | **wantAgent** object of the notification to be sent when the timer expires. (An OpenHarmony application MainAbility can be started, but not an SA service.) | + +**Return value** + +| Type | Description | +| --------------------- | ------------------------------------------------------------ | +| Promise<number> | Promise used to return the timer ID. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + systemTimer.createTimer(options).then((data) => { + console.log(`systemTime.createTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.createTimer because ` + JSON.stringify(error)); + }); + } +} + ``` + + +## systemTime.startTimer + +startTimer(timer: number, triggerTime: number, callback: AsyncCallback<void>): void + +Starts a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | +| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | + + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 10000, (error, data) => { + if (error) { + console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + +## systemTime.startTimer + +startTimer(timer: number, triggerTime: number): Promise<void> + +Starts a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| ----------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | +| triggerTime | number | Yes | Time when the timer is triggered, in milliseconds. | + + +**Example** + + ```js +export default { + systemTimer (){ + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 10000).then((data) => { + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); + }); + } +} + ``` + + +## systemTime.stopTimer + +stopTimer(timer: number, callback: AsyncCallback<void>): void + +Stops a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stoptTimer(timerId, 10000, (error, data) => { + if (error) { + console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + + +## systemTime.stopTimer + +stopTimer(timer: number): Promise<void> + +Stops a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer (){ + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stoptTimer(timerId, 10000).then((data) => { + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); + }); + } +} + ``` + + +## systemTime.destroyTimer + +destroyTimer(timer: number, callback: AsyncCallback<void>): void + +Destroys a timer. This API uses an asynchronous callback to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name | Type | Mandatory| Description | +| -------- | --------------------------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer () { + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stopTimer(timerId) + systemTimer.destroyTimer(timerId, (error, data) => { + if (error) { + console.error(`failed to systemTime.startTimer ` + JSON.stringify(error)); + return; + } + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }); + } +} + ``` + + +## systemTime.destroyTimer + +destroyTimer(timer: number): Promise<void> + +Destroys a timer. This API uses a promise to return the result. + +**System capability**: SystemCapability.MiscServices.Time + +**Parameters** + +| Name| Type | Mandatory| Description | +| ------ | ------- | ---- | ------------------------------------------------------------ | +| timer | number | Yes | ID of the timer. | + +**Example** + + ```js +export default { + systemTimer (){ + var options = { + type: systemTimer.TIMER_TYPE_REALTIME, + repeat:false + } + let timerId = systemTimer.Timer(options) + systemTimer.startTimer(timerId, 100000) + systemTimer.stopTimer(timerId) + systemTimer.destroytTimer(timerId, 10000).then((data) => { + console.log(`systemTime.startTimer success data : ` + JSON.stringify(data)); + }).catch((error) => { + console.error(`failed to systemTime.startTimer because ` + JSON.stringify(error)); + }); + } +} + ``` diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md index c0a42b388411d02548e656ea665fc0b28207e6fd..f1586d1b2fa12c77f9052141938972c1ff3ce340 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-text.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-text.md @@ -32,16 +32,17 @@ Text(content?: string) | Name| Type| Default Value| Description| | -------- | -------- | -------- | -------- | | textAlign | [TextAlign](ts-appendix-enums.md) | TextAlign.Start | Text alignment mode of multiple lines of text.| -| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md)} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.
**NOTE**

Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect.| -| maxLines | number | Infinity | Maximum number of lines in the text.
**NOTE**

By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode.| +| textOverflow | {overflow: [TextOverflow](ts-appendix-enums.md)} | {overflow: TextOverflow.Clip} | Display mode when the text is too long.
**NOTE**
Text is truncated at the transition between words. To truncate text in the middle of a word, add **\u200B** between characters.
This attribute must be used with `maxLines` to take effect. | +| maxLines | number | Infinity | Maximum number of lines in the text.
**NOTE**
By default, text is automatically folded. If this parameter is specified, the text does not exceed the specified number of lines. If there is extra text, you can use `textOverflow` to specify the truncation mode. | | lineHeight | Length | - | Text line height. If the value is less than or equal to **0**, the line height is not limited and the font size is adaptive. If the value of the number type, the unit fp is used.| -| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: Color
} | {
type: TextDecorationType.None,
color: Color.Black
} | Style and color of the text decorative line.| +| decoration | {
type: [TextDecorationType](ts-appendix-enums.md#textdecorationtype),
color?: Color
} | {
type: TextDecorationType.None,
color: Color.Black
} | Style and color of the text decorative line.| | baselineOffset | Length | - | Offset of the text baseline.| | textCase | [TextCase](ts-appendix-enums.md#textcase) | TextCase.Normal | Text case.| | copyOption9+ | [CopyOptions](ts-appendix-enums.md) | CopyOptions.None | Whether copy and paste is allowed.| -> **NOTE**
-> The **\** component cannot contain both the text and the child component **\**. If both of them exist, only the content in **\** is displayed. +> **NOTE** +> +> The **\** component cannot contain both the text and the child component **\**. If both of them exist, only the content in **\** is displayed. ## Example diff --git a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md index ec2ef9926c71afe8e8745d8ab65a92efa6cceacf..ad421991329c3d71689e8a37bb86ee7b35e5e885 100644 --- a/en/application-dev/reference/arkui-ts/ts-basic-components-web.md +++ b/en/application-dev/reference/arkui-ts/ts-basic-components-web.md @@ -1,12 +1,14 @@ # Web -> **NOTE**
->This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> **NOTE** +> +> - This component is supported since API version 8. Updates will be marked with a superscript to indicate their earliest API version. +> - You can preview how this component looks on a real device. The preview is not yet available in the DevEco Studio Previewer. The **** component can be used to display web pages. ## Required Permissions -ohos.permission.INTERNET, required only for accessing online web pages. +ohos.permission.INTERNET, required only for accessing online web pages ## Child Components @@ -14,200 +16,1700 @@ Not supported ## APIs -- Web\(options: { src: string, controller?: WebController }\) - - Table 1 options - - | Name | Type | Mandatory | Default Value | Description | - | ---------- | ------------------------------- | ---- | ---- | ------- | - | src | string | Yes | - | Address of a web page resource.| - | controller | [WebController](#webcontroller) | No | - | Controller. | - +Web(options: { src: string, controller?: WebController }) + +**Parameters** +| Name | Type | Mandatory | Default Value | Description | +| ---------- | ------------------------------- | ---- | ---- | ------- | +| src | string | Yes | - | Address of a web page resource.| +| 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**
> -> - Transition animation is not supported. -> - Multi-instance is not supported. -> - Only local audio and video are supported for playback. +> Transition animation is not supported. ## Attributes -| Name | Type | Default Value | Description | -| ------------------ | ---------------------------------------- | ----------------- | ---------------------------------------- | -| 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. | -| 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. | -| javaScriptProxy | {
object: object,
name: string,
methodList: Array\,
controller: WebController
} | - | 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.
**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.
**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.
**methodList** indicates the methods of the JavaScript object to be registered at the application side.
**controller** indicates the controller.| -| javaScriptAccess | boolean | true | Whether JavaScript scripts can be executed. By default, JavaScript scripts can be executed. | -| 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.| -| zoomAccess | boolean | true | Whether to enable zoom gestures. By default, zoom gestures are enabled. | -| 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. | -| cacheMode | [CacheMode](#cachemode) | CacheMode.Default | Cache mode. | -| textZoomAtio | number | 100 | Text zoom ratio of the page. The default value is **100**, which indicates 100%. | -| userAgent | string | - | User agent. | + +The **\** component has network attributes. + +### domStorageAccess + +domStorageAccess(domStorageAccess: boolean) + +Sets whether to enable the DOM Storage API. By default, this feature is disabled. + +**Parameters** +| Name | Type | Mandatory | Default Value | Description | +| ---------------- | ------- | ---- | ---- | ------------------------------------ | +| domStorageAccess | boolean | Yes | false | Whether to enable the DOM Storage API.| + +**Example** + ```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) + } + } + } + ``` + +### fileFromUrlAccess9+ + +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\, + 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\ | 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**
> -> 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 The universal events are not supported. -| Name | Description | -| ---------------------------------------- | ---------------------------------------- | -| onAlert(callback: (event?: { url: string; message: string; result: [JsResult](#jsresult) }) => boolean) |

Triggered when **alert()** is invoked to display an alert dialog box on the web page.
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 **\** component of the user's operation.
**url**: URL of the web page where the dialog box is displayed.
**message**: information displayed in the dialog box.
**JsResult**: the user's operation.

| -| onBeforeUnload(callback: (event?: { url: string; message: string; result: [JsResult](#jsresult) }) => boolean) |

Triggered when the current page is about to exit after the user refreshes or closes the page.
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 **\** component of the user's operation.
**url**: URL of the web page where the dialog box is displayed.
**message**: information displayed in the dialog box.
**JsResult**: the user's operation.

| -| onConfirm(callback: (event?: { url: string; message: string; result: [JsResult](#jsresult) }) => boolean) |

Triggered when **confirm()** is invoked by the web page.
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 **\** component of the user's operation.
**url**: URL of the web page where the dialog box is displayed.
**message**: information displayed in the dialog box.
**JsResult**: the user's operation.

| -| onPrompt9+(callback: (event?: { url: string; message: string; value: string; result: [JsResult](#jsresult) }) => boolean) |

Triggered when **prompt()** is invoked by the web page.
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 **\** component of the user's operation.
**url**: URL of the web page where the dialog box is displayed.
**message**: information displayed in the dialog box.
**value**: default value in the dialog box.
**JsResult**: the user's operation and dialog box content.

| -| onConsole(callback: (event?: { message: [ConsoleMessage](#consolemessage) }) => boolean) |

Triggered when the host application is notified of a JavaScript console message.
**message**: console message.

| -| onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisposition: string, mimetype: string, contentLength: number }) => void) |

Triggered when a download task starts on the web page.
**url**: URL for the download task.
**userAgent**: name of the user agent (UA) for the download task.
**contentDisposition**: Content-Disposition response header returned by the server, which may be empty.
**mimetype**: content media type (MIME) returned by the server.
**contentLength**: length of the file returned by the server.

| -| onErrorReceive(callback: (event?: { request: [WebResourceRequest](#webresourceerror), error: [WebResourceError](#webresourceerror) }) => void) |

Triggered when an error occurs during web page loading.
For better results, simplify the implementation logic in the callback.
**request**: encapsulation of a web page request.
**error**: encapsulation of a web page resource loading error.

| -| onHttpErrorReceive(callback: (event?: { request: [WebResourceRequest](#webresourceerror), response: [WebResourceResponse](#webresourceresponse) }) => void) |

Triggered when an HTTP error (the response code is greater than or equal to 400) occurs during web page resource loading.
**request**: encapsulation of a web page request.
**response**: encapsulation of a web page response.

| -| 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.
**url**: URL of the page.

| -| onPageEnd(callback: (event?: { url: string }) => void) |

Triggered when the web page loading is complete. This API is triggered only for the main frame content.
**url**: URL of the page.

| -| onProgressChange(callback: (event?: { newProgress: number }) => void) |

Triggered when the web page loading progress changes.
**newProgress**: new loading progress. The value is an integer ranging from 0 to 100.

| -| onTitleReceive(callback: (event?: { title: string }) => void) |

Triggered when the document title of the web page is changed.
**title**: document title.

| -| onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void) |

Triggered when loading of the web page is complete. This callback function is used by an application to update the historical link it accessed.
**url**: URL to be accessed.
**isRefreshed**: whether the page is reloaded. The value **true** means that the page is reloaded, and **false** means that the page is newly loaded.

| -| onRenderExited(callback: (event?: { renderExitReason: [RenderExitReason](#renderexitreason) }) => void) |

Triggered when the rendering process exits abnormally.
**renderExitReason**: cause for the abnormal exit of the rendering process.

| -| onShowFileSelector(callback: (event?: { result: [FileSelectorResult](#fileselectorresult), fileSelector: [FileSelectorParam](#fileselectorparam) }) => void) |

Triggered to process an HTML form whose input type is **file**, in response to the tapping of the **Select File** button.
**result**: file selection result to be sent to the web component.
**fileSelector**: information about the file selector.

| -| onUrlLoadIntercept(callback: (event?: { data:string \| [WebResourceRequest](#webresourcerequest) }) => boolean) |

Triggered before the **\** component loads the URL to determine whether to block the access. The callback returns **true** if the access is blocked, and **false** otherwise.
**data**: URL information.

| - -### ConsoleMessage - -- APIs - - | Name | Description | - | ------------------------------- | ---------------------- | - | getLineNumber(): number | Obtains the number of rows in the **ConsoleMessage**. | - | getMessage(): string | Obtains the log information of the **ConsoleMessage**.| - | getMessageLevel(): MessageLevel | Obtains the log information level of the **ConsoleMessage**.| - | getSourceId(): string | Obtains the path and name of the web page source file. | - -- MessageLevel enums - - | Name | Description | - | ----- | :---- | - | Debug | Debug level.| - | Error | Error level.| - | Info | Information level.| - | Log | Log level.| - | Warn | Warning level. | - -### JsResult - -Provides the result returned to the **\** component to indicate the user operation performed in the dialog box. - -- APIs - - | Name | Description | - | --------------------- | ----------------------- | - | handleCancel(): void |

The user's cancel operation in the dialog box.

| - | handleConfirm(): void |

The user's confirm operation in the dialog box.

| - | handlePromptConfirm9+(result: string): void |

The user's confirm operation in the dialog box as well as the dialog box content.

| - -### WebResourceError - -- APIs - - | Name | Description | - | ---------------------- | ------------ | - | getErrorCode(): number | Obtains the error code for resource loading. | - | getErrorInfo(): string | Obtains error information about resource loading.| - -### WebResourceRequest - -- APIs - - | Name | Description | - | ---------------------------------------- | -------------------- | - | getRequestHeader(): Array\<[Header](#header)\> | Obtains the information about the resource request header. | - | getRequestUrl(): string | Obtains the URL of the resource request. | - | isMainFrame(): boolean | Checks whether the resource request is in the main frame. | - | isRedirect(): boolean | Checks whether the resource request is redirected by the server. | - | isRequestGesture(): boolean | Checks whether the resource request is associated with a gesture (for example, a tap).| - -### Header +### onAlert + +onAlert(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) + +Triggered when **alert()** is invoked to display an alert dialog box on 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 **\** 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 }) + .onAlert((event) => { + AlertDialog.show({ + title: 'title', + message: 'text', + confirm: { + value: 'onAlert', + action: () => { + event.result.handleConfirm() + } + }, + cancel: () => { + event.result.handleCancel() + } + }) + return true; + }) + } + } + } + ``` + +### onBeforeUnload + +onBeforeUnload(callback: (event?: { url: string; message: string; result: JsResult }) => boolean) + +Triggered when the current page is about to exit after the user refreshes or closes the page. + +**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 **\** 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 }) + .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 **\** 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; + }) + } + } + } + ``` + +### onPrompt9+ + +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 **\** 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); + }) + } + } + } + ``` + +### onShowFileSelector9+ + +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 **\** 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 = [ + '/data/storage/el2/base/test', + ] + event.result.handleFileList(fileList) + } + }, + cancel: () => { + let fileList: Array = [] + event.result.handleFileList(fileList) + } + }) + return true; + }) + } + } + } + ``` + +### onUrlLoadIntercept + +onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) + +Triggered when the **\** 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; + }) + } + } + } + ``` + +### onInterceptRequest9+ + +onInterceptRequest9+(callback: (event?: { request: WebResourceRequest}) => WebResourceResponse) + +Triggered when the **\** 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 = "\n" + + "\n"+ + "\n"+ + "intercept test\n"+ + "\n"+ + "\n"+ + "

intercept test

\n"+ + "\n"+ + "" + 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; + }) + } + } + } + ``` + +### onHttpAuthRequest9+ + +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; + }) + } + } + ``` +### onPermissionRequest9+ + +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 **\** 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 **\** component of the user's cancel operation in the dialog box. + +### handleConfirm + +handleConfirm(): void + +Notifies the **\** component of the user's confirm operation in the dialog box. + +### handlePromptConfirm9+ + +handlePromptConfirm(result: string): void + +Notifies the **\** 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\ + +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 **\** 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 | 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.| +getReasonMessage(): string -### 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 | -| -------------------------- | ----------------- | -| 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. | +### getResponseCode -### MixedMode +getResponseCode(): number -| 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. | +Obtains the status code of the resource response. -### 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. | +**Return value** +| Type | Description | +| ------ | ----------- | +| number | Status code of the resource response.| -### FileSelectorResult -Notifies the **\** component of the file selection result. +### getResponseData -- APIs +getResponseData(): string - | Name | Description | - | ---------------------------------------------- | ------------------------------------------------------------ | - | handleFileList(fileList: Array\): void | Instructs the **\** component to select a file.
**fileList**: list of files to operate. | +Obtains the data in the resource response. -### FileSelectorParam -- APIs +**Return value** +| Type | Description | +| ------ | --------- | +| string | Data in the resource response.| - | Name | Description | - | -------------------------------- | ------------ | - | getTitle(): string | Obtains the title of the file selector. | - | getMode(): FileSelectorMode | Obtains the mode of the file selector. | - | getAcceptType(): Array\ | Obtains the file filtering type. | - | isCapture(): boolean | Checks whether multimedia capabilities are invoked.| +### getResponseEncoding -### 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. | +getResponseEncoding(): string + +Obtains the encoding string of the resource response. + +**Return value** +| Type | Description | +| ------ | ---------- | +| string | Encoding string of the resource response.| + +### getResponseHeader + +getResponseHeader() : Array\ + +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.| + +### setResponseData9+ + +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.| + +### setResponseEncoding9+ + +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.| + +### setResponseMimeType9+ + +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.| + +### setReasonMessage9+ + +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.| + +### setResponseHeader9+ + +setResponseHeader(header: Array\) + +Sets the resource response header. + +**Parameters** +| Name | Type | Mandatory | Default Value | Description | +| ------ | -------------------------- | ---- | ---- | ---------- | +| header | Array\<[Header](#header)\> | Yes | - | Resource response header to set.| + +### setResponseCode9+ + +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.| + +## FileSelectorResult9+ + +Notifies the **\** component of the file selection result. For details about the sample code, see [onShowFileSelector](#onshowfileselector9). + +### handleFileList9+ + +handleFileList(fileList: Array\): void + +Instructs the **\** component to select a file. + +**Parameters** +| Name | Type | Mandatory | Default Value | Description | +| -------- | --------------- | ---- | ---- | ------------ | +| fileList | Array\ | Yes | - | List of files to operate.| + +## FileSelectorParam9+ + +Implements the **FileSelectorParam** object. For details about the sample code, see [onShowFileSelector](#onshowfileselector9). + +### getTitle9+ + +getTitle(): string + +Obtains the title of the file selector. + +**Return value** +| Type | Description | +| ------ | ---------- | +| string | Title of the file selector.| + +### getMode9+ + +getMode(): FileSelectorMode + +Obtains the mode of the file selector. + +**Return value** +| Type | Description | +| ---------------------------------------- | ----------- | +| [FileSelectorMode](#fileselectormode)| Mode of the file selector.| + +### getAcceptType9+ + +getAcceptType(): Array\ + +Obtains the file filtering type. + +**Return value** +| Type | Description | +| --------------- | --------- | +| Array\ | File filtering type.| + +### isCapture9+ + +isCapture(): boolean + +Checks whether multimedia capabilities are invoked. + +**Return value** +| Type | Description | +| ------- | ------------ | +| boolean | Whether multimedia capabilities are invoked.| + +## HttpAuthHandler9+ + +Implements the **HttpAuthHandler** object. For details about the sample code, see [onHttpAuthRequest](#onhttpauthrequest9). + +### cancel9+ + +cancel(): void + +Cancels HTTP authentication as requested by the user. + +### confirm9+ + +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.| + +### isHttpAuthInfoSaved9+ + +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.| + +## PermissionRequest9+ + +Implements the **PermissionRequest** object. For details about the sample code, see [onPermissionRequest](#onpermissionrequest9). + +### deny9+ + +deny(): void + +Denies the permission requested by the web page. + +### getOrigin9+ + +getOrigin(): string + +Obtains the origin of this web page. + +**Return value** + +| Type | Description | +| ------- | --------------------- | +| string | Origin of the web page that requests the permission.| + +### getAccessibleResource9+ + +getAccessibleResource(): Array\ + +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\ | List of accessible resources requested by the web page.| + +### grant9+ + +grant(resources: Array\): void + +Grants the permission for resources requested by the web page. + +**Parameters** + +| Name | Type | Mandatory| Default Value| Description | +| --------- | --------------- | ---- | ----- | ---------------------- | +| resources | Array\ | Yes | - | List of accessible resources requested by the web page.| ## WebController @@ -219,35 +1721,134 @@ Defines a **WebController** to control the behavior of the **\** component. 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(): boolean 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(): boolean 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(step: number): boolean Indicates whether a specific number of steps forward or backward can be performed on the current page. -- Parameters - - | 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.| - -- Return value - - | Type | Description | - | ------- | --------- | - | boolean | Whether to go forward or backward from the current page.| +**Parameters** + +| 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.| + +**Return value** +| Type | Description | +| ------- | --------- | +| 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 @@ -255,17 +1856,25 @@ backward(): void Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**. -### deleteJavaScriptRegister - -deleteJavaScriptRegister(name: string): void - -Deletes a specific application JavaScript object that is registered with the window through **registerJavaScriptProxy**. - -- 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(); + + build() { + Column() { + Button('backward') + .onClick(() => { + this.controller.backward(); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` ### forward @@ -273,27 +1882,278 @@ forward(): void 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 }) + } + } + } + ``` + +### backOrForward9+ + +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(): HitTestType Obtains the element type of the area being clicked. -- HitTestType enums - - | Name | Description | - | ------------- | ------------------------ | - | EditText | Editable area. | - | Email | Email address. | - | HttpAnchor | Hyperlink where **src** is **http**. | - | HttpAnchorImg | Image with a hyperlink, where **src** is **http**.| - | Img | HTML::img tag. | - | Map | Geographical address. | - | Unknown | Unknown content. | +**Return value** +| Type | Description | +| ------------------------------- | ----------- | +| [HitTestType](#hittesttype)| Element type of the area being clicked.| + +**Example** + ```ts + // xxx.ets + @Entry + @Component + 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 }) + } + } + } + ``` + +### getHitTestValue9+ +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 }) + } + } + } + ``` + +### getWebId9+ +getWebId(): number + +Obtains the index value of this **\** component, which can be used for **\** component management. + +**Return value** +| Type | Description | +| ------ | ------------ | +| number | Index value of the current **\** 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 }) + } + } + } + ``` + +### getTitle9+ +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 }) + } + } + } + ``` + +### getPageHeight9+ +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 }) + } + } + } + ``` + +### getDefaultUserAgent9+ +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(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. @@ -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 **\** component as a non-encoded string in a manner similar to **loadUrl**. -- options - - | Name | Type | Mandatory | Default Value | Description | - | ---------- | ------ | ---- | ---- | ---------------------------------------- | - | data | string | Yes | - | Character string obtained after being Base64 or URL encoded. | - | mimeType | string | Yes | - | Media type (MIME). | - | encoding | string | Yes | - | Encoding type, which can be Base64 or URL. | - | baseUrl | string | No | - | URL (HTTP/HTTPS/data compliant), which is assigned by the **\** 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.| +**Parameters** +| Name | Type | Mandatory | Default Value | Description | +| ---------- | ------ | ---- | ---- | ---------------------------------------- | +| data | string | Yes | - | Character string obtained after being Base64 or URL encoded. | +| mimeType | string | Yes | - | Media type (MIME). | +| encoding | string | Yes | - | Encoding type, which can be Base64 or URL. | +| baseUrl | string | No | - | URL (HTTP/HTTPS/data compliant), which is assigned by the **\** 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.| + +**Example** + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + + build() { + Column() { + Button('loadData') + .onClick(() => { + this.controller.loadData({ + data: "Source:
source
", + mimeType: "text/html", + encoding: "UTF-8" + }); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` ### loadUrl -loadUrl(options:{ url: string, headers?: Array\ }): void +loadUrl(options: { url: string | Resource, headers?: Array\ }) 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 **registerJavaScriptProxy** is still valid on a new page navigated to through **loadUrl**. - -- options - - | Name | Type | Mandatory | Default Value | Description | - | ------- | ------------------------------ | ---- | ---- | -------------- | - | url | string | Yes | - | URL to load. | - | headers | Array\<[Header](#header)\> | No | [] | Additional HTTP request header of the URL.| +The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**. + +**Parameters** +| Name | Type | Mandatory | Default Value | Description | +| ------- | -------------------------- | ---- | ---- | -------------- | +| url | string | Yes | - | URL to load. | +| 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 @@ -334,130 +2236,1228 @@ onActive(): void Invoked to instruct the **\** 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(): void Invoked to instruct the **\** 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 }) + } + } + } + ``` + +### zoomIn9+ +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 }) + } + } + } + ``` + +### zoomOut9+ +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(): void +refresh() Invoked to instruct the **\** component to refresh the web page. -### registerJavaScriptProxy - -registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\ }): void - -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. +**Example** + ```ts + // xxx.ets + @Entry + @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 | - | ---------- | --------------- | ---- | ---- | ---------------------------------------- | - | 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\ | Yes | - | Methods of the JavaScript object to be registered at the application side. | +registerJavaScriptProxy(options: { object: object, name: string, methodList: Array\ }) + +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. + +**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\ | 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 + + + + + + Hello world! + + + + + ``` ### 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**. -- 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 + + + + + + Hello world! + + + - | 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(): void +stop() 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(): void 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 }) + } + } + } + ``` + +### getCookieManager9+ getCookieManager(): WebCookie Obtains the cookie management object of the **\** component. -- Return value - | Type | Description | - | --------- | ---------------------------------------- | - | WebCookie | Cookie management object. For details, see [WebCookie](#webcookie).| + +**Return value** +| Type | Description | +| --------- | ---------------------------------------- | +| 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 }) + } + } + } + ``` + +## HitTestValue9+ +Implements the **HitTestValue** object. For details about the sample code, see [getHitTestValue](#gethittestvalue9). + +### getType9+ +getType(): HitTestType + +Obtains the element type of the area being clicked. + +**Return value** +| Type | Description | +| ------------------------------- | ------------- | +| [HitTestType](#hittesttype)| Element type of the area being clicked.| + +### getExtra9+ +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 + Manages behavior of cookies in **\** components. All **\** components in an application share a **WebCookie**. You can use the **getCookieManager** API in **controller** to obtain the **WebCookie** for subsequent cookie management. -### setCookie + +### setCookie9+ 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 +### saveCookieSync9+ +saveCookieSync(): boolean - | 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.| +Saves this cookie in the memory to the drive. This API returns the result synchronously. + +**Return value** +| Type | Description | +| ------- | -------------------- | +| boolean | Operation result.| + +**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 }) + } + } + } + ``` + +## WebDataBase9+ +Implements the **WebDataBase** object. + +### existHttpAuthCredentials9+ + +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 }) + } + } + } + ``` + +### deleteHttpAuthCredentials9+ + +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 }) + } + } + } + ``` + +### getHttpAuthCredentials9+ + +static getHttpAuthCredentials(host: string, realm: string): Array\ + +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\ | 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 }) + } + } + } + ``` + +### saveHttpAuthCredentials9+ + +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 }) + } + } + } + ``` + +## WebStorage9+ +Implements the **WebStorage** object, which can be used to manage the Web SQL and the HTML5 Web Storage API. All **\** components in an application share one **WebStorage**. +### deleteAllData9+ +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) + } + } + } + ``` + +### deleteOrigin9+ +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) + } + } + } + ``` + +### getOrigins9+ +static getOrigins(callback: AsyncCallback>) : 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> | 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 -saveCookieSync(): boolean +### getOrigins9+ +static getOrigins() : Promise> + +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 | +| ---------------------------------------- | ---------------------------------------- | +| Promise> | Promise 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() + .then(origins => { + for (let i = 0; i < origins.length; i++) { + console.log('origin: ' + origins[i].origin); + console.log('usage: ' + origins[i].usage); + console.log('quota: ' + origins[i].quota); + } + }) + .catch(error => { + console.log('error: ' + error); + }) + }) + Web({ src: 'www.example.com', controller: this.controller }) + .databaseAccess(true) + } + } + } + ``` + +### getOriginQuota9+ +static getOriginQuota(origin : string, callback : AsyncCallback\) : void + +Obtains the storage quota of an origin in the Web SQL database, in bytes. This API uses an asynchronous callback to return the result. + +**Parameters** +| Name | Type | Mandatory | Description | +| -------- | ---------------------- | ---- | --------- | +| origin | string | Yes | Index of the origin.| +| callback | AsyncCallback\ | 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) + } + } + } + ``` + +### getOriginQuota9+ +static getOriginQuota(origin : string) : Promise\ + +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\ | 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) + } + } + } + ``` + +### getOriginUsage9+ +static getOriginUsage(origin : string, callback : AsyncCallback\) : 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\ | 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) + } + } + } + ``` + +### getOriginUsage9+ +static getOriginUsage(origin : string) : Promise\ + +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\ | 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) + } + } + } + ``` +### searchAllAsync9+ + +searchAllAsync(searchString: string): void + +Searches the web page for content that matches the keyword specified by **'searchString'** and highlights the matches on the page. This API returns the result asynchronously through [onSearchResultReceive](#onsearchresultreceive9). + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | --------------------- | +| searchString | string | Yes | - | Search keyword.| + +**Example** + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + @State searchString: string = "xxx"; + + build() { + Column() { + Button('searchString') + .onClick(() => { + this.controller.searchAllAsync(this.searchString); + }) + Button('clearMatches') + .onClick(() => { + this.controller.clearMatches(); + }) + Button('searchNext') + .onClick(() => { + this.controller.searchNext(true); + }) + Web({ src: 'www.example.com', controller: this.controller }) + .onSearchResultReceive(ret => { + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + + "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting); + }) + } + } + } + ``` + +### clearMatches9+ + +clearMatches(): void + +Clears the matches found through [searchAllAsync](#searchallasync9). + +**Example** + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + + build() { + Column() { + Button('clearMatches') + .onClick(() => { + this.controller.clearMatches(); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +### searchNext9+ + +searchNext(forward: boolean): void + +Searches for and highlights the next match. + +**Parameters** + +| Name | Type | Mandatory | Default Value | Description | +| ---- | ------ | ---- | ---- | --------------------- | +| forward | boolean | Yes | - | Whether to search forward.| + + +**Example** + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + + build() { + Column() { + Button('searchNext') + .onClick(() => { + this.controller.searchNext(true); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +### onSearchResultReceive9+ + +onSearchResultReceive(callback: (event?: {activeMatchOrdinal: number, numberOfMatches: number, isDoneCounting: boolean}) => void): WebAttribute + +Invoked to notify the caller of the search result on the web page. + +**Parameters** + +| Name | Type | Description | +| ------------------ | ------------- | ----------------------------------- | +| activeMatchOrdinal | number | Sequence number of the current match, which starts from 0.| +| numberOfMatches | number | Total number of matches.| +| isDoneCounting | boolean | Whether the search operation on the current page is complete. This API may be called multiple times until **isDoneCounting** is **true**.| + +**Example** + ```ts + // xxx.ets + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + + build() { + Column() { + Web({ src: 'www.example.com', controller: this.controller }) + .onSearchResultReceive(ret => { + console.log("on search result receive:" + "[cur]" + ret.activeMatchOrdinal + + "[total]" + ret.numberOfMatches + "[isDone]"+ ret.isDoneCounting); + }) + } + } + } + ``` + +## WebStorageOrigin9+ + +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. | + +## ProtectedResourceType9+ + +| Name | Description | Remarks | +| --------- | -------------- | -------------- | +| MidiSysex | MIDI SYSEX resources| Currently, only permission events can be reported. MIDI devices are not yet supported.| + +## WebAsyncController + +Implements the **WebAsyncController** object, which can be used to control the behavior of a **\** component with asynchronous callbacks. A **WebAsyncController **object controls one **\** component. + +### Creating an Object -Saves this cookie in the memory to the disk. This API is synchronous. -- Return value - | Type | Description | - | ------- | -------------------- | - | boolean | Returns the operation result.| -## Example - -```ts -// webComponent.ets -@Entry -@Component -struct WebComponent { - @State javaScriptAccess: boolean = true; - @State fileAccess: boolean = true; - controller: WebController = new WebController(); - build() { - Column() { - Web({ src: $rawfile('index.html'), controller: this.controller }) - .javaScriptAccess(this.javaScriptAccess) - .fileAccess(this.fileAccess) - .onPageEnd(e => { - // test() has been defined in index.html. - this.controller.runJavaScript({ script: 'test()' }); - console.log("url: ", e.url); - }) - } - } -} ``` -```html - - - - - - Hello world! - - - +webController: WebController = new WebController(); +webAsyncController: WebAsyncController = new WebAsyncController(webController); ``` -![](figures/Web.png) +### storeWebArchive9+ + +storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback\): void + +Saves the current web page. This API uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| baseName | string | Yes| Save path. The value cannot be null.| +| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
The value **false** means not to automatically generate a file name.| +| callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.| + +**Example** + + ```ts + // xxx.ets + import WebAsyncController from '@ohos.web'; + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + build() { + Column() { + Button('saveWebArchive') + .onClick(() => { + let webAsyncController = new WebAsyncController(this.controller); + webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => { + if (filename != null) { + console.info(`save web archive success: ${filename}`) + } + }); + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` + +### storeWebArchive9+ + +storeWebArchive(baseName: string, autoName: boolean): Promise\ + +Stores the current web page. This API uses an asynchronous callback to return the result. + +**Parameters** + +| Name | Type | Mandatory | Description | +| -------- | ---------------------------------------- | ---- | ----------------------------------- | +| baseName | string | Yes| Save path. The value cannot be null.| +| autoName | boolean | Yes| Determines whether to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
The value **false** means not to automatically generate a file name.| + +**Return value** + +| Type | Description | +| ---------------- | ------------------------------------------------------------ | +| Promise\ | Promise used to return the save path if the operation is successful and null otherwise. | + +**Example** + + ```ts + // xxx.ets + import WebAsyncController from '@ohos.web'; + @Entry + @Component + struct WebComponent { + controller: WebController = new WebController(); + build() { + Column() { + Button('saveWebArchive') + .onClick(() => { + let webAsyncController = new WebAsyncController(this.controller); + webAsyncController.storeWebArchive("/data/storage/el2/base/", true) + .then(filename => { + if (filename != null) { + console.info(`save web archive success: ${filename}`) + } + }) + }) + Web({ src: 'www.example.com', controller: this.controller }) + } + } + } + ``` diff --git a/en/application-dev/reference/arkui-ts/ts-media-components-video.md b/en/application-dev/reference/arkui-ts/ts-media-components-video.md index dc55a6741f7bd0bc72bb12d1238c5c1896845372..40ab09903ee74df7f88877a3d152de2e8847a53b 100644 --- a/en/application-dev/reference/arkui-ts/ts-media-components-video.md +++ b/en/application-dev/reference/arkui-ts/ts-media-components-video.md @@ -1,16 +1,16 @@ # Video -> **NOTE** -> -> This component is supported since API version 7. Updates will be marked with a superscript to indicate their earliest API version. +The **\