diff --git a/en/application-dev/database/database-relational-guidelines.md b/en/application-dev/database/database-relational-guidelines.md
index 53e3ca5aeaa25ecea55f3e27272043e6b533e594..df633d8449281b12557bb3d39f333f97148af1a4 100644
--- a/en/application-dev/database/database-relational-guidelines.md
+++ b/en/application-dev/database/database-relational-guidelines.md
@@ -7,7 +7,7 @@ A relational database (RDB) store allows you to operate local data with or witho
## Available APIs
-Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For details about the APIs, see [Relational Database](../reference/apis/js-apis-data-rdb.md).
+Most of the RDB store APIs are asynchronous interfaces, which can use a callback or promise to return the result. This document uses the promise-based APIs as an example. For more information about the APIs, see [RDB Store](../reference/apis/js-apis-data-relationalStore.md).
### Creating or Deleting an RDB Store
@@ -17,8 +17,8 @@ The following table describes the APIs for creating and deleting an RDB store.
| API | Description |
| ------------------------------------------------------------ | ------------------------------------------------------------ |
-| getRdbStoreV9(context: Context, config: StoreConfigV9, version: number): Promise<RdbStoreV9> | Obtains an **RdbStoreV9** instance. This API uses a promise to return the result. You can set parameters for the RDB store based on service requirements and call APIs to perform data operations.
- **context**: context of the application or function.
- **config**: configuration of the RDB store.
- **version**: version of the RDB store. Currently, automatic RDB upgrades and downgrades performed based on **version** is not supported.|
-| deleteRdbStoreV9(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: context of the application or function.
- **name**: name of the RDB store to delete.|
+| getRdbStore(context: Context, config: StoreConfig): Promise<RdbStore> | Obtains an **RdbStore** object. This API uses a promise to return the result. You can set parameters for the **RdbStore** object based on service requirements and use **RdbStore** APIs to perform data operations.
- **context**: application context.
- **config**: configuration of the RDB store.|
+| deleteRdbStore(context: Context, name: string): Promise<void> | Deletes an RDB store. This API uses a promise to return the result.
- **context**: application context.
- **name**: name of the RDB store to delete.|
### Managing Data in an RDB Store
@@ -33,29 +33,29 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
- | RdbStoreV9 | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.|
+ | RdbStore | insert(table: string, values: ValuesBucket): Promise<number> | Inserts a row of data into a table. This API uses a promise to return the result.
If the operation is successful, the row ID will be returned; otherwise, **-1** will be returned.
- **table**: name of the target table.
- **values**: data to be inserted into the table.|
- **Updating Data**
- Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicatesV9**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned.
+ Call **update()** to update data based on the passed data and the conditions specified by **RdbPredicates**. If the data is updated, the number of rows of the updated data will be returned; otherwise, **0** will be returned.
**Table 3** API for updating data
- | Class | API | Description |
+ | Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
- | RdbStoreV9 | update(values: ValuesBucket, predicates: RdbPredicatesV9): Promise<number> | Updates data based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. |
+ | RdbStore | update(values: ValuesBucket, predicates: RdbPredicates): Promise<number> | Updates data based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows updated.
- **values**: data to update, which is stored in **ValuesBucket**.
- **predicates**: conditions for updating data. |
- **Deleting Data**
- Call **delete()** to delete the data that meets the conditions specified by **RdbPredicatesV9**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned.
+ Call **delete()** to delete the data that meets the conditions specified by **RdbPredicates**. If the data is deleted, the number of rows of the deleted data will be returned; otherwise, **0** will be returned.
**Table 4** API for deleting data
- | Class | API | Description |
+ | Class | API | Description |
| ---------- | ---------------------------------------------------------- | ------------------------------------------------------------ |
- | RdbStoreV9 | delete(predicates: RdbPredicatesV9): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicatesV9** object. This API uses a promise to return the number of rows updated.
- **predicates**: conditions for deleting data. |
+ | RdbStore | delete(predicates: RdbPredicates): Promise<number> | Deletes data from the RDB store based on the specified **RdbPredicates** object. This API uses a promise to return the number of rows deleted.
- **predicates**: conditions for deleting data. |
- **Querying Data**
@@ -66,50 +66,48 @@ The RDB provides APIs for inserting, deleting, updating, and querying data in th
**Table 5** APIs for querying data
-
-| Class | API | Description |
-| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbStoreV9 | query(predicates: RdbPredicatesV9, columns?: Array<string>): Promise<ResultSetV9> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
-| RdbStoreV9 | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSetV9> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.|
-| RdbStoreV9 | remoteQuery(device: string, table: string, predicates: RdbPredicatesV9, columns: Array<string>): Promise<ResultSetV9> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicatesV9** that specifies the query conditions.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
+ | Class | API | Description |
+ | ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
+ | RdbStore | query(predicates: RdbPredicates, columns?: Array<string>): Promise<ResultSet> | Queries data from the RDB store based on specified conditions. This API uses a promise to return the result.
- **predicates**: conditions for querying data.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
+ | RdbStore | querySql(sql: string, bindArgs?: Array<ValueType>): Promise<ResultSet> | Queries data using the specified SQL statement. This API uses a promise to return the result.
- **sql**: SQL statement.
- **bindArgs**: arguments in the SQL statement.|
+ | RdbStore | remoteQuery(device: string, table: string, predicates: RdbPredicates, columns: Array<string>): Promise<ResultSet> | Queries data from the database of a remote device based on specified conditions. This API uses a promise to return the result.
- **device**: network ID of the remote device.
- **table**: name of the table to be queried.
- **predicates**: **RdbPredicates** that specifies the query condition.
- **columns**: columns to query. If this parameter is not specified, the query applies to all columns.|
### Using Predicates
-The **RDB** module provides **RdbPredicatesV9** for you to set database operation conditions.
+The **RDB** module provides **RdbPredicates** for you to set database operation conditions.
-The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-rdb.md#rdbpredicates).
+The following table lists common predicates. For more information about predicates, see [**RdbPredicates**](../reference/apis/js-apis-data-relationalStore.md#rdbpredicates).
**Table 6** APIs for using RDB store predicates
-| Class | API | Description |
+| Class | API | Description |
| --------------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbPredicatesV9 | equalTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. |
-| RdbPredicatesV9 | notEqualTo(field: string, value: ValueType): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. |
-| RdbPredicatesV9 | or(): RdbPredicatesV9 | Adds the OR condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the OR condition. |
-| RdbPredicatesV9 | and(): RdbPredicatesV9 | Adds the AND condition to the **RdbPredicatesV9**.
- **RdbPredicatesV9**: **RdbPredicatesV9** with the AND condition. |
-| RdbPredicatesV9 | contains(field: string, value: string): RdbPredicatesV9 | Sets an **RdbPredicatesV9** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match.
- **RdbPredicatesV9**: **RdbPredicatesV9** object created. |
+| RdbPredicates | equalTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.|
+| RdbPredicates | notEqualTo(field: string, value: ValueType): RdbPredicates | Sets an **RdbPredicates** to search for the data that is not equal to the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.|
+| RdbPredicates | or(): RdbPredicates | Adds the OR condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the OR condition.|
+| RdbPredicates | and(): RdbPredicates | Adds the AND condition to the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** with the AND condition.|
+| RdbPredicates | contains(field: string, value: string): RdbPredicates | Sets an **RdbPredicates** to search for the data that contains the specified value.
- **field**: column name in the database table.
- **value**: value to match the **RdbPredicates**.
- **RdbPredicates**: **RdbPredicates** object created.|
### Using the Result Set
-You can use the APIs provided by **ResultSetV9** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result.
+You can use the APIs provided by **ResultSet** to traverse and access the data you have queried. A result set can be regarded as a row of data in the queried result.
-For details about how to use result set APIs, see [Result Set](../reference/apis/js-apis-data-resultset.md).
+For details about how to use **ResultSet** APIs, see [ResultSet](../reference/apis/js-apis-data-relationalStore.md#resultset).
-> **NOTICE**
->
+> **NOTICE**
> After a result set is used, you must call the **close()** method to close it explicitly.
**Table 7** APIs for using the result set
| Class | API | Description |
| ----------- | ---------------------------------------- | ------------------------------------------ |
-| ResultSetV9 | goToFirstRow(): boolean | Moves to the first row of the result set. |
-| ResultSetV9 | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. |
-| ResultSetV9 | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.|
-| ResultSetV9 | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. |
-| ResultSetV9 | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. |
-| ResultSetV9 | close(): void | Closes the result set. |
+| ResultSet | goToFirstRow(): boolean | Moves to the first row of the result set. |
+| ResultSet | getString(columnIndex: number): string | Obtains the value in the form of a string based on the specified column and current row. |
+| ResultSet | getBlob(columnIndex: number): Uint8Array | Obtains the value in the form of a byte array based on the specified column and the current row.|
+| ResultSet | getDouble(columnIndex: number): number | Obtains the value in the form of double based on the specified column and current row. |
+| ResultSet | getLong(columnIndex: number): number | Obtains the value in the form of a long integer based on the specified column and current row. |
+| ResultSet | close(): void | Closes the result set. |
@@ -117,7 +115,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis
> **NOTE**
>
-> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore V9**.
+> - The **ohos.permission.DISTRIBUTED_DATASYNC** permission is required for calling the **setDistributedTables**, **obtainDistributedTableName**, **sync**, **on** and **off** APIs of **RdbStore**.
> - The devices must be connected over network before the distributed tables are used. For details about the APIs and usage, see [Device Management](../reference/apis/js-apis-device-manager.md).
**Setting Distributed Tables**
@@ -126,7 +124,7 @@ For details about how to use result set APIs, see [Result Set](../reference/apis
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbStoreV9 | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.|
+| RdbStore | setDistributedTables(tables: Array\): Promise\ | Sets distributed tables. This API uses a promise to return the result.
- **tables**: names of the distributed tables to set.|
**Obtaining the Distributed Table Name for a Remote Device**
@@ -136,7 +134,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbStoreV9 | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.|
+| RdbStore | obtainDistributedTableName(device: string, table: string): Promise\ | Obtains the distributed table name for a remote device based on the local table name. The distributed table name is required when the RDB store of a remote device is queried. This API uses a promise to return the result.
- **device**: remote device.
- **table**: local table name.|
**Synchronizing Data Between Devices**
@@ -144,7 +142,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbStoreV9 | sync(mode: SyncMode, predicates: RdbPredicatesV9): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
+| RdbStore | sync(mode: SyncMode, predicates: RdbPredicates): Promise\> | Synchronizes data between devices. This API uses a promise to return the result.
- **mode**: synchronization mode. **SYNC_MODE_PUSH** means to push data from the local device to a remote device. **SYNC_MODE_PULL** means to pull data from a remote device to the local device.
- **predicates**: specifies the data and devices to synchronize.
- **string**: device ID.
- **number**: synchronization status of each device. The value **0** indicates a successful synchronization. Other values indicate a synchronization failure.|
**Registering an RDB Store Observer**
@@ -152,7 +150,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbStoreV9 | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.|
+| RdbStore | on(event: 'dataChange', type: SubscribeType, observer: Callback\>): void | Registers an observer for this RDB store to subscribe to distributed data changes. When data in the RDB store changes, a callback will be invoked to return the data changes.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer that listens for data changes in the RDB store.|
**Unregistering an RDB Store Observer**
@@ -160,7 +158,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | ------------------------------------------------------------ | ------------------------------------------------------------ |
-| RdbStoreV9 | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.|
+| RdbStore | off(event:'dataChange', type: SubscribeType, observer: Callback\>): void; | Unregisters the observer of the specified type from the RDB store. This API uses an asynchronous callback to return the result.
- **type**: subscription type. **SUBSCRIBE_TYPE_REMOTE**: subscribes to remote data changes.
- **observer**: observer to unregister.|
### Backing Up and Restoring an RDB Store
@@ -170,7 +168,7 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | --------------------------------------------- | ------------------------------------------------------------ |
-| RdbStoreV9 | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.|
+| RdbStore | backup(destName: string): Promise<void> | Backs up an RDB store. This API uses a promise to return the result.
- **destName**: name of the RDB backup file.|
**Restoring an RDB Store**
@@ -178,17 +176,17 @@ You can obtain the distributed table name for a remote device based on the local
| Class | API | Description |
| ---------- | --------------------------------------------- | ------------------------------------------------------------ |
-| RdbStoreV9 | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.|
+| RdbStore | restore(srcName: string): Promise<void> | Restores an RDB store from a backup file. This API uses a promise to return the result.
- **srcName**: name of the backup file used to restore the RDB store.|
-**Transaction**
+### Transaction
Table 15 Transaction APIs
| Class | API | Description |
| -------- | ----------------------- | --------------------------------- |
-| RdbStoreV9 | beginTransaction(): void | Starts the transaction before executing SQL statements.|
-| RdbStoreV9 | commit(): void | Commits the executed SQL statements. |
-| RdbStoreV9 | rollBack(): void | Rolls back the SQL statements that have been executed. |
+| RdbStore | beginTransaction(): void | Starts the transaction before executing SQL statements.|
+| RdbStore | commit(): void | Commits the executed SQL statements. |
+| RdbStore | rollBack(): void | Rolls back the SQL statements that have been executed. |
## How to Develop
@@ -203,27 +201,27 @@ Table 15 Transaction APIs
FA model:
```js
- import data_rdb from '@ohos.data.rdb'
+ import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
import featureAbility from '@ohos.ability.featureAbility'
let context = featureAbility.getContext()
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
- const STORE_CONFIGV9 = { name: "RdbTest.db",
+ const STORE_CONFIG = { name: "RdbTest.db",
securityLevel: data_rdb.SecurityLevel.S1}
- data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) {
- rdbStoreV9.executeSql(CREATE_TABLE_TEST)
+ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
+ rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
Stage model:
```ts
- import data_rdb from '@ohos.data.rdb'
+ import data_rdb from '@ohos.data.relationalStore'
// Obtain the context.
- import Ability from '@ohos.application.Ability'
+ import UIAbility from '@ohos.app.ability.UIAbility';
let context = null
- class MainAbility extends Ability {
+ class EntryAbility extends UIAbility {
onWindowStageCreate(windowStage) {
context = this.context
}
@@ -231,10 +229,10 @@ Table 15 Transaction APIs
const CREATE_TABLE_TEST = "CREATE TABLE IF NOT EXISTS test (" + "id INTEGER PRIMARY KEY AUTOINCREMENT, " + "name TEXT NOT NULL, " + "age INTEGER, " + "salary REAL, " + "blobType BLOB)";
- const STORE_CONFIGV9 = { name: "rdbstore.db",
+ const STORE_CONFIG = { name: "rdbstore.db",
securityLevel: data_rdb.SecurityLevel.S1}
- data_rdb.getRdbStoreV9(context, STORE_CONFIGV9, 1, function (err, rdbStoreV9) {
- rdbStoreV9.executeSql(CREATE_TABLE_TEST)
+ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
+ rdbStore.executeSql(CREATE_TABLE_TEST)
console.info('create table done.')
})
```
@@ -248,14 +246,29 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- var u8 = new Uint8Array([1, 2, 3])
+ let u8 = new Uint8Array([1, 2, 3])
const valueBucket = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }
- let insertPromise = rdbStoreV9.insert("test", valueBucket)
+ let insertPromise = rdbStore.insert("test", valueBucket)
+ ```
+
+ ```js
+ // Use a transaction to insert data.
+ beginTransaction()
+ try {
+ let u8 = new Uint8Array([1, 2, 3])
+ const valueBucket1 = { "name": "Tom", "age": 18, "salary": 100.5, "blobType": u8 }
+ const valueBucket2 = { "name": "Jam", "age": 19, "salary": 200.5, "blobType": u8 }
+ let insertPromise1 = rdbStore.insert("test", valueBucket1)
+ let insertPromise2 = rdbStore.insert("test", valueBucket2)
+ commit()
+ } catch (e) {
+ rollBack()
+ }
```
3. Query data.
- (1) Create an **RdbPredicatesV9** object to specify query conditions.
+ (1) Create an **RdbPredicates** object to specify query conditions.
(2) Call the **query()** API to query data.
@@ -264,17 +277,17 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- let predicatesV9 = new data_rdb.RdbPredicatesV9("test");
- predicatesV9.equalTo("name", "Tom")
- let promisequery = rdbStoreV9.query(predicatesV9)
- promisequery.then((resultSetV9) => {
- resultSetV9.goToFirstRow()
- const id = resultSetV9.getLong(resultSetV9.getColumnIndex("id"))
- const name = resultSetV9.getString(resultSetV9.getColumnIndex("name"))
- const age = resultSetV9.getLong(resultSetV9.getColumnIndex("age"))
- const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("salary"))
- const blobType = resultSetV9.getBlob(resultSetV9.getColumnIndex("blobType"))
- resultSetV9.close()
+ let predicates = new data_rdb.RdbPredicates("test");
+ predicates.equalTo("name", "Tom")
+ let promisequery = rdbStore.query(predicates)
+ promisequery.then((resultSet) => {
+ resultSet.goToFirstRow()
+ const id = resultSet.getLong(resultSet.getColumnIndex("id"))
+ const name = resultSet.getString(resultSet.getColumnIndex("name"))
+ const age = resultSet.getLong(resultSet.getColumnIndex("age"))
+ const salary = resultSet.getDouble(resultSet.getColumnIndex("salary"))
+ const blobType = resultSet.getBlob(resultSet.getColumnIndex("blobType"))
+ resultSet.close()
})
```
@@ -302,7 +315,7 @@ Table 15 Transaction APIs
context.requestPermissionsFromUser(['ohos.permission.DISTRIBUTED_DATASYNC'], 666, function (result) {
console.info(`result.requestCode=${result.requestCode}`)
})
- let promise = rdbStoreV9.setDistributedTables(["test"])
+ let promise = rdbStore.setDistributedTables(["test"])
promise.then(() => {
console.info("setDistributedTables success.")
}).catch((err) => {
@@ -312,7 +325,7 @@ Table 15 Transaction APIs
5. Synchronize data across devices.
- (1) Construct an **RdbPredicatesV9** object to specify remote devices within the network to be synchronized.
+ (1) Construct an **RdbPredicates** object to specify remote devices within the network to be synchronized.
(2) Call **rdbStore.sync()** to synchronize data.
@@ -321,9 +334,9 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- let predicateV9 = new data_rdb.RdbPredicatesV9('test')
- predicateV9.inDevices(['12345678abcde'])
- let promise = rdbStoreV9.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicateV9)
+ let predicate = new data_rdb.RdbPredicates('test')
+ predicate.inDevices(['12345678abcde'])
+ let promise = rdbStore.sync(data_rdb.SyncMode.SYNC_MODE_PUSH, predicate)
promise.then((result) => {
console.log('sync done.')
for (let i = 0; i < result.length; i++) {
@@ -350,7 +363,7 @@ Table 15 Transaction APIs
}
try {
- rdbStoreV9.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver)
+ rdbStore.on('dataChange', data_rdb.SubscribeType.SUBSCRIBE_TYPE_REMOTE, storeObserver)
} catch (err) {
console.log('register observer failed')
}
@@ -365,8 +378,8 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- let tableName = rdbStoreV9.obtainDistributedTableName(deviceId, "test");
- let resultSetV9 = rdbStoreV9.querySql("SELECT * FROM " + tableName)
+ let tableName = rdbStore.obtainDistributedTableName(deviceId, "test");
+ let resultSet = rdbStore.querySql("SELECT * FROM " + tableName)
```
8. Query data of a remote device.
@@ -379,17 +392,17 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- let rdbPredicateV9 = new data_rdb.RdbPredicatesV9('employee')
- predicatesV9.greaterThan("id", 0)
- let promiseQuery = rdbStoreV9.remoteQuery('12345678abcde', 'employee', rdbPredicateV9)
- promiseQuery.then((resultSetV9) => {
- while (resultSetV9.goToNextRow()) {
- let idx = resultSetV9.getLong(0);
- let name = resultSetV9.getString(1);
- let age = resultSetV9.getLong(2);
+ let rdbPredicate = new data_rdb.RdbPredicates('employee')
+ predicates.greaterThan("id", 0)
+ let promiseQuery = rdbStore.remoteQuery('12345678abcde', 'employee', rdbPredicate)
+ promiseQuery.then((resultSet) => {
+ while (resultSet.goToNextRow()) {
+ let idx = resultSet.getLong(0);
+ let name = resultSet.getString(1);
+ let age = resultSet.getLong(2);
console.info(idx + " " + name + " " + age);
}
- resultSetV9.close();
+ resultSet.close();
}).catch((err) => {
console.info("failed to remoteQuery, err: " + err)
})
@@ -402,7 +415,7 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- let promiseBackup = rdbStoreV9.backup("dbBackup.db")
+ let promiseBackup = rdbStore.backup("dbBackup.db")
promiseBackup.then(() => {
console.info('Backup success.')
}).catch((err) => {
@@ -414,7 +427,7 @@ Table 15 Transaction APIs
The sample code is as follows:
```js
- let promiseRestore = rdbStoreV9.restore("dbBackup.db")
+ let promiseRestore = rdbStore.restore("dbBackup.db")
promiseRestore.then(() => {
console.info('Restore success.')
}).catch((err) => {
diff --git a/en/application-dev/device/inputdevice-guidelines.md b/en/application-dev/device/inputdevice-guidelines.md
index d29d1ae340f5f2c569559791fe2b001e07adce4a..da6eef71d750b74e01d1ea8a9eaaf49b1bf598cb 100644
--- a/en/application-dev/device/inputdevice-guidelines.md
+++ b/en/application-dev/device/inputdevice-guidelines.md
@@ -16,8 +16,8 @@ The following table lists the common APIs for input device management. For detai
| Instance| API | Description|
| ----------- | ------------------------------------------------------------ | -------------------------- |
-| inputDevice | function getDeviceList(callback: AsyncCallback\>): void; | Obtains the list of input devices.|
-| inputDevice | function getKeyboardType(deviceId: number, callback: AsyncCallback\): void; | Obtains the keyboard type of the input device.|
+| inputDevice | function getDeviceList(): Promise\>; | Obtains the list of input devices.|
+| inputDevice | function getKeyboardType(deviceId: number): Promise\; | Obtains the keyboard type of the input device.|
| inputDevice | function on(type: "change", listener: Callback\): void; | Enables listening for device hot swap events.|
| inputDevice | function off(type: "change", listener?: Callback\): void; | Disables listening for device hot swap events.|
@@ -51,7 +51,7 @@ try {
// 2. Listen for device hot swap events.
inputDevice.on("change", (data) => {
console.log(`Device event info: ${JSON.stringify(data)}`);
- inputDevice.getKeyboardType(data.deviceId, (error, type) => {
+ inputDevice.getKeyboardType(data.deviceId).then((type) => {
console.log("The keyboard type is: " + type);
if (type === inputDevice.KeyboardType.ALPHABETIC_KEYBOARD && data.type == 'add') {
// The physical keyboard is inserted.
diff --git a/en/application-dev/notification/Readme-EN.md b/en/application-dev/notification/Readme-EN.md
index dccfc8dbc4c59611db4aa53ff8a5a295cbba4d46..bf85581053f30d6aa56e0218c51339ef6ee3f268 100644
--- a/en/application-dev/notification/Readme-EN.md
+++ b/en/application-dev/notification/Readme-EN.md
@@ -1,9 +1,10 @@
-# Common Event and Notification
+# Notification
+
+- [Notification Overview](notification-overview.md)
+- [Notification Subscription (Open Only to System Applications)](notification-subscription.md)
+- [Enabling Notification](notification-enable.md)
+- Publishing a Notification
+ - [Publishing a Basic Notification](text-notification.md)
+ - [Publishing a Progress Notification](progress-bar-notification.md)
+ - [Adding a WantAgent Object to a Notification](notification-with-wantagent.md)
-- [Common Event and Notification Overview](notification-brief.md)
-- [Common Event Development](common-event.md)
-- [Notification Development](notification-guidelines.md)
-- Agent-Powered Scheduled Reminder
- - [Agent-Powered Scheduled Reminder Overview](background-agent-scheduled-reminder-overview.md)
- - [Agent-Powered Scheduled Reminder Development](background-agent-scheduled-reminder-guide.md)
-- [Debugging Assistant Usage](assistant-guidelines.md)
diff --git a/en/application-dev/notification/assistant-guidelines.md b/en/application-dev/notification/assistant-guidelines.md
deleted file mode 100644
index 5d83cf443c0f629fcb471a6c12ccd3069ac2e593..0000000000000000000000000000000000000000
--- a/en/application-dev/notification/assistant-guidelines.md
+++ /dev/null
@@ -1,134 +0,0 @@
-# Debugging Assistant Usage
-
-The common event and notification module provides debugging tools to facilitate your application development. With these tools, you can view common event and notification information, publish common events, and more. These tools have been integrated with the system. You can run related commands directly in the shell.
-
-## cem Debugging Assistant
-
-### publish
-
-* Function
-
- Publishes a common event.
-
-* Usage
-
- `cem publish []`
-
- The table below describes the available options.
-
- | Option | Description |
- | ------------ | ------------------------------------------ |
- | -e/--event | Indicates the name of the common event to publish. Mandatory. |
- | -s/--sticky | Indicates that the common event to publish is sticky. Optional. By default, non-sticky events are published. |
- | -o/--ordered | Indicates that the common event to publish is ordered. Optional. By default, non-ordered events are published. |
- | -c/--code | Indicates the result code of the common event. Optional. |
- | -d/--data | Indicates the data carried in the common event. Optional. |
- | -h/--help | Indicates the help Information |
-
-* Example
-
- `cem publish --event "testevent"`
-
- Publish a common event named **testevent**.
-
- ![cem-publish-event](figures/cem-publish-event.png)
-
-
-
- `cem publish -e "testevent" -s -o -c 100 -d "this is data" `
-
- Publish a sticky, ordered common event named **testevent**. The result code of the event is **100** and the data carried is **this is data**.
-
- ![cem-publish-all](figures/cem-publish-all.png)
-
-### dump
-
-* Function
-
- Displays information about common events.
-
-* Usage
-
- `cem dump []`
-
- The table below describes the available options.
-
- | Option | Description |
- | ---------- | -------------------------------------------- |
- | -a/--all | Displays information about all common events that have been sent since system startup. |
- | -e/--event | Displays information about a specific event. |
- | -h/--help | Displays the help information. |
-
-* Example
-
- `cem dump -e "testevent"`
-
- Display information about the common event testevent.
-
- ![cem-dump-e](figures/cem-dump-e.png)
-
-### help
-
-* Function
-
- Displays the help information.
-
-* Usage
-
- `cem help`
-
-* Example
-
- ![cem-help](figures/cem-help.png)
-
-
-
-## anm Debugging Assistant
-
-### dump
-
-* Function
-
- Displays information about notifications.
-
-* Usage
-
- `anm dump []`
-
- The table below describes the available options.
-
- | Option | Description |
- | ---------------- | ---------------------------------------- |
- | -A/--active | Displays information about all active notifications. |
- | -R/--recent | Displays information about the recent notifications. |
- | -D/--distributed | Displays information about distributed notifications from other devices. |
- | --setRecentCount | Indicates the number of the cached recent notifications to be displayed. Optional. |
- | -h/--help | Displays the help information. |
-
-* Example
-
- `anm dump -A`
-
- Display information about all active notifications.
-
- ![anm-dump-A](figures/anm-dump-A.png)
-
-
-
- `anm dump --setRecentCount 10`
-
- Set the number of the cached recent notifications to be displayed to **10**.
-
-### help
-
-* Function
-
- Displays the help information.
-
-* Usage
-
- `anm help`
-
-* Example
-
- ![anm-help](figures/anm-help.png)
diff --git a/en/application-dev/notification/common-event.md b/en/application-dev/notification/common-event.md
deleted file mode 100644
index dfb611ea572b80486756faaa4b004513cd6858a7..0000000000000000000000000000000000000000
--- a/en/application-dev/notification/common-event.md
+++ /dev/null
@@ -1,172 +0,0 @@
-# Common Event Development
-## Introduction
-OpenHarmony provides a Common Event Service (CES) for applications to subscribe to, publish, and unsubscribe from common events.
-
-Common events are classified into system common events and custom common events.
-
-+ System common events: The system sends an event based on system policies to the apps that have subscribed to this event when it occurs. This type of event is typically system events published by key system services, such as HAP installation, update, and uninstallation.
-
-+ Custom common event: customized by applications to implement cross-application event communication.
-
-Each application can subscribe to common events as required. After your application subscribes to a common event, the system sends it to your application every time the event is published. Such an event may be published by the system, other applications, or your own application.
-
-## Common Event Subscription Development
-
-### When to Use
-You can create a subscriber object to subscribe to a common event to obtain the parameters passed in the event. Certain system common events require specific permissions to subscribe to. For details, see [Required Permissions](../reference/apis/js-apis-commonEvent.md#support).
-
-### Available APIs
-| API | Description|
-| ---------------------------------------------------------------------------------------------- | ----------- |
-| createSubscriber(subscribeInfo: CommonEventSubscribeInfo, callback: AsyncCallback) | Creates a subscriber. This API uses a callback to return the result.|
-| createSubscriber(subscribeInfo: CommonEventSubscribeInfo) | Creates a subscriber. This API uses a promise to return the result. |
-| subscribe(subscriber: CommonEventSubscriber, callback: AsyncCallback) | Subscribes to common events.|
-
-### How to Develop
-1. Import the **commonEvent** module.
-
-```js
-import commonEvent from '@ohos.commonEvent';
-```
-
-2. Create a **subscribeInfo** object. For details about the data types and parameters of the object, see [CommonEventSubscribeInfo](../reference/apis/js-apis-commonEvent.md#commoneventsubscribeinfo).
-
-```js
-// Used to save the created subscriber object for subsequent subscription and unsubscription.
-private subscriber = null
-
-// Subscriber information
-var subscribeInfo = {
- events: ["event"],
-}
-```
-
-3. Create a subscriber object and save the returned object for subsequent operations such as subscription and unsubscription.
-
-```js
-// Callback for subscriber creation.
-commonEvent.createSubscriber(subscribeInfo, (err, subscriber) => {
- if (err.code) {
- console.error("[CommonEvent]CreateSubscriberCallBack err=" + JSON.stringify(err))
- } else {
- console.log("[CommonEvent]CreateSubscriber")
- this.subscriber = subscriber
- this.result = "Create subscriber succeed"
- }
-})
-```
-
-4. Create a subscription callback, which is triggered when an event is received. The data returned by the subscription callback contains information such as the common event name and data carried by the publisher. For details about the data types and parameters of the common event data, see [CommonEventData](../reference/apis/js-apis-commonEvent.md#commoneventdata).
-
-```js
-// Callback for common event subscription.
-if (this.subscriber != null) {
- commonEvent.subscribe(this.subscriber, (err, data) => {
- if (err.code) {
- console.error("[CommonEvent]SubscribeCallBack err=" + JSON.stringify(err))
- } else {
- console.log("[CommonEvent]SubscribeCallBack data=" + JSON.stringify(data))
- this.result = "receive, event = " + data.event + ", data = " + data.data + ", code = " + data.code
- }
- })
- this.result = "Subscribe succeed"
-} else {
- prompt.showToast({ message: "Need create subscriber" })
-}
-```
-
-## Common Event Publishing Development
-
-### When to Use
-You can use the **publish** APIs to publish a custom common event, which can carry data for subscribers to parse and process.
-
-### Available APIs
-| API | Description|
-| ---------------------------------- | ------ |
-| publish(event: string, callback: AsyncCallback) | Publishes a common event.|
-| publish(event: string, options: CommonEventPublishData, callback: AsyncCallback) | Publishes a common event with given attributes.|
-
-### How to Develop
-#### Development for Publishing a Common Event
-1. Import the **commonEvent** module.
-
-```js
-import commonEvent from '@ohos.commonEvent';
-```
-
-2. Pass in the common event name and callback, and publish the event.
-
-```js
-// Publish a common event.
-commonEvent.publish("event", (err) => {
- if (err.code) {
- console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
- } else {
- console.info("[CommonEvent]Publish1")
- }
-})
-```
-
-#### Development for Publishing a Common Event with Given Attributes
-1. Import the **commonEvent** module.
-
-```js
-import commonEvent from '@ohos.commonEvent'
-```
-
-2. Define attributes of the common event to publish. For details about the data types and parameters in the data to publish, see [CommonEventPublishData](../reference/apis/js-apis-commonEvent.md#commoneventpublishdata).
-
-```js
-// Attributes of a common event.
-var options = {
- code: 1, // Result code of the common event
- data: "initial data";// Result data of the common event
-}
-```
-
-3. Pass in the common event name, attributes of the common event, and callback, and publish the event.
-
-```js
-// Publish a common event.
-commonEvent.publish("event", options, (err) => {
- if (err.code) {
- console.error("[CommonEvent]PublishCallBack err=" + JSON.stringify(err))
- } else {
- console.info("[CommonEvent]Publish2")
- }
-})
-```
-
-## Common Event Unsubscription Development
-
-### When to Use
-You can use the **unsubscribe** API to unsubscribe from a common event.
-
-### Available APIs
-| API | Description|
-| ---------------------------------- | ------ |
-| unsubscribe(subscriber: CommonEventSubscriber, callback?: AsyncCallback) | Unsubscribes from a common event.|
-
-### How to Develop
-1. Import the **commonEvent** module.
-
-```js
-import commonEvent from '@ohos.commonEvent';
-```
-
-2. Subscribe to a common event by following instructions in [Common Event Subscription Development](#common-event-subscription-development).
-3. Invoke the **unsubscribe** API in **CommonEvent** to unsubscribe from the common event.
-
-```js
-if (this.subscriber != null) {
- commonEvent.unsubscribe(this.subscriber, (err) => {
- if (err.code) {
- console.error("[CommonEvent]UnsubscribeCallBack err=" + JSON.stringify(err))
- } else {
- console.log("[CommonEvent]Unsubscribe")
- this.subscriber = null
- this.result = "Unsubscribe succeed"
- }
- })
-}
-```
diff --git a/en/application-dev/notification/figures/anm-dump-A.png b/en/application-dev/notification/figures/anm-dump-A.png
deleted file mode 100644
index 368e6f2d810976486e786a4c8f0603a87ad48540..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/anm-dump-A.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/anm-help.png b/en/application-dev/notification/figures/anm-help.png
deleted file mode 100644
index d80ac8e76a70c2be383f0a05a12e3e707dcf242b..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/anm-help.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/ans.png b/en/application-dev/notification/figures/ans.png
deleted file mode 100644
index 8be552d2acedbef962326365fb2d19ded3838c14..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/ans.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/cem-dump-e.png b/en/application-dev/notification/figures/cem-dump-e.png
deleted file mode 100644
index c2422ba0e51011174c333985ad7647f170e0f126..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/cem-dump-e.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/cem-help.png b/en/application-dev/notification/figures/cem-help.png
deleted file mode 100644
index 8ca4bc0605f9c1f75a8cb45f8ab77c9c5d6f04e4..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/cem-help.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/cem-publish-all.png b/en/application-dev/notification/figures/cem-publish-all.png
deleted file mode 100644
index 99526e1f7245d101914354e2a89d5e97d710c27f..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/cem-publish-all.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/cem-publish-event.png b/en/application-dev/notification/figures/cem-publish-event.png
deleted file mode 100644
index f0ca7e73093f1be72c743bd7c08467f11e2a0e05..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/cem-publish-event.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/ces.png b/en/application-dev/notification/figures/ces.png
deleted file mode 100644
index b1aa5438a19ac79899e0f45791f3e1a79e4242dc..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/ces.png and /dev/null differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001416585590.png b/en/application-dev/notification/figures/en-us_image_0000001416585590.png
new file mode 100644
index 0000000000000000000000000000000000000000..9da6812580fd6c7d785391c652104ef0698ce2bc
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416585590.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001416745530.png b/en/application-dev/notification/figures/en-us_image_0000001416745530.png
new file mode 100644
index 0000000000000000000000000000000000000000..7a6fd0d9304abef2eb240a3c78a93b73bb9237af
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001416745530.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062434.png b/en/application-dev/notification/figures/en-us_image_0000001417062434.png
new file mode 100644
index 0000000000000000000000000000000000000000..07db3298f0db1c3357624b44d271dc1e6f97ea9e
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062434.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001417062446.png b/en/application-dev/notification/figures/en-us_image_0000001417062446.png
new file mode 100644
index 0000000000000000000000000000000000000000..c197fd6293f41890b2bfcf17a28a1477e8aa6d96
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001417062446.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462297.png b/en/application-dev/notification/figures/en-us_image_0000001466462297.png
new file mode 100644
index 0000000000000000000000000000000000000000..a07d9e818677e9364ad3239e61ce198471b68603
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462297.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001466462305.png b/en/application-dev/notification/figures/en-us_image_0000001466462305.png
new file mode 100644
index 0000000000000000000000000000000000000000..740f4b79a9ee234008cad6cf3616a8f213569476
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466462305.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582017.png b/en/application-dev/notification/figures/en-us_image_0000001466582017.png
new file mode 100644
index 0000000000000000000000000000000000000000..1652d9111be2a27863fe2322c4feb577bab22ae9
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582017.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001466582045.png b/en/application-dev/notification/figures/en-us_image_0000001466582045.png
new file mode 100644
index 0000000000000000000000000000000000000000..4040452a87bc69ae8fa0eb9b55ca77ac32bdb2d8
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466582045.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782025.png b/en/application-dev/notification/figures/en-us_image_0000001466782025.png
new file mode 100644
index 0000000000000000000000000000000000000000..d8e45c1746ab419a8056f9493c8796cfb734d2d0
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782025.png differ
diff --git a/en/application-dev/notification/figures/en-us_image_0000001466782033.png b/en/application-dev/notification/figures/en-us_image_0000001466782033.png
new file mode 100644
index 0000000000000000000000000000000000000000..218e5fcef6d163113c9037028215297ef626fcfa
Binary files /dev/null and b/en/application-dev/notification/figures/en-us_image_0000001466782033.png differ
diff --git a/en/application-dev/notification/figures/notification-with-wantagent.png b/en/application-dev/notification/figures/notification-with-wantagent.png
new file mode 100644
index 0000000000000000000000000000000000000000..234ef895c918404598cf7640f9d072de2bb2d0d0
Binary files /dev/null and b/en/application-dev/notification/figures/notification-with-wantagent.png differ
diff --git a/en/application-dev/notification/figures/notification.png b/en/application-dev/notification/figures/notification.png
deleted file mode 100644
index 18dcb99b0c531a19698f749105d88db91043837a..0000000000000000000000000000000000000000
Binary files a/en/application-dev/notification/figures/notification.png and /dev/null differ
diff --git a/en/application-dev/notification/notification-brief.md b/en/application-dev/notification/notification-brief.md
deleted file mode 100644
index 75237412fdf29d88843a9f23fa653f64f2de7c86..0000000000000000000000000000000000000000
--- a/en/application-dev/notification/notification-brief.md
+++ /dev/null
@@ -1,20 +0,0 @@
-# Common Event and Notification Overview
-
-The common event and notification module enables applications to publish messages to other applications, and receive messages from the system or other applications. These messages can be news push messages, advertisement notifications, warning information, and more.
-
-Common Event Service (CES) enables applications to publish, subscribe to, and unsubscribe from common events. Based on the sender type, common events are classified into system common events and custom common events.
-
-![ces](figures/ces.png)
-
-- System common event: sent by the system based on system policies to the applications that have subscribed to the event. This type of event includes the screen-on/off events that the users are aware of and the system events published by key system services, such as USB device attachment or detachment, network connection, and system update events.
-- Custom common event: customized by applications to be received by specific subscribers. This type of event is usually related to the service logic of the sender applications.
-
-The Advanced Notification Service (ANS) enables applications to publish notifications. Below are some typical use cases for publishing notifications:
-
-- Display received SMS messages and instant messages.
-- Display push messages of applications, such as advertisements, version updates, and news notifications.
-- Display ongoing events, such as music playback, navigation information, and download progress.
-
-Notifications are displayed in the notification panel. Uses can delete a notification or click the notification to trigger predefined actions.
-
-![ans](figures/ans.png)
diff --git a/en/application-dev/notification/notification-enable.md b/en/application-dev/notification/notification-enable.md
new file mode 100644
index 0000000000000000000000000000000000000000..12aa4f41eb1570d707b4c65310cefe6aa45e1b17
--- /dev/null
+++ b/en/application-dev/notification/notification-enable.md
@@ -0,0 +1,49 @@
+# Enabling Notification
+
+
+To publish a notification, you must have notification enabled for your application. You can call the [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) API to display a dialog box prompting the user to enable notification for your application. Note that the dialog box is displayed only when the API is called for the first time.
+
+ **Figure 1** Dialog box prompting the user to enable notification
+
+![en-us_image_0000001416585590](figures/en-us_image_0000001416585590.png)
+
+
+- Touching **allow** enables notification for the application, and touching **ban** keeps notification disabled.
+
+- The dialog box will not be displayed again when [requestEnableNotification()](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification) is called later. The user can manually enable notification as follows.
+
+ | 1. Swipe down from the upper left corner of the device screen to access the notification panel. | 2. Touch the **Settings** icon in the upper right corner. On the notification screen, locate the target application.| 3. Toggle on **Allow notifications**. |
+ | ------------------------------------------------------------ | ------------------------------------------------------------ | ------------------------------------------------------------ |
+ | ![en-us_image_0000001417062434](figures/en-us_image_0000001417062434.png) | ![en-us_image_0000001466462297](figures/en-us_image_0000001466462297.png) | ![en-us_image_0000001466782025](figures/en-us_image_0000001466782025.png) |
+
+
+## Available APIs
+
+For details about the APIs, see [@ohos.notificationManager](../reference/apis/js-apis-notificationManager.md#notificationrequestenablenotification).
+
+**Table 1** Notification APIs
+
+| Name | Description |
+| -------- | -------- |
+| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback<boolean>): void | Checks whether notification is enabled.
**NOTE**
This is a system API and cannot be called by third-party applications. |
+| setNotificationEnable(bundle: BundleOption, enable: boolean, callback: AsyncCallback<void>): void | Sets whether to enable notification. Notification can be enabled or disabled in **Notifications** of the target application under **Settings** > **Apps & services** > **Apps**.
**NOTE**
This is a system API and cannot be called by third-party applications.|
+| requestEnableNotification(callback: AsyncCallback<void>): void | Requests notification to be enabled. When called for the first time, this API displays a dialog box prompting the user to enable notification. |
+
+
+## How to Develop
+
+1. Import the **NotificationManager** module.
+
+ ```ts
+ import notificationManager from '@ohos.notificationManager';
+ ```
+
+2. Call the API to request notification to be enabled.
+
+ ```ts
+ notificationManager.requestEnableNotification().then(() => {
+ console.info(`[ANS] requestEnableNotification success`);
+ }).catch((err) => {
+ console.error(`[ANS] requestEnableNotification failed, errCode[${err}]`);
+ });
+ ```
diff --git a/en/application-dev/notification/notification-guidelines.md b/en/application-dev/notification/notification-guidelines.md
deleted file mode 100644
index fb73f274202aafd9ff852201ca2fb8c5116aba50..0000000000000000000000000000000000000000
--- a/en/application-dev/notification/notification-guidelines.md
+++ /dev/null
@@ -1,258 +0,0 @@
-
-
-# Notification Development
-
-## When to Use
-
-OpenHarmony uses the Advanced Notification Service (ANS) to manage notifications, with support for various notification types, including text, long text, multi-text, image, social, and media. All system services and applications can send notifications through the notification API. Users can view all notifications on the system UI.
-
-Below are some typical use cases for notifications:
-
-- Display received SMS messages and instant messages.
-- Display push messages of applications, such as advertisements and version updates.
-- Display ongoing events, such as navigation information and download progress.
-
-
-
-## Notification Service Process
-
-The notification service process involves the ANS subsystem, notification sender, and notification subscriber.
-
-A notification is generated by the notification sender and sent to the ANS through inter-process communication (IPC). The ANS then distributes the notification to the notification subscriber.
-
-System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the ANS for storage in the memory and database.
-
-![1648113187545](figures/notification.png)
-
-
-
-## Available APIs
-
-Certain APIs can be called only by system applications that have been granted the **SystemCapability.Notification.Notification** permission. The APIs use either a callback or promise to return the result. The tables below list the APIs that use a callback, which provide the same functions as their counterparts that use a promise. For details about the APIs, see the [API document](../reference/apis/js-apis-notification.md).
-
-**Table 1** APIs for notification enabling
-
-| API | Description |
-| ------------------------------------------------------------ | ---------------- |
-| isNotificationEnabled(bundle: BundleOption, callback: AsyncCallback\): void | Checks whether notification is enabled.|
-| enableNotification(bundle: BundleOption, enable: boolean, callback: AsyncCallback\): void | Sets whether to enable notification. |
-
-If the notification function of an application is disabled, it cannot send notifications.
-
-
-
-**Table 2** APIs for notification subscription
-
-| API | Description |
-| ------------------------------------------------------------ | ---------------- |
-| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback\): void | Subscribes to a notification with the subscription information specified.|
-| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Subscribes to all notifications. |
-| unsubscribe(subscriber: NotificationSubscriber, callback: AsyncCallback\): void | Unsubscribes from a notification. |
-
-The subscription APIs support subscription to all notifications and notifications from specific applications.
-
-
-
-**Table 3** Notification subscription callbacks
-
-| API | Description |
-| ------------------------------------------------ | ---------------- |
-| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. |
-| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. |
-| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates.|
-| onConnect?:() => void; | Callback for subscription. |
-| onDisconnect?:() => void; | Callback for unsubscription. |
-
-
-
-**Table 4** APIs for notification sending
-
-| API | Description |
-| ------------------------------------------------------------ | ------------------------ |
-| publish(request: NotificationRequest, callback: AsyncCallback\): void | Publishes a notification. |
-| publish(request: NotificationRequest, userId: number, callback: AsyncCallback\): void | Publishes a notification to the specified user. |
-| cancel(id: number, label: string, callback: AsyncCallback\): void | Cancels a specified notification. |
-| cancelAll(callback: AsyncCallback\): void; | Cancels all notifications published by the application.|
-
-The **publish** API that carries **userId** can be used to publish notifications to subscribers of a specified user.
-
-
-
-## Development Guidelines
-
-The notification development process generally involves three aspects: subscribing to notifications, enabling the notification feature, and publishing notifications.
-
-### Modules to Import
-
-```js
-import Notification from '@ohos.notification';
-```
-
-
-
-### Subscribing to Notifications
-
-The notification recipient preferentially initiates a notification subscription request to the notification subsystem.
-
-```js
-var subscriber = {
- onConsume: function (data) {
- let req = data.request;
- console.info('===>onConsume callback req.id: ' + req.id);
- },
- onCancel: function (data) {
- let req = data.request;
- console.info('===>onCancel callback req.id: : ' + req.id);
- },
- onUpdate: function (data) {
- console.info('===>onUpdate in test===>');
- },
- onConnect: function () {
- console.info('===>onConnect in test===>');
- },
- onDisconnect: function () {
- console.info('===>onDisConnect in test===>');
- },
- onDestroy: function () {
- console.info('===>onDestroy in test===>');
- },
- };
-
- Notification.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
- if (err.code) {
- console.error('===>failed to subscribe because ' + JSON.stringify(err));
- return;
- }
- console.info('===>subscribeTest success : ' + JSON.stringify(data));
- });
-```
-
-
-
-### Publishing Notifications
-
-##### Enabling Notification
-
-Before publishing a notification, check whether the notification feature is enabled for your application. By default, the feature is disabled. The application calls **Notification.requestEnableNotification** to prompt the user to enable the feature.
-
-```js
-Notification.requestEnableNotification().then((data) => {
- console.info('===>requestEnableNotification success');
-}).catch((err) => {
- console.error('===>requestEnableNotification failed because ' + JSON.stringify(err));
-});
-```
-
-
-
-##### Publishing Notifications
-
-To publish a notification, create a **NotificationRequest** object and set attributes such as the notification type, title, and content. In the following examples, a normal text notification and a notification containing a **WantAgent** are being published.
-
-Normal text notification:
-
-```js
-// Create a NotificationRequest object.
-var notificationRequest = {
- id: 1,
- content: {
- contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
- normal: {
- title: "test_title",
- text: "test_text",
- additionalText: "test_additionalText"
- }
- }
-}
-
-// Publish the notification.
-Notification.publish(notificationRequest).then((data) => {
- console.info('===>publish promise success req.id : ' + notificationRequest.id);
-}).catch((err) => {
- console.error('===>publish promise failed because ' + JSON.stringify(err));
-});
-```
-
-
-
-Notification containing **WantAgent**:
-
-For details about how to use **WantAgent**, see [WantAgent Development](https://gitee.com/openharmony/docs/blob/master/en/application-dev/ability/wantagent.md).
-
-- Create a **WantAgent** object.
-
-```js
-import wantAgent from '@ohos.wantAgent';
-
-// WantAgentInfo object
-var wantAgentInfo = {
- wants: [
- {
- bundleName: 'ohos.samples.eTSNotification',
- abilityName: 'ohos.samples.eTSNotification.MainAbility',
- }
- ],
- operationType: wantAgent.OperationType.START_ABILITY,
- requestCode: 0,
- wantAgentFlags:[wantAgent.WantAgentFlags.UPDATE_PRESENT_FLAG]
-}
-
-// WantAgent object
-var WantAgent;
-
-// getWantAgent callback
-function getWantAgentCallback(err, data) {
- console.info("===>getWantAgentCallback===>");
- if (err.code == 0) {
- WantAgent = data;
- } else {
- console.info('----getWantAgent failed!----');
- }
-}
-
-// Obtain the WantAgent object.
-wantAgent.getWantAgent(wantAgentInfo, getWantAgentCallback)
-```
-
-- Publish the notification.
-
-```js
-// Create a NotificationRequest object.
-var notificationRequest = {
- content: {
- contentType: Notification.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
- normal: {
- title: "AceApplication_Title",
- text: "AceApplication_Text",
- additionalText: "AceApplication_AdditionalText"
- },
- },
- id: 1,
- label: 'TEST',
- wantAgent: WantAgent,
- slotType: Notification.SlotType.OTHER_TYPES,
- deliveryTime: new Date().getTime()
-}
-
-// Publish the notification.
-Notification.publish(notificationRequest).then((data) => {
- console.info('===>publish promise success req.id : ' + notificationRequest.id);
-}).catch((err) => {
- console.error('===>publish promise failed because ' + JSON.stringify(err));
-});
-```
-
-
-
-- Cancel the notification.
-
-An application can cancel a single notification or all notifications. An application can cancel only the notifications published by itself.
-
-```js
-// cancel callback
-function cancelCallback(err) {
- console.info("===>cancelCallback===>");
-}
-
-Notification.cancel(1, "label", cancelCallback)
-```
diff --git a/en/application-dev/notification/notification-overview.md b/en/application-dev/notification/notification-overview.md
new file mode 100644
index 0000000000000000000000000000000000000000..6bef8be8fd446e62b3e3da04582b467c9ddc5961
--- /dev/null
+++ b/en/application-dev/notification/notification-overview.md
@@ -0,0 +1,27 @@
+# Notification Overview
+
+
+## Introduction
+
+All system applications and services can publish notifications through the notification APIs. Users can view the notifications in the notification panel or click a notification to open the publishing application.
+
+Below are some typical use cases for notifications:
+
+- Display received SMS messages and instant messages.
+
+- Display push messages, such as advertisements and version updates.
+
+- Display ongoing events, such as the download progress.
+
+The Advanced Notification Service (ANS) in OpenHarmony is used to manage notifications of various types, such as basic notifications, progress notifications, and reminders published through the background agent.
+
+
+## Notification Service Process
+
+The notification service process involves the notification subsystem, notification sender, and notification subscriber.
+
+A notification is generated by the notification sender and sent to the notification subsystem through [inter-process communication (IPC)](../connectivity/ipc-rpc-overview.md). The notification subsystem then distributes the notification to the notification subscriber.
+
+System applications also support notification-related configuration options, such as switches. The system configuration initiates a configuration request and sends the request to the notification subsystem for storage in the memory and database.
+
+![en-us_image_0000001466582017](figures/en-us_image_0000001466582017.png)
diff --git a/en/application-dev/notification/notification-subscription.md b/en/application-dev/notification/notification-subscription.md
new file mode 100644
index 0000000000000000000000000000000000000000..a633a2bb955bcf877fbe4befb8b40ad103d7e7e6
--- /dev/null
+++ b/en/application-dev/notification/notification-subscription.md
@@ -0,0 +1,82 @@
+# Notification Subscription (Open Only to System Applications)
+
+
+To receive notifications, an application must subscribe to notifications first. The notification subsystem provides two types of subscription APIs, allowing applications to subscribe to notifications from all applications or notifications from a specific application.
+
+
+You can use the **NotificationSubscriber** object to provide callbacks for subscription events, such as subscription success, notification reception, notification cancellation, and subscription cancellation.
+
+
+## Available APIs
+
+The major APIs for notification subscription are described as follows. For details about the APIs, see [@ohos.notificationSubscribe](../reference/apis/js-apis-notificationSubscribe.md).
+
+**Table 1** Major APIs for notification subscription
+
+| Name | Description|
+| -------- | -------- |
+| subscribe(subscriber: NotificationSubscriber, info: NotificationSubscribeInfo, callback: AsyncCallback<void>): void | Subscribes to notifications from a specific application.|
+| subscribe(subscriber: NotificationSubscriber, callback: AsyncCallback<void>): void | Subscribes to notifications from all applications. |
+
+**Table 2** Callbacks for notification subscription
+
+| Name | Description|
+| -------- | -------- |
+| onConsume?:(data: SubscribeCallbackData) => void | Callback for receiving notifications. |
+| onCancel?:(data: SubscribeCallbackData) => void | Callback for canceling notifications. |
+| onUpdate?:(data: NotificationSortingMap) => void | Callback for notification sorting updates. |
+| onConnect?:() => void; | Callback for subscription. |
+| onDisconnect?:() => void; | Callback for unsubscription. |
+| onDestroy?:() => void | Callback for disconnecting from the notification subsystem. |
+| onDoNotDisturbDateChange?:(mode: notification.DoNotDisturbDate) => void | Callback for the Do Not Disturb (DNT) time changes.|
+| onEnabledNotificationChanged?:(callbackData: EnabledNotificationCallbackData) => void | Callback for notification switch changes. |
+
+
+## How to Develop
+
+1. Request the **ohos.permission.NOTIFICATION_CONTROLLER** permission. For details, see [Permission Application Guide](../security/accesstoken-guidelines.md#declaring-permissions-in-the-configuration-file).
+
+2. Import the **notificationSubscribe** module.
+
+ ```ts
+ import notificationSubscribe from '@ohos.notificationSubscribe';
+ ```
+
+3. Create a **subscriber** object.
+
+ ```ts
+ let subscriber = {
+ onConsume: function (data) {
+ let req = data.request;
+ console.info('[ANS] onConsume callback req.id: ' + req.id);
+ },
+ onCancel: function (data) {
+ let req = data.request;
+ console.info('[ANS] onCancel callback req.id: : ' + req.id);
+ },
+ onUpdate: function (data) {
+ console.info('[ANS] onUpdate in test');
+ },
+ onConnect: function () {
+ console.info('[ANS] onConnect in test');
+ },
+ onDisconnect: function () {
+ console.info('[ANS] onDisConnect in test');
+ },
+ onDestroy: function () {
+ console.info('[ANS] onDestroy in test');
+ },
+ };
+ ```
+
+4. Initiate notification subscription.
+
+ ```ts
+ notificationSubscribe.subscribe(subscriber, (err, data) => { // This API uses an asynchronous callback to return the result.
+ if (err) {
+ console.error(`[ANS] failed to subscribe, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] subscribeTest success : + ${data}`);
+ });
+ ```
diff --git a/en/application-dev/notification/notification-with-wantagent.md b/en/application-dev/notification/notification-with-wantagent.md
new file mode 100644
index 0000000000000000000000000000000000000000..d8f0321d28738749d6ed6073e49f26181c22e706
--- /dev/null
+++ b/en/application-dev/notification/notification-with-wantagent.md
@@ -0,0 +1,121 @@
+# Adding a WantAgent Object to a Notification
+
+A [WantAgent](../reference/apis/js-apis-app-ability-wantAgent.md) object encapsulates an intention to start a specified ability, release a common event, and more. In OpenHarmony, a **WantAgent** object can be passed in a notification from the publisher to the subscriber, so as to trigger the intention specified. For example, you may want the user to start a specific ability by touching the notification published by your application. In this case, you can add a **WantAgent** object that encapsulates such an action to the notification. After receiving the **WantAgent** object, the system triggers it once the user touches the notification from the notification panel, starting the specified ability.
+
+Below you can see the process of adding a **WantAgent** object to a notification. The notification publisher requests a **WantAgent** object from the Ability Manager Service (AMS), and then sends a notification carrying the **WantAgent** object to the home screen. When the user touches the notification from the notification panel on the home screen, the **WantAgent** object is triggered.
+
+ **Figure 1** Publishing a notification with a WantAgent object
+![notification-with-wantagent](figures/notification-with-wantagent.png)
+
+
+## Available APIs
+
+For details about the APIs, see [@ohos.app.ability.wantAgent](../reference/apis/js-apis-app-ability-wantAgent.md).
+
+| Name| Description|
+| -------- | -------- |
+| getWantAgent(info: WantAgentInfo, callback: AsyncCallback<WantAgent>): void | Creates a **WantAgent** object.|
+| trigger(agent: WantAgent, triggerInfo: TriggerInfo, callback?: Callback<CompleteData>): void | Triggers a **WantAgent** object.|
+| cancel(agent: WantAgent, callback: AsyncCallback<void>): void | Cancels a **WantAgent** object.|
+| getWant(agent: WantAgent, callback: AsyncCallback<Want>): void | Obtains a **WantAgent** object.|
+| equal(agent: WantAgent, otherAgent: WantAgent, callback: AsyncCallback<boolean>): void | Checks whether two **WantAgent** objects are equal. |
+
+
+## How to Develop
+
+1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user.
+
+2. Import the modules.
+
+ ```typescript
+ import notificationManager from '@ohos.notificationManager';
+ import wantAgent from '@ohos.app.ability.wantAgent';
+ ```
+
+3. Create a **WantAgentInfo** object.
+
+ Scenario 1: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for starting a UIAbility component.
+
+ ```typescript
+ let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations.
+
+ // Set the action type through operationType of WantAgentInfo.
+ let wantAgentInfo = {
+ wants: [
+ {
+ deviceId: '',
+ bundleName: 'com.example.myapplication',
+ abilityName: 'EntryAbility',
+ action: '',
+ entities: [],
+ uri: '',
+ parameters: {}
+ }
+ ],
+ operationType: wantAgent.OperationType.START_ABILITY,
+ requestCode: 0,
+ wantAgentFlags:[wantAgent.WantAgentFlags.CONSTANT_FLAG]
+ };
+ ```
+
+ Scenario 2: Create a [WantAgentInfo](../reference/apis/js-apis-inner-wantAgent-wantAgentInfo.md) object for publishing a [common event](../application-models/common-event-overview.md).
+
+ ```typescript
+ let wantAgentObj = null; // Save the WantAgent object created. It will be used to complete the trigger operations.
+
+ // Set the action type through operationType of WantAgentInfo.
+ let wantAgentInfo = {
+ wants: [
+ {
+ action: 'event_name', // Set the action name.
+ parameters: {},
+ }
+ ],
+ operationType: wantAgent.OperationType.SEND_COMMON_EVENT,
+ requestCode: 0,
+ wantAgentFlags: [wantAgent.WantAgentFlags.CONSTANT_FLAG],
+ }
+ ```
+
+4. Invoke the [getWantAgent()](../reference/apis/js-apis-app-ability-wantAgent.md#wantagentgetwantagent) API to create a **WantAgent** object.
+
+ ```typescript
+ // Create a WantAgent object.
+ wantAgent.getWantAgent(wantAgentInfo, (err, data) => {
+ if (err) {
+ console.error('[WantAgent]getWantAgent err=' + JSON.stringify(err));
+ return;
+ }
+ console.info('[WantAgent]getWantAgent success');
+ wantAgentObj = data;
+ });
+ ```
+
+5. Create a **NotificationRequest** object and publish a notification that carries the **WantAgent** object.
+
+ ```typescript
+ // Create a NotificationRequest object.
+ let notificationRequest = {
+ content: {
+ contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
+ normal: {
+ title: 'Test_Title',
+ text: 'Test_Text',
+ additionalText: 'Test_AdditionalText',
+ },
+ },
+ id: 1,
+ label: 'TEST',
+ wantAgent: wantAgentObj,
+ }
+
+ notificationManager.publish(notificationRequest, (err) => {
+ if (err) {
+ console.error(`[ANS] failed to publish, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] publish success`);
+ });
+ ```
+
+6. When the user touches the notification from the notification panel, the system automatically triggers the action specified in the **WantAgent** object.
diff --git a/en/application-dev/notification/progress-bar-notification.md b/en/application-dev/notification/progress-bar-notification.md
new file mode 100644
index 0000000000000000000000000000000000000000..de430008e3048532e9afea94d83a62dd2f8342c1
--- /dev/null
+++ b/en/application-dev/notification/progress-bar-notification.md
@@ -0,0 +1,69 @@
+# Publishing a Progress Notification
+
+
+The progress notification is a commonly used notification type, mainly used to display the progress of an ongoing operation, such as file downloading. When publishing a progress notification through the notification subsystem, you can use the readily available template by specifying the related attributes, such as the template name and template data.
+
+In the [NotificationTemplate](../reference/apis/js-apis-notificationManager.md#notificationtemplate), which can only be of the progress type, **data** indicates custom template data.
+
+
+## Available APIs
+
+| Name| Description|
+| -------- | -------- |
+| isSupportTemplate(templateName: string, callback: AsyncCallback<boolean>): void | Checks whether a specific template is supported. This API uses an asynchronous callback to return the result.
Only the progress-type template is supported.|
+
+
+## How to Develop
+
+1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user.
+
+2. Import the module.
+
+ ```ts
+ import notificationManager from '@ohos.notificationManager';
+ ```
+
+3. Check whether a specific template is supported. In this example, the template of the **downloadTemplate** type is checked.
+
+ ```ts
+ notificationManager.isSupportTemplate('downloadTemplate').then((data) => {
+ console.info(`[ANS] isSupportTemplate success`);
+ let isSupportTpl: boolean = data; // The value **true** means that the template of the **downloadTemplate** type is supported; and false means the opposite.
+ // ...
+ }).catch((err) => {
+ console.error(`[ANS] isSupportTemplate failed, error[${err}]`);
+ });
+ ```
+
+ > **NOTE**
+ >
+ > Proceed with the step below only when the specified template is supported.
+4. Create a **NotificationRequest** object and publish a progress notification.
+
+ ```ts
+ let notificationRequest = {
+ id: 1,
+ content: {
+ contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT,
+ normal: {
+ title: 'test_title',
+ text: 'test_text',
+ additionalText: 'test_additionalText'
+ }
+ },
+ // Create a progress template. The name field has a fixed value of downloadTemplate.
+ template: {
+ name: 'downloadTemplate',
+ data: { title: 'File Title', fileName: 'music.mp4', progressValue: 45 }
+ }
+ }
+
+ // Publish the notification.
+ notificationManager.publish(notificationRequest, (err) => {
+ if (err) {
+ console.error(`[ANS] failed to publish, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] publish success `);
+ });
+ ```
diff --git a/en/application-dev/notification/text-notification.md b/en/application-dev/notification/text-notification.md
new file mode 100644
index 0000000000000000000000000000000000000000..ddbc5478cee37208da33d2acecb71417deaccdc2
--- /dev/null
+++ b/en/application-dev/notification/text-notification.md
@@ -0,0 +1,160 @@
+# Publishing a Basic Notification
+
+
+You can publish basic notifications to send SMS messages, prompt messages, and advertisements. Available content types of basic notifications include normal text, long text, multi-line text, and picture-attached.
+
+
+ **Table 1** Basic notification content types
+
+| Type| Description|
+| -------- | -------- |
+| NOTIFICATION_CONTENT_BASIC_TEXT | Normal text notification.|
+| NOTIFICATION_CONTENT_LONG_TEXT | Long text notification.|
+| NOTIFICATION_CONTENT_MULTILINE | Multi-line text notification.|
+| NOTIFICATION_CONTENT_PICTURE | Picture-attached notification.|
+
+
+Notifications are displayed in the notification panel, which is the only system subscriber to notifications. Below you can see two examples of the basic notification.
+
+**Figure 1** Examples of the basic notification
+![en-us_image_0000001466462305](figures/en-us_image_0000001466462305.png)
+
+
+## Available APIs
+
+The following table describes the APIs for notification publishing. You specify the notification type by setting the [NotificationRequest](../reference/apis/js-apis-notificationManager.md#notificationrequest) parameter in the APIs.
+
+| Name| Description|
+| -------- | -------- |
+| publish(request: NotificationRequest, callback: AsyncCallback<void>): void | Publishes a notification. |
+| cancel(id: number, label: string, callback: AsyncCallback<void>): void | Cancels a notification. |
+| cancelAll(callback: AsyncCallback<void>): void; | Cancels all notifications published by the application.|
+
+
+## How to Develop
+
+1. [Enable notification](notification-enable.md). An application can use the notification feature only after being authorized by the user.
+
+2. Import the module.
+
+ ```ts
+ import notificationManager from '@ohos.notificationManager';
+ ```
+
+3. Create a **NotificationRequest** object and publish a progress notification.
+ - A normal text notification consists of the **title**, **text**, and **additionalText** parameters, of which **title** and **text** are mandatory. The value of these parameters contains less than 200 bytes.
+
+ ```ts
+ let notificationRequest = {
+ id: 1,
+ content: {
+ contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_BASIC_TEXT, // Basic notification
+ normal: {
+ title: 'test_title',
+ text: 'test_text',
+ additionalText: 'test_additionalText',
+ }
+ }
+ }
+
+ notificationManager.publish(notificationRequest, (err) => {
+ if (err) {
+ console.error(`[ANS] failed to publish, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] publish success`);
+ });
+ ```
+
+ Below is an example of the normal text notification.
+ ![en-us_image_0000001466782033](figures/en-us_image_0000001466782033.png)
+ - In addition to the parameters in the normal text notification, the long text notification provides the **longText**, **briefText**, and **expandedTitle** parameters. The value of **longText** contains a maximum of 1024 bytes, while that of any other parameters contains less than 200 bytes. By default, a long-text notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **expandedTitle** and **longText**, respectively.
+
+ ```ts
+ let notificationRequest = {
+ id: 1,
+ content: {
+ contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_LONG_TEXT, // Long-text notification
+ longText: {
+ title: 'test_title',
+ text: 'test_text',
+ additionalText: 'test_additionalText',
+ longText: 'test_longText',
+ briefText: 'test_briefText',
+ expandedTitle: 'test_expandedTitle',
+ }
+ }
+ }
+
+ // Publish the notification.
+ notificationManager.publish(notificationRequest, (err) => {
+ if (err) {
+ console.error(`[ANS] failed to publish, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] publish success`);
+ });
+ ```
+
+ Below is an example of the long-text notification.
+ ![en-us_image_0000001416745530](figures/en-us_image_0000001416745530.png)
+ - In addition to the parameters in the normal text notification, the multi-line text notification provides the **lines**, **briefText**, and **longTitle** parameters. The value of these parameters contains less than 200 bytes. By default, a multi-line notification looks in the same way as a normal text notification. When expanded, the notification displays the title and content specified in **longTitle** and **lines**, respectively.
+
+ ```ts
+ let notificationRequest = {
+ id: 1,
+ content: {
+ contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_MULTILINE, // Multi-line text notification
+ multiLine: {
+ title: 'test_title',
+ text: 'test_text',
+ briefText: 'test_briefText',
+ longTitle: 'test_longTitle',
+ lines: ['line_01', 'line_02', 'line_03', 'line_04'],
+ }
+ }
+ }
+
+ // Publish the notification.
+ notificationManager.publish(notificationRequest, (err) => {
+ if (err) {
+ console.error(`[ANS] failed to publish, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] publish success`);
+ });
+ ```
+
+ Below is an example of the multi-line notification.
+ ![en-us_image_0000001417062446](figures/en-us_image_0000001417062446.png)
+ - In addition to the parameters in the normal text notification, the picture-attached text notification provides the **picture**, **briefText**, and **expandedTitle** parameters. The value of **picture** is a pixel map that does not exceed 2 MB.
+
+ ```ts
+ let notificationPicture: PixelMap = undefined; // Obtain the pixel map information.
+ let notificationRequest = {
+ id: 1,
+ content: {
+ contentType: notificationManager.ContentType.NOTIFICATION_CONTENT_PICTURE,
+ picture: {
+ title: 'test_title',
+ text: 'test_text',
+ additionalText: 'test_additionalText',
+ briefText: 'test_briefText',
+ expandedTitle: 'test_expandedTitle',
+ picture: notificationPicture
+ }
+ }
+ }
+
+ // Publish the notification.
+ notificationManager.publish(notificationRequest, (err) => {
+ if (err) {
+ console.error(`[ANS] failed to publish, error[${err}]`);
+ return;
+ }
+ console.info(`[ANS] publish success `);
+ });
+ ```
+
+ Below is an example of the picture-attached notification.
+ ![en-us_image_0000001466582045](figures/en-us_image_0000001466582045.png)
diff --git a/en/application-dev/quick-start/figures/02.png b/en/application-dev/quick-start/figures/02.png
index 19dd76ca232282b19883dde63075c5d155e7db70..eef374a1fd63f2b1e4d72e3323e7f4c23f5705fb 100644
Binary files a/en/application-dev/quick-start/figures/02.png and b/en/application-dev/quick-start/figures/02.png differ
diff --git a/en/application-dev/quick-start/figures/04.png b/en/application-dev/quick-start/figures/04.png
index cf23d17c7ee8552e30a5b234c97862b51981dcf8..1190d1e5aa631b12171632d258e4c4fae32e9bba 100644
Binary files a/en/application-dev/quick-start/figures/04.png and b/en/application-dev/quick-start/figures/04.png differ
diff --git a/en/application-dev/quick-start/figures/07.png b/en/application-dev/quick-start/figures/07.png
index 0f34d01d824ae1780c73cade9a39fff5f4b9b84e..17f2b060d300667ff250935b6a37485843e854ce 100644
Binary files a/en/application-dev/quick-start/figures/07.png and b/en/application-dev/quick-start/figures/07.png differ
diff --git a/en/application-dev/reference/apis/Readme-EN.md b/en/application-dev/reference/apis/Readme-EN.md
index 105928883e9ce6dd263cb9c52e67d8fd9855e5c2..80d0336aa005712ce116d5eb131ab299c1bff006 100644
--- a/en/application-dev/reference/apis/Readme-EN.md
+++ b/en/application-dev/reference/apis/Readme-EN.md
@@ -194,23 +194,24 @@
- [@ohos.resourceschedule.usageStatistics](js-apis-resourceschedule-deviceUsageStatistics.md)
- [@ohos.WorkSchedulerExtensionAbility](js-apis-WorkSchedulerExtensionAbility.md)
- Security
- - [@ohos.abilityAccessCtrl](js-apis-abilityAccessCtrl.md)
- - [@ohos.privacyManager](js-apis-privacyManager.md)
- - [@ohos.security.cryptoFramework](js-apis-cryptoFramework.md)
- - [@ohos.security.huks ](js-apis-huks.md)
- - [@ohos.userIAM.faceAuth](js-apis-useriam-faceauth.md)
- - [@ohos.userIAM.userAuth ](js-apis-useriam-userauth.md)
- - [@system.cipher](js-apis-system-cipher.md)
+ - [@ohos.abilityAccessCtrl (Ability Access Control)](js-apis-abilityAccessCtrl.md)
+ - [@ohos.privacyManager (Privacy Management)](js-apis-privacyManager.md)
+ - [@ohos.security.cert (Certificate)](js-apis-cert.md)
+ - [@ohos.security.cryptoFramework (Crypto Framework)](js-apis-cryptoFramework.md)
+ - [@ohos.security.huks (HUKS)](js-apis-huks.md)
+ - [@ohos.userIAM.faceAuth (Facial Authentication)](js-apis-useriam-faceauth.md)
+ - [@ohos.userIAM.userAuth (User Authentication)](js-apis-useriam-userauth.md)
+ - [@system.cipher (Cipher Algorithm)](js-apis-system-cipher.md)
- Data Management
- - [@ohos.data.dataAbility ](js-apis-data-ability.md)
- - [@ohos.data.dataShare](js-apis-data-dataShare.md)
- - [@ohos.data.dataSharePredicates](js-apis-data-dataSharePredicates.md)
- - [@ohos.data.dataShareResultSet](js-apis-data-DataShareResultSet.md)
- - [@ohos.data.distributedDataObject](js-apis-data-distributedobject.md)
- - [@ohos.data.distributedKVStore](js-apis-distributedKVStore.md)
- - [@ohos.data.preferences](js-apis-data-preferences.md)
- - [@ohos.data.rdb](js-apis-data-rdb.md)
- - [@ohos.data.ValuesBucket](js-apis-data-valuesBucket.md)
+ - [@ohos.data.dataAbility (DataAbility Predicates)](js-apis-data-ability.md)
+ - [@ohos.data.dataShare (DataShare)](js-apis-data-dataShare.md)
+ - [@ohos.data.dataSharePredicates (DataShare Predicates)](js-apis-data-dataSharePredicates.md)
+ - [@ohos.data.dataShareResultSet (DataShare Result Set)](js-apis-data-DataShareResultSet.md)
+ - [@ohos.data.distributedDataObject (Distributed Data Object)](js-apis-data-distributedobject.md)
+ - [@ohos.data.distributedKVStore (Distributed KV Store)](js-apis-distributedKVStore.md)
+ - [@ohos.data.preferences (Preferences)](js-apis-data-preferences.md)
+ - [@ohos.data.rdb (RDB)](js-apis-data-rdb.md)
+ - [@ohos.data.ValuesBucket (Value Bucket)](js-apis-data-valuesBucket.md)
- data/rdb
- [resultSet](js-apis-data-resultset.md)
- File Management
@@ -307,6 +308,7 @@
- [@ohos.sensor](js-apis-sensor.md)
- [@ohos.settings](js-apis-settings.md)
- [@ohos.stationary](js-apis-stationary.md)
+ - [@ohos.systemCapability (SystemCapability)](js-apis-system-capability.md)
- [@ohos.systemParameterV9](js-apis-system-parameterV9.md)
- [@ohos.thermal](js-apis-thermal.md)
- [@ohos.update](js-apis-update.md)
@@ -324,7 +326,7 @@
- [@ohos.enterprise.dateTimeManager](js-apis-enterprise-dateTimeManager.md)
- Language Base Class Library
- - [@ohos.buffer](js-apis-buffer.md)
+ - [@ohos.buffer (Buffer)](js-apis-buffer.md)
- [@ohos.convertxml](js-apis-convertxml.md)
- [@ohos.process](js-apis-process.md)
- [@ohos.uri](js-apis-uri.md)
diff --git a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md
index d593cf5a61697773be5837287f0e63d33cff3ce8..ed59083949a8d151e7e007e9b2475d20e91446e6 100644
--- a/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md
+++ b/en/application-dev/reference/apis/js-apis-abilityAccessCtrl.md
@@ -1,4 +1,4 @@
-# Ability Access Control
+# @ohos.abilityAccessCtrl (Ability Access Control)
The **AbilityAccessCtrl** module provides APIs for application permission management, including authentication, authorization, and revocation.
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md
index 80c507b83ab0012aafbdc9745810730a54997293..6f512b4f9f32904106f9120ea2fcc1095ec732b8 100644
--- a/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md
+++ b/en/application-dev/reference/apis/js-apis-app-ability-appRecovery.md
@@ -1,6 +1,6 @@
-# @ohos.app.ability.appRecovery
+# @ohos.app.ability.appRecovery (Application Recovery)
-The **appRecovery** module provides APIs for recovering faulty applications.
+The **appRecovery** module provides APIs for recovering failed applications.
> **NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md
index 3fb88a2b8ad93d3dbb5adf627f105d117ca86fda..f7203ef5de08d0151d65e2c65cf19b6e3855c1ea 100644
--- a/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md
+++ b/en/application-dev/reference/apis/js-apis-app-ability-errorManager.md
@@ -1,6 +1,6 @@
-# @ohos.app.ability.errorManager
+# @ohos.app.ability.errorManager (Error Manager)
-The **ErrorManager** module provides APIs for registering and deregistering error observers.
+The **errorManager** module provides APIs for registering and deregistering error observers.
> **NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-application-errorManager.md b/en/application-dev/reference/apis/js-apis-application-errorManager.md
index 5326b582120b6dcbf23a88bedb1ff4dcbe6192ae..b1a98049c70502462a6225a63efd642c164ca60c 100644
--- a/en/application-dev/reference/apis/js-apis-application-errorManager.md
+++ b/en/application-dev/reference/apis/js-apis-application-errorManager.md
@@ -1,6 +1,6 @@
-# @ohos.application.errorManager
+# @ohos.application.errorManager (Error Manager)
-The **ErrorManager** module provides APIs for registering and deregistering error observers.
+The **errorManager** module provides APIs for registering and deregistering error observers.
> **NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-battery-info.md b/en/application-dev/reference/apis/js-apis-battery-info.md
index 488c8f1633bc625610e122d37092cd2ed1ed254c..41d13ba5741ecf4324b1f4c859fb2a0a4bdf1d19 100644
--- a/en/application-dev/reference/apis/js-apis-battery-info.md
+++ b/en/application-dev/reference/apis/js-apis-battery-info.md
@@ -1,11 +1,10 @@
-# @ohos.batteryInfo
+# @ohos.batteryInfo (Battery Information)
The **batteryInfo** module provides APIs for querying the charger type, battery health status, and battery charging status.
> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
-
## Modules to Import
```js
diff --git a/en/application-dev/reference/apis/js-apis-batteryStatistics.md b/en/application-dev/reference/apis/js-apis-batteryStatistics.md
index 7c1df26a13d242c8c875efea9c523b19752d1c34..2bb3159fc3912a6a1fe272451ce31aa812052432 100644
--- a/en/application-dev/reference/apis/js-apis-batteryStatistics.md
+++ b/en/application-dev/reference/apis/js-apis-batteryStatistics.md
@@ -1,4 +1,4 @@
-# @ohos.batteryStatistics
+# @ohos.batteryStatistics (Battery Statistics)
The **batteryStatistics** module provides APIs for querying software and hardware power consumption statistics.
diff --git a/en/application-dev/reference/apis/js-apis-buffer.md b/en/application-dev/reference/apis/js-apis-buffer.md
index b5c914e7725c878305ff0235a33d8d98d6c6d6e4..72e65e53e63380ef4ea0aa9b33796e236bc7ee84 100644
--- a/en/application-dev/reference/apis/js-apis-buffer.md
+++ b/en/application-dev/reference/apis/js-apis-buffer.md
@@ -1,11 +1,12 @@
-# Buffer
+# @ohos.buffer (Buffer)
-> **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.
+A **Buffer** object represents a byte sequence of a fixed length. It is used to store binary data.
-A **Buffer** object represents a fixed-length sequence of bytes. It is used to store binary data.
+You can use the APIs provided by the Buffer module to process images and a large amount of binary data, and receive or upload files.
-You can use the APIs provided by the **Buffer** module to process images and a large amount of binary data, and receive or upload files.
+> **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
@@ -21,55 +22,23 @@ Enumerates the supported encoding formats of strings.
| Encoding Format | Description |
| ------- | -------------------- |
-| ascii | ASCII format. |
-| utf8 | UTF-8 |
-| utf-8 | UTF-8 format.|
-| utf16le | UTF-16LE format.|
-| ucs2 | UTF-16LE format.|
-| ucs-2 | UTF-16LE format.|
-| base64 | Base64 format.|
-| base64url | Base64 format.|
-| latin1 | ASCII format.|
-| binary | Binary format.|
-| hex | Hexadecimal format.|
-
-## Buffer
-
-### Attributes
-
-**System capability**: SystemCapability.Utils.Lang
-
-| Name| Type| Readable| Writable| Description|
-| -------- | -------- | -------- | -------- | -------- |
-| length | number | Yes| No| Length of the buffer, in bytes.|
-| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.|
-| byteOffset | number | Yes| No| Offset of the buffer in the memory pool.|
-
-**Error codes**
-
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
-
-| ID| Error Message|
-| -------- | -------- |
-| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. |
-
-**Example**
-
-```ts
-import buffer from '@ohos.buffer';
-
-let buf = buffer.from("1236");
-console.log(JSON.stringify(buf.length));
-let arrayBuffer = buf.buffer;
-console.log(JSON.stringify(new Uint8Array(arrayBuffer)));
-console.log(JSON.stringify(buf.byteOffset));
-```
-
-### alloc
+| 'ascii' | ASCII format, which is case insensitive.|
+| 'utf8' | UTF-8 format, which is case insensitive.|
+| 'utf-8' | UTF-8 format, which is case insensitive.|
+| 'utf16le' | UTF-16 little-endian format, which is case insensitive.|
+| 'ucs2' | UTF-16 little-endian format, which is case insensitive.|
+| 'ucs-2' | UTF-16 little-endian format, which is case insensitive.|
+| 'base64' | Base64 format, which is case insensitive.|
+| 'base64url' | Base64 format, which is case insensitive.|
+| 'latin1' | ASCII format, which is case insensitive.|
+| 'binary' | Binary format, which is case insensitive.|
+| 'hex' | Hexadecimal format, which is case insensitive.|
+
+## buffer.alloc
alloc(size: number, fill?: string | Buffer | number, encoding?: BufferEncoding): Buffer
-Allocates and initializes a **Buffer** instance of the specified size.
+Creates and initializes a **Buffer** instance of the specified length.
**System capability**: SystemCapability.Utils.Lang
@@ -77,8 +46,8 @@ Allocates and initializes a **Buffer** instance of the specified size.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.|
-| fill | string \| Buffer \| number | No| Pre-filled value. The default value is **0**.|
+| size | number | Yes| Size of the **Buffer** instance to create, in bytes.|
+| fill | string \| Buffer \| number | No| Value to be filled in the buffer. The default value is **0**.|
| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format (valid only when **fill** is a string). The default value is **utf-8**.|
**Return value**
@@ -97,12 +66,12 @@ let buf2 = buffer.alloc(5, 'a');
let buf3 = buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64');
```
-### allocUninitializedFromPool
+## buffer.allocUninitializedFromPool
allocUninitializedFromPool(size: number): Buffer
-Allocates a **Buffer** instance of the specified size from the buffer pool, without initializing it.
-To initialize the **Buffer** instance, call **fill()**.
+Creates a **Buffer** instance of the specified size from the buffer pool, without initializing it.
+You need to use [fill()](#fill) to initialize the **Buffer** instance created.
**System capability**: SystemCapability.Utils.Lang
@@ -110,7 +79,7 @@ To initialize the **Buffer** instance, call **fill()**.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| size | number | Yes| Size of the **Buffer** instance to allocate, in bytes.|
+| size | number | Yes| Size of the **Buffer** instance to create, in bytes.|
**Return value**
@@ -127,11 +96,12 @@ let buf = buffer.allocUninitializedFromPool(10);
buf.fill(0);
```
-### allocUninitialized
+## buffer.allocUninitialized
allocUninitialized(size: number): Buffer
-Allocates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool.
+Creates a **Buffer** instance of the specified size, without initializing it. This API does not allocate memory from the buffer pool.
+You need to use [fill()](#fill) to initialize the **Buffer** instance created.
**System capability**: SystemCapability.Utils.Lang
@@ -139,7 +109,7 @@ Allocates a **Buffer** instance of the specified size, without initializing it.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| size | number | Yes|Size of the **Buffer** instance to allocate, in bytes.|
+| size | number | Yes|Size of the **Buffer** instance to create, in bytes.|
**Return value**
@@ -156,7 +126,7 @@ let buf = buffer.allocUninitialized(10);
buf.fill(0);
```
-### byteLength
+## buffer.byteLength
byteLength(string: string | Buffer | TypedArray | DataView | ArrayBuffer | SharedArrayBuffer, encoding?: BufferEncoding): number
@@ -169,7 +139,7 @@ Obtains the number of bytes of a string based on the encoding format.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| string | string \| Buffer \| TypedArray \| DataView \| ArrayBuffer \| SharedArrayBuffer | Yes| Target string.|
-| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format. The default value is **utf-8**.|
+| encoding | [BufferEncoding](#bufferencoding) | No| Encoding format of the string. The default value is **utf-8**.|
**Return value**
@@ -187,7 +157,7 @@ console.log(`${str}: ${str.length} characters, ${buffer.byteLength(str, 'utf-8')
// Print: ½ + ¼ = ¾: 9 characters, 12 bytes
```
-### compare
+## buffer.compare
compare(buf1: Buffer | Uint8Array, buf2: Buffer | Uint8Array): -1 | 0 | 1
@@ -221,11 +191,11 @@ let res = buf1.compare(buf2);
console.log(Number(res).toString()); // Print 1.
```
-### concat
+## buffer.concat
concat(list: Buffer[] | Uint8Array[], totalLength?: number): Buffer
-Concatenates an array of **Buffer** instances into a new instance of the specified length.
+Concatenates an array of **Buffer** instances of the specified length into a new instance.
**System capability**: SystemCapability.Utils.Lang
@@ -234,7 +204,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
| list | Buffer[] \| Uint8Array[] | Yes| Array of instances to concatenate.|
-| totalLength | number | No| Total length of the new **Buffer** instance, in bytes.|
+| totalLength | number | No| Total length of bytes to be copied.|
**Return value**
@@ -244,7 +214,7 @@ Concatenates an array of **Buffer** instances into a new instance of the specifi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -261,7 +231,7 @@ let buf = buffer.concat([buf1, buf2]);
console.log(buf.toString('hex')); // 3132333461626364
```
-### from
+## buffer.from
from(array: number[]): Buffer;
@@ -290,11 +260,11 @@ let buf = buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]);
console.log(buf.toString('hex')); // 627566666572
```
-### from
+## buffer.from
from(arrayBuffer: ArrayBuffer | SharedArrayBuffer, byteOffset?: number, length?: number): Buffer
-Creates a **Buffer** instance that shares memory with the specified array of **Buffer** instances.
+Creates a **Buffer** instance of the specified length that shares memory with **arrayBuffer**.
**System capability**: SystemCapability.Utils.Lang
@@ -314,7 +284,7 @@ Creates a **Buffer** instance that shares memory with the specified array of **B
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -329,7 +299,7 @@ let ab = new ArrayBuffer(10);
let buf = buffer.from(ab, 0, 2);
```
-### from
+## buffer.from
from(buffer: Buffer | Uint8Array): Buffer
@@ -341,7 +311,7 @@ Creates a **Buffer** instance with the copy of another instance.
| Name| Type| Mandatory| Description|
| -------- | -------- | -------- | -------- |
-| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy. |
+| buffer | Buffer \| Uint8Array | Yes| **Buffer** instance to copy.|
**Return value**
@@ -358,7 +328,7 @@ let buf1 = buffer.from('buffer');
let buf2 = buffer.from(buf1);
```
-### from
+## buffer.from
from(object: Object, offsetOrEncoding: number | string, length: number): Buffer
@@ -385,10 +355,10 @@ Creates a **Buffer** instance based on the specified object.
```ts
import buffer from '@ohos.buffer';
-let buf = buffer.from(new String('this is a test'));
+let buf = buffer.from(new String('this is a test'), 'utf8', 14);
```
-### from
+## buffer.from
from(string: String, encoding?: BufferEncoding): Buffer
@@ -418,11 +388,11 @@ let buf1 = buffer.from('this is a test');
let buf2 = buffer.from('7468697320697320612074c3a97374', 'hex');
console.log (buf1.toString()); // Print: this is a test
-console.log(buf2.toString());
+console.log (buf2.toString()); // print: this is a test
```
-### isBuffer
+## buffer.isBuffer
isBuffer(obj: Object): boolean
@@ -454,7 +424,7 @@ buffer.isBuffer([]); // false
buffer.isBuffer(new Uint8Array(1024)); // false
```
-### isEncoding
+## buffer.isEncoding
isEncoding(encoding: string): boolean
@@ -485,6 +455,70 @@ console.log(buffer.isEncoding('utf/8').toString()); // Print: false
console.log(buffer.isEncoding('').toString()); // Print: false
```
+## buffer.transcode
+
+transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer
+
+Transcodes the given **Buffer** or **Uint8Array** object from one encoding format to another.
+
+**System capability**: SystemCapability.Utils.Lang
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| source | Buffer \| Uint8Array | Yes| Instance to encode.|
+| fromEnc | string | Yes| Current encoding format.|
+| toEnc | string | Yes| Target encoding format.|
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Buffer | New **Buffer** instance in the target encoding format.|
+
+**Example**
+
+```ts
+import buffer from '@ohos.buffer';
+
+let buf = buffer.alloc(50);
+let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii');
+console.log(newBuf.toString('ascii'));
+```
+
+## Buffer
+
+### Attributes
+
+**System capability**: SystemCapability.Utils.Lang
+
+| Name| Type| Readable| Writable| Description|
+| -------- | -------- | -------- | -------- | -------- |
+| length | number | Yes| No| Length of the **Buffer** instance, in bytes.|
+| buffer | ArrayBuffer | Yes| No| **ArrayBuffer** object.|
+| byteOffset | number | Yes| No| Offset of the **Buffer** instance in the memory pool.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 10200013 | Cannot set property ${propertyName} of Buffer which has only a getter. |
+
+**Example**
+
+```ts
+import buffer from '@ohos.buffer';
+
+let buf = buffer.from("1236");
+console.log(JSON.stringify(buf.length));
+let arrayBuffer = buf.buffer;
+console.log(JSON.stringify(new Uint8Array(arrayBuffer)));
+console.log(JSON.stringify(buf.byteOffset));
+```
+
### compare
compare(target: Buffer | Uint8Array, targetStart?: number, targetEnd?: number, sourceStart?: number, sourceEnd?: number): -1 | 0 | 1
@@ -507,7 +541,15 @@ Compares this **Buffer** instance with another instance.
| Type| Description|
| -------- | -------- |
-| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted. |
+| number | Returns **0** if the two **Buffer** instances are the same.
Returns **1** if this instance comes after the target instance when sorted.
Returns **-1** if this instance comes before the target instance when sorted.|
+
+**Error codes**
+
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
+
+| ID| Error Message|
+| -------- | -------- |
+| 10200001 | The value of "[targetStart/targetEnd/sourceStart/sourceEnd]" is out of range. |
**Example**
@@ -547,7 +589,7 @@ Copies data at the specified position in this **Buffer** instance to the specifi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -578,6 +620,13 @@ Creates and returns an iterator that contains key-value pairs of this **Buffer**
**System capability**: SystemCapability.Utils.Lang
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| number | Key of the iterator.|
+| number | Value of the iterator.|
+
**Example**
```ts
@@ -647,7 +696,7 @@ Fills this **Buffer** instance at the specified position. By default, data is fi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -739,7 +788,7 @@ Creates and returns an iterator that contains the keys of this **Buffer** instan
| Type| Description|
| -------- | -------- |
-| IterableIterator<number> | Iterator.|
+| IterableIterator<number> | Iterator created.|
**Example**
@@ -789,7 +838,7 @@ console.log(buf.lastIndexOf('buffer').toString()); // Print: 17
readBigInt64BE(offset?: number): bigint
-Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at the specified offset.
+Reads a signed, big-endian 64-bit integer from this **Buffer** instance at the specified offset.
**System capability**: SystemCapability.Utils.Lang
@@ -807,7 +856,7 @@ Reads a signed, big-endian 64-bit Big integer from this **Buffer** instance at t
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -848,7 +897,7 @@ Reads a signed, little-endian 64-bit Big integer from this **Buffer** instance a
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -889,7 +938,7 @@ Reads an unsigned, big-endian 64-bit Big integer from this **Buffer** instance a
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -930,7 +979,7 @@ Reads an unsigned, little-endian 64-bit Big integer from this **Buffer** instanc
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -971,7 +1020,7 @@ Reads a big-endian double-precision floating-point number from this **Buffer** i
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1011,7 +1060,7 @@ Reads a little-endian double-precision floating-point number from this **Buffer*
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1051,7 +1100,7 @@ Reads a big-endian single-precision floating-point number from this **Buffer** i
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1091,7 +1140,7 @@ Reads a little-endian single-precision floating-point number from this **Buffer*
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1131,7 +1180,7 @@ Reads a signed 8-bit integer from this **Buffer** instance at the specified offs
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1172,7 +1221,7 @@ Reads a signed, big-endian 16-bit integer from this **Buffer** instance at the s
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1212,7 +1261,7 @@ Reads a signed, little-endian 16-bit integer from this **Buffer** instance at th
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1252,7 +1301,7 @@ Reads a signed, big-endian 32-bit integer from this **Buffer** instance at the s
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1292,7 +1341,7 @@ Reads a signed, little-endian 32-bit integer from this **Buffer** instance at th
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1334,7 +1383,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1378,7 +1427,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1419,7 +1468,7 @@ Reads an unsigned 8-bit integer from this **Buffer** instance at the specified o
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1461,7 +1510,7 @@ Reads an unsigned, big-endian 16-bit integer from this **Buffer** instance at th
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1503,7 +1552,7 @@ Reads an unsigned, little-endian 16-bit integer from this **Buffer** instance at
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1545,7 +1594,7 @@ Reads an unsigned, big-endian 32-bit integer from this **Buffer** instance at th
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1586,7 +1635,7 @@ Reads an unsigned, little-endian 32-bit integer from this **Buffer** instance at
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1628,7 +1677,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1670,7 +1719,7 @@ Reads the specified number of bytes from this **Buffer** instance at the specifi
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1741,7 +1790,7 @@ Interprets this **Buffer** instance as an array of unsigned 16-bit integers and
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1776,7 +1825,7 @@ Interprets this **Buffer** instance as an array of unsigned 32-bit integers and
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1811,7 +1860,7 @@ Interprets this **Buffer** instance as an array of unsigned 64-bit integers and
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1901,7 +1950,7 @@ Creates and returns an iterator that contains the values of this **Buffer** inst
| Type| Description|
| -------- | -------- |
-| IterableIterator<number> | Iterator created.|
+| IterableIterator<number> | Iterator.|
**Example**
@@ -1940,7 +1989,7 @@ Writes a string of the specified length to this **Buffer** instance at the speci
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -1984,7 +2033,7 @@ Writes a signed, big-endian 64-bit Big integer to this **Buffer** instance at th
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2023,7 +2072,7 @@ Writes a signed, little-endian 64-bit Big integer to this **Buffer** instance at
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2062,7 +2111,7 @@ Writes an unsigned, big-endian 64-bit Big integer to this **Buffer** instance at
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2101,7 +2150,7 @@ Writes an unsigned, little-endian 64-bit Big integer to this **Buffer** instance
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2140,7 +2189,7 @@ Writes a big-endian double-precision floating-point number to this **Buffer** in
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2179,7 +2228,7 @@ Writes a little-endian double-precision floating-point number to this **Buffer**
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2218,7 +2267,7 @@ Writes a big-endian single-precision floating-point number to this **Buffer** in
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2258,7 +2307,7 @@ Writes a little-endian single-precision floating-point number to this **Buffer**
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2297,7 +2346,7 @@ Writes a signed 8-bit integer to this **Buffer** instance at the specified offse
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2338,7 +2387,7 @@ Writes a signed, big-endian 16-bit integer to this **Buffer** instance at the sp
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2378,7 +2427,7 @@ Writes a signed, little-endian 16-bit integer to this **Buffer** instance at the
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2417,7 +2466,7 @@ Writes a signed, big-endian 32-bit integer to this **Buffer** instance at the sp
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2457,7 +2506,7 @@ Writes a signed, little-endian 32-bit integer to this **Buffer** instance at the
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2497,7 +2546,7 @@ Writes a big-endian signed value of the specified length to this **Buffer** inst
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2538,7 +2587,7 @@ Writes a little-endian signed value of the specified length to this **Buffer** i
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2577,7 +2626,7 @@ Writes an unsigned 8-bit integer to this **Buffer** instance at the specified of
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2619,7 +2668,7 @@ Writes an unsigned, big-endian 16-bit integer to this **Buffer** instance at the
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2659,7 +2708,7 @@ Writes an unsigned, little-endian 16-bit integer to this **Buffer** instance at
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2699,7 +2748,7 @@ Writes an unsigned, big-endian 32-bit integer to this **Buffer** instance at the
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2738,7 +2787,7 @@ Writes an unsigned, little-endian 32-bit integer to this **Buffer** instance at
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2778,7 +2827,7 @@ Writes an unsigned big-endian value of the specified length to this **Buffer** i
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2818,7 +2867,7 @@ Writes an unsigned little-endian value of the specified length to this **Buffer*
**Error codes**
-For details about the error codes, see [Buffer Error Codes](../errorcodes/errorcode-buffer.md).
+For details about the error codes, see [Utils Error Codes](../errorcodes/errorcode-utils.md).
| ID| Error Message|
| -------- | -------- |
@@ -2833,38 +2882,6 @@ let buf = buffer.allocUninitializedFromPool(6);
buf.writeUIntLE(0x1234567890ab, 0, 6);
```
-### transcode
-
-transcode(source: Buffer | Uint8Array, fromEnc: string, toEnc: string): Buffer
-
-Transcodes the given **Buffer** or **Uint8Array** instance from one encoding format to another.
-
-**System capability**: SystemCapability.Utils.Lang
-
-**Parameters**
-
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| source | Buffer \| Uint8Array | Yes| Instance to transcode. |
-| fromEnc | string | Yes| Current encoding format.|
-| toEnc | string | Yes| Target encoding format.|
-
-**Return value**
-
-| Type| Description|
-| -------- | -------- |
-| Buffer | New **Buffer** instance in the target encoding format.|
-
-**Example**
-
-```ts
-import buffer from '@ohos.buffer';
-
-let buf = buffer.alloc(50);
-let newBuf = buffer.transcode(buffer.from('€'), 'utf-8', 'ascii');
-console.log(newBuf.toString('ascii'));
-```
-
## Blob
### Attributes
@@ -2941,7 +2958,7 @@ Creates a **Blob** instance by copying specified data from this **Blob** instanc
**Return value**
| Type| Description|
| -------- | -------- |
-| Blob | **Blob** instance created. |
+| Blob | New **Blob** instance created.|
**Example**
```ts
@@ -2954,7 +2971,7 @@ let blob3 = blob.slice(0, 2, "MIME");
text(): Promise<string>
-Returns text in UTF-8 format.
+Returns text in UTF-8 format. This API uses a promise to return the result.
**System capability**: SystemCapability.Utils.Lang
diff --git a/en/application-dev/reference/apis/js-apis-bytrace.md b/en/application-dev/reference/apis/js-apis-bytrace.md
index 544a4ba0d27e6c39794e063fc63282ba5455bf5e..89e14f7ad3e4fb3f525ccd9d5aab83b56e8c6521 100644
--- a/en/application-dev/reference/apis/js-apis-bytrace.md
+++ b/en/application-dev/reference/apis/js-apis-bytrace.md
@@ -1,4 +1,4 @@
-# Performance Tracing
+# @ohos.bytrace (Performance Tracing)
> **NOTE**
> - The APIs of this module are no longer maintained since API version 8. It is recommended that you use the APIs of [hiTraceMeter](js-apis-hitracemeter.md) instead.
diff --git a/en/application-dev/reference/apis/js-apis-call.md b/en/application-dev/reference/apis/js-apis-call.md
index 7c5bd52bd9ccbc5ee7ad99b8a1e7311ce8c5f8d5..0ccd49a5dc2a8b8e3577b7614f8219573de7cf7d 100644
--- a/en/application-dev/reference/apis/js-apis-call.md
+++ b/en/application-dev/reference/apis/js-apis-call.md
@@ -1,6 +1,6 @@
-# Call
+# @ohos.telephony.call (Call)
-The call module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers.
+The **call** module provides call management functions, including making calls, redirecting to the dial screen, obtaining the call status, and formatting phone numbers.
To subscribe to the call status, use [`observer.on('callStateChange')`](js-apis-observer.md#observeroncallstatechange).
diff --git a/en/application-dev/reference/apis/js-apis-cert.md b/en/application-dev/reference/apis/js-apis-cert.md
new file mode 100644
index 0000000000000000000000000000000000000000..dc506245c6feef1b2c22b70613ce3359404162dc
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-cert.md
@@ -0,0 +1,2109 @@
+# @ohos.security.cert (Certificate)
+
+The **certificate** module provides APIs for performing certificate operations. For details about the APIs for implementing the basic algorithm capabilities based on the cryptographic (crypto) framework, see [Crypto Framework](js-apis-cryptoFramework.md).
+
+> **NOTE**
+>
+> The initial APIs of this module are supported since API version 9.
+
+## Modules to Import
+
+```javascript
+import cryptoCert from '@ohos.security.cert';
+import cryptoFramework from "@ohos.security.cryptoFramework"
+```
+
+## CertResult
+
+ Enumerates the error codes.
+
+ **System capability**: SystemCapability.Security.Cert
+
+| Name | Value | Description |
+| --------------------------------------| -------- | -----------------------------|
+| INVALID_PARAMS | 401 | Invalid parameters. |
+| NOT_SUPPORT | 801 | This operation is not supported. |
+| ERR_OUT_OF_MEMORY | 19020001 | Memory error. |
+| ERR_RUNTIME_ERROR | 19020002 | Runtime error. |
+| ERR_CRYPTO_OPERATION | 19030001 | Crypto operation error. |
+| ERR_CERT_SIGNATURE_FAILURE | 19030002 | The certificate signature verification failed. |
+| ERR_CERT_NOT_YET_VALID | 19030003 | The certificate has not taken effect. |
+| ERR_CERT_HAS_EXPIRED | 19030004 | The certificate has expired. |
+| ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY | 19030005 | Failed to obtain the certificate issuer. |
+| ERR_KEYUSAGE_NO_CERTSIGN | 19030006 | The key cannot be used for signing a certificate. |
+| ERR_KEYUSAGE_NO_DIGITAL_SIGNATURE | 19030007 | The key cannot be used for digital signature. |
+
+## DataBlob
+Defines a binary data array.
+ **System capability**: SystemCapability.Security.Cert
+| Name | Type | Readable| Writable| Description |
+| -------------- | -------------- | ---- | ---- | ----------------|
+| data | Uint8Array | Yes | Yes | Data. |
+
+## DataArray
+
+Defines a list of data arrays.
+ **System capability**: SystemCapability.Security.Cert
+| Name | Type | Readable| Writable| Description |
+| -------------- | -------------- | ---- | ---- | ----------------|
+| data | Uint8Array | Yes | Yes | Data list. |
+
+## EncodingFormat
+
+ Enumerates the certificate encoding formats.
+
+ **System capability**: SystemCapability.Security.Cert
+
+| Name | Value| Description |
+| ---------- | ------ | --------- |
+| FORMAT_DER | 0 | Distinguished Encoding Rules (DER) format.|
+| FORMAT_PEM | 1 | Privacy-Enhanced Mail (PEM) format.|
+
+
+## EncodingBlob
+
+Defines a certificate binary array in encoding format.
+
+### Attributes
+
+**System capability**: SystemCapability.Security.Cert
+
+| Name | Type | Readable| Writable| Description |
+| -------------- | --------------------------------- | ---- | ---- | ------------------------------ |
+| data | Uint8Array | Yes | Yes | Certificate data.|
+| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. |
+
+
+## CertChainData
+
+Defines the certificate chain data, which is passed in as input parameters during certificate chain verification.
+
+### Attributes
+
+**System capability**: SystemCapability.Security.Cert
+
+| Name | Type | Readable| Writable| Description |
+| -------------- | --------------------------------- | ---- | ---- | ------------------------------------------------------------ |
+| data | Uint8Array | Yes | Yes | Certificate data, in the *length* (2 bytes) + *data* format. For example, **08ABCDEFGH07ABCDEFG**. The first two bytes indicate the length of the first certificate is eight bytes, and the following eight bytes indicate the certificate data. Then, the next two bytes indicate the length of another certificate is seven bytes, and the seven bytes followed indicate the certificate data.|
+| count | number | Yes | Yes | Number of certificates contained in the input data. |
+| encodingFormat | [EncodingFormat](#encodingformat) | Yes | Yes | Certificate encoding format. |
+
+
+## cryptoCert.createX509Cert
+
+createX509Cert(inStream : EncodingBlob, callback : AsyncCallback\) : void
+
+Creates an **X509Cert** instance. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------------- | ---- | -------------------------- |
+| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. **X509Cer** instance created.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoFramework.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ }
+});
+```
+
+## cryptoCert.createX509Cert
+
+createX509Cert(inStream : EncodingBlob) : Promise\
+
+Creates an **X509Cert** instance. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------------- | ---- | ------------------ |
+| inStream | [EncodingBlob](#encodingblob) | Yes | X.509 certificate serialization data.|
+
+**Return value**
+
+| Type | Description |
+| ------- | ---------------- |
+| Promise\ | **X509Cer** instance created.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
+ console.log("createX509Cert success");
+}, error => {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+## X509Cert
+
+Provides APIs for X.509 certificate operations.
+
+### verify
+
+verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void
+
+Verifies the certificate signature. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | --------------------- | ---- | ------------------------------------------------------------ |
+| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+import cryptoFramework from "@ohos.security.cryptoFramework"
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance.
+ let pubKey = null;
+ x509Cert.verify(pubKey, function (error, data) {
+ if (error != null) {
+ console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("verify success");
+ }
+ });
+ }
+});
+```
+
+### verify
+
+verify(key : cryptoFramework.PubKey) : Promise\
+
+Verifies the certificate signature. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ------------------ |
+| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | ----------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
+ console.log("createX509Cert success");
+ // Generate a public key by AsyKeyGenerator or obtain the public key by using getPublicKey() of the X509Cert instance.
+ let pubKey = null;
+ x509Cert.verify(pubKey).then(result => {
+ console.log("verify success");
+ }, error => {
+ console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
+ });
+}, error => {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### getEncoded
+
+getEncoded(callback : AsyncCallback\) : void
+
+Obtains the serialized X.509 certificate data. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------------------- | ---- | -------------------------------- |
+| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized X.509 certificate data obtained.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ x509Cert.getEncoded(function (error, data) {
+ if (error != null) {
+ console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("getEncoded success");
+ }
+ });
+ }
+});
+```
+
+### getEncoded
+
+getEncoded() : Promise\
+
+Obtains the serialized X.509 certificate data. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | ---------------------- |
+| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized X.509 certificate data obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob).then(x509Cert => {
+ console.log("createX509Cert success");
+ x509Cert.getEncoded().then(result => {
+ console.log("getEncoded success");
+ }, error => {
+ console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
+ });
+}, error => {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### getPublicKey
+
+getPublicKey() : cryptoFramework.PubKey
+
+Obtains the public key of this X.509 certificate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ---------------- |
+| cryptoFramework.PubKey | X.509 certificate public key obtained.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+import cryptoFramework from "@ohos.security.cryptoFramework"
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let pubKey = null;
+ try {
+ pubKey = x509Cert.getPublicKey();
+ } catch (error) {
+ console.log("getPublicKey failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
+ }
+});
+```
+
+### checkValidityWithDate
+
+checkValidityWithDate(date: string) : void
+
+Checks the validity period of this X.509 certificate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------- | ---- | ---------- |
+| date | string | Yes | Date of the certificate to check. |
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let date = "150527000001Z";
+
+ // Verify the certificate validity period.
+ try {
+ x509Cert.checkValidityWithDate(date);
+ } catch (error) {
+ console.log("checkValidityWithDate failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
+ }
+});
+```
+
+### getVersion
+
+getVersion() : number
+
+Obtains the X.509 certificate version.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ---------------- |
+| number | X.509 certificate version obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let version = x509Cert.getVersion();
+ }
+});
+```
+
+### getSerialNumber
+
+getSerialNumber() : number
+
+Obtains the X.509 certificate serial number.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------ |
+| number | X.509 certificate serial number obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let serialNumber = x509Cert.getSerialNumber();
+ }
+});
+```
+
+### getIssuerName
+
+getIssuerName() : DataBlob
+
+Obtains the X.509 certificate issuer.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ---------------------- |
+| [DataBlob](#datablob) | X.509 certificate issuer obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let issuerName = x509Cert.getIssuerName();
+ }
+});
+```
+
+### getSubjectName
+
+getSubjectName() : DataBlob
+
+Obtains the subject of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | -------------------- |
+| [DataBlob](#datablob) | Subject name obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let subjectName = x509Cert.getSubjectName();
+ }
+});
+```
+
+### getNotBeforeTime
+
+getNotBeforeTime() : string
+
+Obtains the start time of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------------------- |
+| string | Start time of the X.509 certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let notBefore = x509Cert.getNotBeforeTime();
+ }
+});
+```
+
+### getNotAfterTime
+
+getNotAfterTime() : string
+
+Obtains the expiration time of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------------------- |
+| string | Expiration time of the X.509 certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let notAfter = x509Cert.getNotAfterTime();
+ }
+});
+```
+
+### getSignature
+
+getSignature() : DataBlob
+
+Obtains the signature data of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | -------------------- |
+| [DataBlob](#datablob) | Signature data obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let signature = x509Cert.getSignature();
+ }
+});
+```
+
+### getSignatureAlgName
+
+getSignatureAlgName() : string
+
+Obtains the signing algorithm of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------------ |
+| string | X.509 certificate signing algorithm obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let sigAlgName = x509Cert.getSignatureAlgName();
+ }
+});
+```
+
+### getSignatureAlgOid
+
+getSignatureAlgOid() : string
+
+Obtains the object identifier (OID) of the X.509 certificate signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO).
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | --------------------------------- |
+| string | OID obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let sigAlgOid = x509Cert.getSignatureAlgOid();
+ }
+});
+```
+
+### getSignatureAlgParams
+
+getSignatureAlgParams() : DataBlob
+
+Obtains the signing algorithm parameters of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ------------------------ |
+| [DataBlob](#datablob) | X.509 certificate signing algorithm parameters obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let sigAlgParams = x509Cert.getSignatureAlgParams();
+ }
+});
+```
+
+### getKeyUsage
+
+getKeyUsage() : DataBlob
+
+Obtains the key usage of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | -------------------- |
+| [DataBlob](#datablob) | Key usage of the X.509 certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let keyUsage = x509Cert.getKeyUsage();
+ }
+});
+```
+
+### getExtKeyUsage
+
+getExtKeyUsage() : DataArray
+
+Obtains the usage of the extended key of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ----------------------- | ------------------------ |
+| [DataArray](#dataarray) | Usage of the extended key obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let extKeyUsage = x509Cert.getExtKeyUsage();
+ }
+});
+```
+
+### getBasicConstraints
+
+getBasicConstraints() : number
+
+Obtains the basic constraints for obtaining this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------------- |
+| number | Basic constraints obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let basicConstraints = x509Cert.getBasicConstraints();
+ }
+});
+```
+
+### getSubjectAltNames
+
+getSubjectAltNames() : DataArray
+
+Obtains the Subject Alternative Names (SANs) of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ----------------------- | ------------------------ |
+| [DataArray](#dataarray) | SANs obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let subjectAltNames = x509Cert.getSubjectAltNames();
+ }
+});
+```
+
+### getIssuerAltNames
+
+getIssuerAltNames() : DataArray
+
+Obtains the Issuer Alternative Names (IANs) of this X.509 certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ----------------------- | -------------------------- |
+| [DataArray](#dataarray) | IANs obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Certificate binary data, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Cert(encodingBlob, function (error, x509Cert) {
+ if (error != null) {
+ console.log("createX509Cert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Cert success");
+ let issuerAltNames = x509Cert.getIssuerAltNames();
+ }
+});
+```
+
+## cryptoCert.createX509Crl
+
+createX509Crl(inStream : EncodingBlob, callback : AsyncCallback\) : void
+
+Creates an **X509Crl** instance. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------------- | ---- | ------------------------------ |
+| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized certificate revocation list (CRL) data. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. Promise used to return the **X509Crl** instance created.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ }
+});
+```
+
+## cryptoCert.createX509Crl
+
+createX509Crl(inStream : EncodingBlob) : Promise\
+
+Creates an **X509Crl** instance. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------------- | ---- | -------------------------- |
+| inStream | [EncodingBlob](#encodingblob) | Yes | Serialized CRL data.|
+
+**Return value**
+
+| Type | Description |
+| ----------------- | -------------------- |
+| Promise\ | Promise used to return the **X509Crl** instance created.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
+ console.log("createX509Crl success");
+}, error => {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+## X509Crl
+
+Provides APIs for X.509 certificate CRL operations.
+
+### isRevoked
+
+isRevoked(cert : X509Cert) : boolean
+
+Checks whether an X.509 certificate is revoked. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | -------- | ---- | -------------------- |
+| cert | X509Cert | Yes | X.509 certificate to check.|
+
+**Return value**
+
+| Type | Description |
+| --------- | --------------------------------------------- |
+| boolean | Promise used to return the result. The value **true** indicates the certificate is revoked; the value **false** indicates the opposite.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ // Create an X509Cert instance.
+ let x509Cert = null;
+ try {
+ let revokedFlag = x509Crl.isRevoked(x509Cert);
+ } catch (error) {
+ console.log("isRevoked failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
+ }
+});
+```
+
+### getType
+
+getType() : string
+
+Obtains the CRL type.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------------- |
+| string | CRL type obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let type = x509Crl.getType();
+ }
+});
+```
+
+### getEncoded
+
+getEncoded(callback : AsyncCallback\) : void
+
+Obtains the serialized X.509 CRL data. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ---------------------------- | ---- | ------------------------------------------ |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the serialized X.509 CRL data obtained.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ x509Crl.getEncoded(function (error, data) {
+ if (error != null) {
+ console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("getEncoded success");
+ }
+ });
+ }
+});
+```
+
+### getEncoded
+
+getEncoded() : Promise\
+
+Obtains the serialized X.509 CRL data. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ---------------------- | -------------------------------- |
+| Promise\ | Promise used to return the serialized X.509 CRL data obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
+ console.log("createX509Crl success");
+ x509Crl.getEncoded().then(result => {
+ console.log("getEncoded success");
+ }, error => {
+ console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
+ });
+}, error => {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### verify
+
+verify(key : cryptoFramework.PubKey, callback : AsyncCallback\) : void
+
+Verifies the signature of the X.509 CRL. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ------------------------------------------------------------ |
+| key | cryptoFramework.PubKey | Yes | Public key used for signature verification. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the signature verification is successful. If **error** is not **null**, the signature verification fails.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+import cryptoFramework from "@ohos.security.cryptoFramework"
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ // Generate the public key by AsyKeyGenerator.
+ let pubKey = null;
+ x509Crl.verify(pubKey, function (error, data) {
+ if (error != null) {
+ console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("verify success");
+ }
+ });
+ }
+});
+```
+
+### verify
+
+verify(key : cryptoFramework.PubKey) : Promise\
+
+Verifies the signature of the X.509 CRL. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ---------------------- |
+| key | cryptoFramework.PubKey | Yes | Public key used for signature verification.|
+
+**Return value**
+
+| Type| Description |
+| ---- | ------------------------------------------------------------ |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+import cryptoFramework from "@ohos.security.cryptoFramework"
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
+ console.log("createX509Crl success");
+ // Generate the public key by AsyKeyGenerator.
+ let pubKey = null;
+ x509Crl.verify(pubKey).then(result => {
+ console.log("verify success");
+ }, error => {
+ console.log("verify failed, errCode: " + error.code + ", errMsg: " + error.message);
+ });
+}, error => {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### getVersion
+
+getVersion() : number
+
+Obtains the version of the X.509 CRL.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------------------------- |
+| number | Version of the X.509 CRL obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let version = x509Crl.getVersion();
+ }
+});
+```
+
+### getIssuerName
+
+getIssuerName() : DataBlob
+
+Obtains the issuer of the X.509 CRL.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ------------------------------ |
+| [DataBlob](#datablob) | Issuer of the X.509 CRL obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let issuerName = x509Crl.getIssuerName();
+ }
+});
+```
+
+### getLastUpdate
+
+getLastUpdate() : string
+
+Obtains the date when the X.509 CRL was last updated.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------------------------ |
+| string | Last update date of the X.509 CRL.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let lastUpdate = x509Crl.getLastUpdate();
+ }
+});
+```
+
+### getNextUpdate
+
+getNextUpdate() : string
+
+Obtains the date when the CRL will be updated the next time.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------------------------ |
+| string | Next update date obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let nextUpdate = x509Crl.getNextUpdate();
+ }
+});
+```
+
+### getRevokedCert
+
+getRevokedCert(serialNumber : number) : X509CrlEntry
+
+Obtains the revoked X.509 certificate based on the specified serial number of the certificate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------------ | ------ | ---- | -------------- |
+| serialNumber | number | Yes | Serial number of the certificate.|
+
+**Return value**
+
+| Type | Description |
+| ---------------------- | --------------------- |
+| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ // Set the serial number of the corresponding certificate.
+ let serialNumber = 1000;
+ try {
+ let entry = x509Crl.getRevokedCert(serialNumber);
+ } catch (error) {
+ console.log("getRevokedCert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
+ }
+});
+```
+
+### getRevokedCertWithCert
+
+getRevokedCertWithCert(cert : X509Cert) : X509CrlEntry
+
+Obtains the revoked X.509 certificate based on the specified certificate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name| Type | Mandatory| Description |
+| ------ | -------- | ---- | ------------ |
+| cert | X509Cert | Yes | Certificate based on which the revoked certificate is obtained.|
+
+**Return value**
+
+| Type | Description |
+| ------------ | -------------------- |
+| X509CrlEntry | Promise used to return the revoked X.509 certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ // Create an X509Cert instance.
+ let x509Cert = null;
+ try {
+ let entry = x509Crl.getRevokedCertWithCert(x509Cert);
+ } catch (error) {
+ console.log("getRevokedCertWithCert failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
+ }
+});
+```
+
+### getRevokedCerts
+
+getRevokedCerts(callback : AsyncCallback>) : void
+
+Obtains all the revoked X.509 certificates. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------------------- | ---- | -------------------------------- |
+| callback | AsyncCallback> | Yes | Callback invoked to return the result. Promise used to return a list of revoked X.509 certificates.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ x509Crl.getRevokedCerts(function (error, array) {
+ if (error != null) {
+ console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("getRevokedCerts success");
+ }
+ });
+ }
+});
+```
+
+### getRevokedCerts
+
+getRevokedCerts() : Promise>
+
+Obtains all the revoked X.509 certificates. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ----------------------------- | ---------------------- |
+| Promise> | Promise used to return a list of revoked X.509 certificates.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob).then(x509Crl => {
+ console.log("createX509Crl success");
+ x509Crl.getRevokedCerts().then(array => {
+ console.log("getRevokedCerts success");
+ }, error => {
+ console.log("getRevokedCerts failed, errCode: " + error.code + ", errMsg: " + error.message);
+ });
+}, error => {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### getTbsInfo
+
+getTbsInfo() : DataBlob
+
+Obtains the DER-encoded CRL information, the **tbsCertList** from this CRL. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ------------------------------- |
+| [DataBlob](#datablob) | Promise used to return the **tbsCertList** information obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ try {
+ let tbsInfo = x509Crl.getTbsInfo();
+ } catch (error) {
+ console.log("getTbsInfo failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
+ }
+});
+```
+
+### getSignature
+
+getSignature() : DataBlob
+
+Obtains the signature data of the X.509 CRL.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ------------------------------ |
+| [DataBlob](#datablob) | Signature data of the X.509 CRL obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let signature = x509Crl.getSignature();
+ }
+});
+```
+
+### getSignatureAlgName
+
+getSignatureAlgName() : string
+
+Obtains the signing algorithm of the X.509 CRL.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | -------------------------------- |
+| string | Signing algorithm obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let sigAlgName = x509Crl.getSignatureAlgName();
+ }
+});
+```
+
+### getSignatureAlgOid
+
+getSignatureAlgOid() : string
+
+Obtains the OID of the X.509 CRL signing algorithm. OIDs are allocated by the International Organization for Standardization (ISO).
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | --------------------------------------------- |
+| string | OID of the X.509 CRL signing algorithm obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let sigAlgOid = x509Crl.getSignatureAlgOid();
+ }
+});
+```
+
+### getSignatureAlgParams
+
+getSignatureAlgParams() : DataBlob
+
+Obtains the parameters of the X.509 CRL signing algorithm.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ---------------------------------- |
+| [DataBlob](#datablob) | Algorithm parameters obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Binary data of the CRL, which must be set based on the service.
+let encodingData = null;
+let encodingBlob = {
+ data: encodingData,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+cryptoCert.createX509Crl(encodingBlob, function (error, x509Crl) {
+ if (error != null) {
+ console.log("createX509Crl failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("createX509Crl success");
+ let sigAlgParams = x509Crl.getSignatureAlgParams();
+ }
+});
+```
+
+## cryptoCert.createCertChainValidator
+
+createCertChainValidator(algorithm :string) : CertChainValidator
+
+Creates a **CertChainValidator** object.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------- | ------ | ---- | ------------------------------------------ |
+| algorithm | string | Yes | Certificate chain validator algorithm. Currently, only **PKIX** is supported.|
+
+**Return value**
+
+| Type | Description |
+| ------------------ | -------------------- |
+| CertChainValidator | **CertChainValidator** object created.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+let validator = cryptoCert.createCertChainValidator("PKIX");
+```
+
+## CertChainValidator
+
+Provides APIs for certificate chain validator operations.
+
+
+### Attributes
+
+**System capability**: SystemCapability.Security.CryptoFramework
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | -------------------------- |
+| algorithm | string | Yes | No | Algorithm used by the X509 certificate chain validator.|
+
+
+### validate
+
+validate(certChain : CertChainData, callback : AsyncCallback\) : void
+
+Validates the X.509 certificate chain. This API uses an asynchronous callback to return the result.
+The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications).
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------- | ------------------------------- | ---- | ------------------------------------------------------------ |
+| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If **error** is **null**, the X.509 certificate chain is valid. If **error** is not **null**, the X.509 certificate chain is not valid.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+let validator = cryptoCert.createCertChainValidator("PKIX");
+// Certificate chain binary data, which must be set based on the service.
+let encodingData = null;
+// Number of certificates in the certificate chain. It must be set based on the service.
+let certCount = 2;
+let certChainData = {
+ data: encodingData,
+ count: certCount,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+validator.validate(certChainData, function (error, data) {
+ if (error != null) {
+ console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("validate success");
+ }
+});
+```
+
+### validate
+
+validate(certChain : CertChainData) : Promise\
+
+Validates the X.509 certificate chain. This API uses a promise to return the result.
+The certificate chain validator does not verify the certificate validity period because the system time on the device is untrusted. To check the validity period of a certificate, use the [checkValidityWithDate()](#checkvaliditywithdate) API of the **X509Cert** class. For details, see [Certificate Specifications](../../security/cert-overview.md#certificate-specifications).
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| --------- | ------------------------------- | ---- | -------------------------- |
+| certChain | [CertChainData](#certchaindata) | Yes | Serialized X.509 certificate chain data.|
+
+**Return value**
+
+| Type | Description |
+| -------------- | ----------- |
+| Promise\ | Promise used to return the result.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+let validator = cryptoCert.createCertChainValidator("PKIX");
+// Certificate chain binary data, which must be set based on the service.
+let encodingData = null;
+// Number of certificates in the certificate chain. It must be set based on the service.
+let certCount = 2;
+let certChainData = {
+ data: encodingData,
+ count: certCount,
+ // Set the encoding format, which can be FORMAT_PEM or FORMAT_DER.
+ encodingFormat: cryptoCert.EncodingFormat.FORMAT_PEM
+};
+validator.validate(certChainData).then(result => {
+ console.log("validate success");
+}, error => {
+ console.log("validate failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### algorithm
+
+algorithm : string
+
+Obtains the algorithm of the X.509 certificate chain validator.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------------ |
+| string | Algorithm of the X.509 certificate chain validator obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+let validator = cryptoCert.createCertChainValidator("PKIX");
+let algorithm = validator.algorithm;
+```
+
+## X509CrlEntry
+
+Provides APIs for operating the revoked certificates.
+
+### getEncoded
+
+getEncoded(callback : AsyncCallback\) : void
+
+Obtains the serialized data of this revoked certificate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------------------- | ---- | ------------------------------------ |
+| callback | AsyncCallback\<[EncodingBlob](#encodingblob)> | Yes | Callback invoked to return the result. Promise used to return the serialized data of the revoked certificate obtained.|
+
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
+let x509CrlEntry = null;
+x509CrlEntry.getEncoded(function (error, data) {
+ if (error != null) {
+ console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
+ } else {
+ console.log("getEncoded success");
+ }
+});
+```
+
+### getEncoded
+
+getEncoded() : Promise\
+
+Obtains the serialized data of this revoked certificate. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------------------------- | -------------------------- |
+| Promise\<[EncodingBlob](#encodingblob)> | Promise used to return the serialized data of the revoked certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
+let x509CrlEntry = null;
+x509CrlEntry.getEncoded().then(result => {
+ console.log("getEncoded success");
+}, error => {
+ console.log("getEncoded failed, errCode: " + error.code + ", errMsg: " + error.message);
+});
+```
+
+### getSerialNumber
+
+getSerialNumber() : number
+
+Obtains the serial number of this revoked certificate.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ---------------------- |
+| number | Serial number of the revoked certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
+let x509CrlEntry = null;
+let serialNumber = x509CrlEntry.getSerialNumber();
+```
+
+### getCertIssuer
+
+getCertIssuer() : DataBlob
+
+Obtains the issuer of this revoked certificate. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| --------------------- | ---------------------- - |
+| [DataBlob](#datablob) | Promise used to return the issuer of the revoked certificate obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
+let x509CrlEntry = null;
+try {
+ let issuer = x509CrlEntry.getCertIssuer();
+} catch (error) {
+ console.log("getCertIssuer failed, errCode: " + error.code + ", errMsg: " + error.message);
+}
+```
+
+### getRevocationDate
+
+getRevocationDate() : string
+
+Obtains the date when the certificate was revoked. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Security.Cert
+
+**Return value**
+
+| Type | Description |
+| ------ | ------------------ |
+| string | Promise used to return the certificate revocation date obtained.|
+
+**Example**
+
+```js
+import cryptoCert from '@ohos.security.cert';
+
+// Obtain X509CrlEntry by using getRevokedCert() of X509Crl.
+let x509CrlEntry = null;
+try {
+ let date = x509CrlEntry.getRevocationDate();
+} catch (error) {
+ console.log("getRevocationDate failed, errCode: " + error.code + ", errMsg: " + error.message);
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-contact.md b/en/application-dev/reference/apis/js-apis-contact.md
index a166781108683f6b6fb53673da4deacd99882b26..2778a143c65125eca650324e67a220ab60f64ead 100644
--- a/en/application-dev/reference/apis/js-apis-contact.md
+++ b/en/application-dev/reference/apis/js-apis-contact.md
@@ -1,4 +1,4 @@
-# Contacts
+# @ohos.contact (Contacts)
>**NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-cryptoFramework.md b/en/application-dev/reference/apis/js-apis-cryptoFramework.md
index 30d79a672420f70d0ab3067857e8726ab8a7ba32..4b6210a18736d99c786a2a305dc5ed534445b488 100644
--- a/en/application-dev/reference/apis/js-apis-cryptoFramework.md
+++ b/en/application-dev/reference/apis/js-apis-cryptoFramework.md
@@ -1,9 +1,9 @@
-# Crypto Framework
+# @ohos.security.cryptoFramework (Crypto Framework)
-The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for crytographic operations.
+The **cryptoFramework** module shields underlying hardware and algorithm libraries and provides unified APIs for cryptographic operations.
> **NOTE**
->
+>
> The initial APIs of this module are supported since API version 9.
## Modules to Import
@@ -18,20 +18,23 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Default Value | Description |
-| --------------------------------------| -------- | -------------------------|
-| INVALID_PARAMS | 401 | Invalid parameters. |
-| NOT_SUPPORT | 801 | This operation is not supported. |
-| ERR_OUT_OF_MEMORY | 17620001 | Memory error. |
-| ERR_RUNTIME_ERROR | 17620002 | Runtime error. |
-| ERR_CRYPTO_OPERATION | 17630001 | Crypto operation error. |
+| Name | Value | Description |
+| ------------------------------------- | -------- | ---------------------------- |
+| INVALID_PARAMS | 401 | Invalid parameters. |
+| NOT_SUPPORT | 801 | Unsupported operation. |
+| ERR_OUT_OF_MEMORY | 17620001 | Memory error. |
+| ERR_RUNTIME_ERROR | 17620002 | Runtime error. |
+| ERR_CRYPTO_OPERATION | 17630001 | Cryptographic operation error. |
## DataBlob
+
Defines a binary data array.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| -------------- | -------------- | ---- | ---- | ----------------|
-| data | Uint8Array | Yes | Yes | Data. |
+
+| Name| Type | Readable| Writable| Description |
+| ---- | ---------- | ---- | ---- | ------ |
+| data | Uint8Array | Yes | Yes | Data.|
+
## cryptoFramework.createMac
@@ -53,6 +56,12 @@ Creates a **Mac** instance for message authentication code (MAC) operations.
| ---- | --------------------------------------- |
| Mac | [Mac](#mac) instance created.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------ |
+| 17620001 | memory error |
+
**Example**
```javascript
@@ -60,6 +69,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
var mac;
try {
+ // Set algName based on the algorithm supported.
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
@@ -70,7 +80,7 @@ try {
Provides APIs for MAC operations. Before using any API of the **Mac** class, you must create a **Mac** instance by using [createMac](#cryptoframeworkcreatemac).
-### **Attributes**
+### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
@@ -88,10 +98,16 @@ Initializes the MAC computation using a symmetric key. This API uses an asynchro
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| key | SymKey | Yes | Shared symmetric key. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ------------ |
+| key | SymKey | Yes | Shared symmetric key.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
**Example**
@@ -118,8 +134,6 @@ symKeyGenerator.convertKey(KeyBlob, (err, symKey) => {
});
```
-
-
### init
init(key : SymKey) : Promise\;
@@ -136,10 +150,16 @@ Initializes the MAC computation using a symmetric key. This API uses a promise t
**Return value**
-| Type | Description |
-| --------------- | ------------ |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -149,9 +169,7 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
- AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message});
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
-
}
console.error("Mac algName is: " + mac.algName);
@@ -175,10 +193,18 @@ Updates the MAC computation data. This API uses an asynchronous callback to retu
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ---------- |
-| input | DataBlob | Yes | Message to pass in. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------- |
+| input | DataBlob | Yes | Data to pass in.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
**Example**
@@ -190,7 +216,6 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
- AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
@@ -220,16 +245,26 @@ Updates the MAC computation data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
+**Parameters**
+
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
-| input | DataBlob | Yes | Message to pass in.|
+| input | DataBlob | Yes | Data to pass in.|
**Return value**
-| Type | Description |
-| --------------- | ----------- |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
+
+**Example**
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
@@ -237,14 +272,11 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
- AlertDialog.show({message: "[Promise]: error code: " + error.code + ", message is: " + error.message});
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
-AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
-
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
var promiseConvertKey = symKeyGenerator.convertKey(KeyBlob);
promiseConvertKey.then(symKey => {
@@ -260,8 +292,6 @@ promiseConvertKey.then(symKey => {
```
-
-
### doFinal
doFinal(callback : AsyncCallback\) : void;
@@ -270,10 +300,19 @@ Finalizes the MAC computation. This API uses an asynchronous callback to return
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------- | ---- | -------- |
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------ | ---- | -------- |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17620001 | memory error |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -284,7 +323,6 @@ var mac;
try {
mac = cryptoFramework.createMac("SHA256");
} catch (error) {
- AlertDialog.show({message: "[Callback]: error code: " + error.code + ", message is: " + error.message});
console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
}
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
@@ -323,10 +361,17 @@ Finalizes the MAC computation. This API uses a promise to return the result.
**Return value**
-| Type | Description |
-| ------------------- | ----------- |
+| Type | Description |
+| ------------------ | ----------- |
| Promise\ | Promise used to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17620001 | memory error |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -339,7 +384,6 @@ try {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
-AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
@@ -375,6 +419,12 @@ Obtains the MAC length, in bytes.
| ------ | ------------------------- |
| number | MAC length obtained.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -387,7 +437,6 @@ try {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
}
console.error("Mac algName is: " + mac.algName);
-AlertDialog.show({message: "Mac algName is: " + mac.algName});
var KeyBlob;
var symKeyGenerator = cryptoFramework.createSymKeyGenerator("AES128");
@@ -405,7 +454,7 @@ promiseConvertKey.then(symKey => {
}).then(macOutput => {
console.error("[Promise]: HMAC result: " + macOutput.data);
let macLen = mac.getMacLength();
- AlertDialog.show({message: "MAC len: " + macLen});
+ console.error("MAC len: " + macLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
@@ -431,6 +480,12 @@ Creates an **Md** instance for message digest operations.
| ---- | ------------------------------------- |
| Md | [Md](#md) instance created.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------ |
+| 17620001 | memory error |
+
**Example**
```javascript
@@ -438,6 +493,7 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
var md;
try {
+ // Set algName based on the algorithm supported.
md = cryptoFramework.createMd("SHA256");
} catch (error) {
console.error("[Promise]: error code: " + error.code + ", message is: " + error.message);
@@ -448,27 +504,34 @@ try {
Provides APIs for message digest operations. Before using any API of the **Md** class, you must create an **Md** instance by using [createMd](#cryptoframeworkcreatemd).
-### **Attributes**
+### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
| Name | Type | Readable| Writable| Description |
| ------- | ------ | ---- | ---- | -------------------- |
-| algName | string | Yes | No | Digest algorithm to use.|
+| algName | string | Yes | No | Digest algorithm.|
### update
update(input : DataBlob, callback : AsyncCallback\) : void;
-Updates the message digest data with the message passed in. This API uses an asynchronous callback to return the result.
+Updates the message digest data. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------ |
-| input | DataBlob | Yes | Message to pass in. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+**Parameters**
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------- |
+| input | DataBlob | Yes | Data to pass in.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
**Example**
@@ -495,20 +558,26 @@ md.update(blob, (err,) => {
update(input : DataBlob) : Promise\;
-Updates the message digest data with the message passed in. This API uses a promise to return the result.
+Updates the message digest data. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
-| input | DataBlob | Yes | Message to pass in.|
+| input | DataBlob | Yes | Data to pass in.|
**Return value**
-| Type | Description |
-| --------------- | ------------ |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -539,10 +608,17 @@ Generates a message digest. This API uses an asynchronous callback to return the
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------- | ---- | -------------------- |
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------ | ---- | -------- |
| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17620001 | memory error |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -581,10 +657,17 @@ Generates a message digest. This API uses a promise to return the result.
**Return value**
-| Type | Description |
-| ------------------- | ----------- |
+| Type | Description |
+| ------------------ | ----------- |
| Promise\ | Promise used to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17620001 | memory error |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -622,7 +705,13 @@ Obtains the message digest length, in bytes.
| Type | Description |
| ------ | ------------------------ |
-| number | Message digest length obtained. |
+| number | Message digest length obtained.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17630001 | crypto operation error |
**Example**
@@ -645,7 +734,7 @@ promiseMdUpdate.then(() => {
}).then(mdOutput => {
console.error("[Promise]: MD result: " + mdOutput.data);
let mdLen = md.getMdLength();
- AlertDialog.show({message: "MD len: " + mdLen});
+ console.error("MD len: " + mdLen);
}).catch(error => {
console.error("[Promise]: error: " + error.message);
});
@@ -665,6 +754,12 @@ Creates a **Random** instance for generating random numbers and setting seeds.
| ------ | --------------------------------------------- |
| Random | [Random](#random) instance created.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------ |
+| 17620001 | memory error |
+
**Example**
```javascript
@@ -679,7 +774,7 @@ try {
## Random
-Provides APIs for computing random numbers. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom).
+Provides APIs for computing random numbers and setting seeds. Before using any API of the **Random** class, you must create a **Random** instance by using [createRandom](#cryptoframeworkcreaterandom).
### generateRandom
@@ -689,10 +784,19 @@ Generates a random number of the given length. This API uses an asynchronous cal
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Mandatory| Description |
-| -------- | ------------------------- | ---- | -------------------- |
-| len | number | Yes | Length of the random number to generate.|
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------ | ---- | -------------------- |
+| len | number | Yes | Length of the random number to generate.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17620001 | memory error |
+| 17630001 | crypto operation error |
**Example**
@@ -722,16 +826,25 @@ Generates a random number of the given length. This API uses a promise to return
**System capability**: SystemCapability.Security.CryptoFramework
+**Parameters**
+
| Name| Type | Mandatory| Description |
| ------ | ------ | ---- | -------------------- |
| len | number | Yes | Length of the random number to generate.|
**Return value**
-| Type | Description |
-| ------------------- | ----------- |
+| Type | Description |
+| ------------------ | ----------- |
| Promise\ | Promise used to return the result.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ---------------------- |
+| 17620001 | memory error |
+| 17630001 | crypto operation error |
+
**Example**
```javascript
@@ -754,16 +867,21 @@ promiseGenerateRand.then(randData => {
### setSeed
-setSeed(seed : DataBlob, callback : AsyncCallback\) : void;
+setSeed(seed : DataBlob) : void;
Sets a seed. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Mandatory| Description |
-| -------- | -------------------- | ---- | ------------ |
-| seed | DataBlob | Yes | Seed to set. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | --------------------- | ---- | ---------- |
+| seed | DataBlob | Yes | Seed to set.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ----------------- |
+| 17620001 | memory error |
**Example**
@@ -782,94 +900,70 @@ rand.generateRandom(12, (err, randData) => {
console.error("[Callback] err: " + err.code);
} else {
console.error("[Callback]: generate random result: " + randData.data);
- rand.setSeed(randData, (err1, data) => {
- if (err1) {
- console.error("[Callback] err: " + err1.code);
- } else {
- console.error("[Callback]: setSeed success");
- }
- });
+ try {
+ rand.setSeed(randData);
+ } catch (error) {
+ console.log("setSeed failed, errCode: " + error.code + ", errMsg: " + error.message);
+ }
}
});
```
-### setSeed
-
-setSeed(seed : DataBlob) : Promise\;
-
-Sets a seed. This API uses a promise to return the result.
-
-**System capability**: SystemCapability.Security.CryptoFramework
-
-| Name| Type | Mandatory| Description |
-| ------ | -------- | ---- | ---------- |
-| seed | DataBlob | Yes | Seed to set.|
-
-```javascript
-import cryptoFramework from "@ohos.security.cryptoFramework"
-
-var rand;
-try {
- rand = cryptoFramework.createRandom();
-} catch (error) {
- console.error("[Callback]: error code: " + error.code + ", message is: " + error.message);
-}
-
-var promiseGenerateRand = rand.generateRandom(12);
-promiseGenerateRand.then(randData => {
- console.error("[Promise]: rand result: " + randData.data);
- var promiseSetSeed = rand.setSeed(randData);
- return promiseSetSeed;
-}).then(() => {
- console.error("[Promise]: setSeed success");
-}).catch(error => {
- console.error("[Promise]: error: " + error.message);
-});
-```
-
## ParamsSpec
-Defines the parameters for encryption and decryption. For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). You do not need to construct the child class object if the IV is not required.
+Defines the parameters used for encryption and decryption.
For the symmetric encryption and decryption modes that require parameters such as the initialization vector (IV), you need to construct a child class object and pass it to [init()](#init-2). If the IV is not required (for example, the ECB mode), pass in **null** in [init()](#init-2).
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------- |
-| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters.
Options:
- **IvParamsSpec**: applicable to the CBC, CTR, OFB, and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode. |
+| Name | Type | Readable| Writable| Description |
+| -------- | ------ | ---- | ---- | ----------------------- |
+| algoName | string | Yes | Yes | Symmetric encryption and decryption parameters. Options:
- **IvParamsSpec**: applicable to the CBC,|CTR,|OFB, |and CFB modes.
- **GcmParamsSpec**: applicable to the GCM mode.
- **CcmParamsSpec**: applicable to the CCM mode.|
+
+> **NOTE**
+> The **params** parameter in [init()](#init-2) is of the **ParamsSpec** type (parent class), while a child class object (such as **IvParamsSpec**) needs to be passed in. When constructing the child class object, you must set **algoName** for the parent class **ParamsSpec** to let the algorithm library know the child class object to pass in in **init()**.
## IvParamsSpec
-Defines the parameters for the CBC, CTR, OFB, and CFB modes, which require only an IV for each encryption operation. For the symmetric encryption and decryption that use the CBC, CTR, OFB, or CFB mode, you need to construct **IvParamsSpec** and pass it to [init()](#init-2).
+Defines the child class of [ParamsSpec](#paramsspec). It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**IvParamsSpec** applies to the encryption and decryption modes such as CBC, CTR, OFB, and CFB, which use only the IV.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------- |
-| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption.
Options:
- AES CBC, CTR, OFB, or CFB mode: 16-byte IV
- 3DES CBC, OFB or CFB mode: 8-byte IV |
+| Name| Type | Readable| Writable| Description |
+| ---- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
+| iv | [DataBlob](#datablob) | Yes | Yes | IV for encryption and decryption. Options:
- AES CBC, |CTR, |OFB, |or CFB mode: 16-byte IV
- 3DES CBC,|OFB, or |CFB mode: 8-byte IV|
+
+> **NOTE**
+> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec).
## GcmParamsSpec
-Defines the parameters for the GCM mode. For the symmetric encryption and decryption that use the GCM mode, you need to construct **GcmParamsSpec** and pass it to [init()](#init-2).
+Defines the child class of [ParamsSpec](#paramsspec) for the GCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**GcmParamsSpec** applies to the GCM mode.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------- |
-| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes.|
-| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes.|
-| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 16 bytes.
When the GCM mode is used for encryption, the last 16 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [GcmParamsSpec](#gcmparamsspec) for decryption.|
+| Name | Type | Readable| Writable| Description |
+| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
+| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 12 bytes. |
+| aad | [DataBlob](#datablob) | Yes | Yes | Additional authenticated data (AAD), which is of 8 bytes. |
+| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 16 bytes.
When the GCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 16 bytes of [DataBlob](#datablob) are used as as **authTag** in [GcmParamsSpec](#gcmparamsspec) of [init()](#init-2). |
+
+> **NOTE**
+> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec).
## CcmParamsSpec
-Defines the parameters for the CCM mode. For the symmetric encryption and decryption that use the CCM mode, you need to construct **CcmParamsSpec** and pass it to [init()](#init-2).
+Defines the child class of [ParamsSpec](#paramsspec) for the CCM mode. It is used as the parameters of [init()](#init-2) during symmetric encryption and decryption.
**CcmParamsSpec** applies to the CCM mode.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | -------- | ---- | ---- | -------------------------------|
+| Name | Type | Readable| Writable| Description |
+| ------- | --------------------- | ---- | ---- | ------------------------------------------------------------ |
| iv | [DataBlob](#datablob) | Yes | Yes | IV, which is of 7 bytes. |
| aad | [DataBlob](#datablob) | Yes | Yes | AAD, which is of 8 bytes. |
-| authTag | [DataBlob](#datablob) | Yes | Yes | AuthTag, which is of 12 bytes.
When the CCM mode is used for encryption, the last 12 bytes of the [DataBlob](#datablob) returned by [doFinal()](#dofinal-2) are used as the **authTag** in [CcmParamsSpec](#ccmparamsspec) for decryption.|
+| authTag | [DataBlob](#datablob) | Yes | Yes | Authentication tag, which is of 12 bytes.
When the CCM mode is used for encryption, [DataBlob](#datablob) output by [doFinal()](#dofinal-2) is required. The last 12 bytes of [DataBlob](#datablob) are used as as **authTag** in [CcmParamsSpec](#ccmparamsspec) of [init()](#init-2).|
+
+> **NOTE**
+> Before passing [init()](#init-2), specify **algoName** for its parent class [ParamsSpec](#paramsspec).
## CryptoMode
@@ -877,22 +971,22 @@ Enumerates the cryptographic operations.
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Value | Description |
-| ------------ | -------- | -------------------------------- |
-| ENCRYPT_MODE | 0 | Encryption. |
-| DECRYPT_MODE | 1 | Decryption. |
+| Name | Value | Description |
+| ------------ | ---- | ---------------- |
+| ENCRYPT_MODE | 0 | Encryption.|
+| DECRYPT_MODE | 1 | Decryption.|
## Key
-Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance. Keys can be generated by a key generator.
+Provides APIs for key operations. Before performing cryptographic operations (such as encryption and decryption), you need to construct a child class object of **Key** and pass it to [init()](#init-2) of the [Cipher](#cipher) instance.
Keys can be generated by a key generator.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------- |
-| format | string | Yes | No | Format of the key.|
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| format | string | Yes | No | Format of the key. |
| algName | string | Yes | No | Algorithm name (including the key length).|
### getEncoded
@@ -905,48 +999,50 @@ Obtains the key in hexadecimal format. This API returns the result synchronously
**Return value**
-| Type |Description |
-| ------- | ----------- |
+| Type | Description |
+| --------------------- | ------------------------ |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
+import cryptoFramework from "@ohos.security.cryptoFramework"
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
-let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
+let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
let encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data));
```
## SymKey
-Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption. Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator).
+Provides APIs for symmetric key operations. It is a child class of [Key](#key). Its objects need to be passed to [init()](#init-2) of the [Cipher](#cipher) instance in symmetric encryption and decryption.
Symmetric keys can be generated by a [SymKeyGenerator](#symkeygenerator).
### clearMem
clearMem() : void
-Clears the keys from the memory. This API returns the result synchronously.
+Clears the keys in the memory. This API returns the result synchronously. You are advised to use this API when symmetric key instances are no longer used.
**System capability**: SystemCapability.Security.CryptoFramework
**Example**
```js
+import cryptoFramework from "@ohos.security.cryptoFramework"
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
-let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
+let key; // The key is generated by a symKeyGenerator. The generation process is omitted here.
let encodedKey = key.getEncoded();
-console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content.
+console.info("key hex: "+ uint8ArrayToShowStr(encodedKey.data)); // Display key content.
key.clearMem();
encodedKey = key.getEncoded();
console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display all 0s.
@@ -954,15 +1050,15 @@ console.info("key hex:" + uint8ArrayToShowStr(encodedKey.data)); // Display a
## PubKey
-Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Public keys can be generated by an **AsyKeyGenerator**.
+Provides APIs for public key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Public keys can be generated by an **AsyKeyGenerator**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------- |
-| format | string | Yes | No | Format of the key.|
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| format | string | Yes | No | Format of the key. |
| algName | string | Yes | No | Algorithm name (including the key length).|
@@ -976,30 +1072,37 @@ Obtains the key in binary format. This API returns the result synchronously. The
**Return value**
-| Type |Description |
-| ------- | ----------- |
+| Type | Description |
+| --------------------- | ------------------------ |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
+function uint8ArrayToShowStr(uint8Array) {
+ return Array.prototype.map
+ .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
+ .join('');
+}
+
+let key; // The key is a public key generated by the asymmetric key generator. The generation process is omitted here.
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
-console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
+console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data));
```
## PriKey
-Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement. Private keys can be generated by an **AsyKeyGenerator**.
+Provides APIs for private key operations. It is a child class of [Key](#key). Its objects need to be passed in during asymmetric encryption and decryption, signature verification, and key agreement.
Private keys can be generated by an **AsyKeyGenerator**.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------- |
-| format | string | Yes | No | Format of the key.|
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| format | string | Yes | No | Format of the key. |
| algName | string | Yes | No | Algorithm name (including the key length).|
### getEncoded
@@ -1012,52 +1115,74 @@ Obtains the key in binary format. This API returns the result synchronously. The
**Return value**
-| Type |Description |
-| ------- | ----------- |
+| Type | Description |
+| --------------------- | ------------------------ |
| [DataBlob](#datablob) | Key obtained.|
**Example**
```js
+function uint8ArrayToShowStr(uint8Array) {
+ return Array.prototype.map
+ .call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
+ .join('');
+}
+
+let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here.
console.info("key format:" + key.format);
console.info("key algName:" + key.algName);
var encodedKey = key.getEncoded();
-console.info("key encoded:" + Uint8ArrayToShowStr(encodedKey.data));
+console.info("key encoded:" + uint8ArrayToShowStr(encodedKey.data));
```
### clearMem
clearMem() : void
-Clears the keys from the memory. This API returns the result synchronously.
+Clears the keys in the memory. This API returns the result synchronously.
**System capability**: SystemCapability.Security.CryptoFramework
**Example**
```js
+let key; // The key is a private key generated by the asymmetric key generator. The generation process is omitted here.
key.clearMem();
```
+## KeyPair
+
+Defines an asymmetric key pair, which includes a public key and a private key.
Asymmetric key pairs can be generated by the **AsyKeyGenerator**.
+
+### Attributes
+
+**System capability**: SystemCapability.Security.CryptoFramework
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ------------ |
+| priKey | [PriKey](#prikey) | Yes | No | Private key. |
+| pubKey | [PubKey](#pubkey) | Yes | No | Public key. |
+
+
## cryptoFramework.createSymKeyGenerator
createSymKeyGenerator(algName : string) : SymKeyGenerator
-Creates a **SymKeyGenerator** instance based on the specified algorithm. For details about the supported symmetric key parameters, see "String for Generating a Key" in [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications).
+Creates a **symKeyGenerator** instance based on the specified algorithm.
For details about the supported specifications, see [Key Generation Specifications](../../security/cryptoFramework-overview.md#key-generation-specifications).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| ------- | ------ | ---- | ----------------------------- |
-| algName | string | Yes | Algorithm used by the **symkeyGenerator**.|
+| Name | Type | Mandatory| Description |
+| ------- | ------ | ---- | ------------------------------------------------------------ |
+| algName | string | Yes | Algorithm used to create the **symKeyGenerator** instance.
For details, see "String for Generating a Key" in [Key Generation Specifications] (../../security/cryptoFramework-overview.md#key-generation-specifications).|
**Return value**
-| Type | Description |
+| Type | Description |
| ----------------------------------- | -------------------------- |
-| [SymKeyGenerator](#symkeygenerator) | **SymKeyGenerator** instance created.|
+| [SymKeyGenerator](#symkeygenerator) | **symKeyGenerator** instance created.|
**Example**
@@ -1068,29 +1193,35 @@ let symKeyGenerator = cryptoFramework.createSymKeyGenerator('3DES192');
## SymKeyGenerator
-Provides APIs for using the **symKeyGenerator**. Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
+Provides APIs for using the **symKeyGenerator**.
Before using any API of the **SymKeyGenerator** class, you must create a **symKeyGenerator** instance by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| ------- | ------ | ---- | ---- | ---------------------------- |
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ------------------------------ |
| algName | string | Yes | No | Algorithm used by the **symKeyGenerator**.|
### generateSymKey
generateSymKey(callback : AsyncCallback\) : void
-Generates a key randomly. This API uses an asynchronous callback to return the result.
+Generates a key randomly. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------- | ---- | ------------------- |
-| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.|
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
+| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------- |
+| 17620001 | memory error. |
**Example**
@@ -1099,11 +1230,11 @@ import cryptoFramework from '@ohos.security.cryptoFramework';
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
symKeyGenerator.generateSymKey((err, symKey) => {
- if (err) {
- console.error('Failed to generate symKey');
- return;
- }
- console.log('Generate symKey success, algName: ' + symKey.algName);
+ if (err) {
+ console.error(`Generate symKey failed, ${err.code}, ${err.message}`);
+ } else {
+ console.info(`Generate symKey success, algName: ${symKey.algName}`);
+ }
})
```
@@ -1111,24 +1242,33 @@ symKeyGenerator.generateSymKey((err, symKey) => {
generateSymKey() : Promise\
-Generates a key randomly. This API uses a promise to return the result.
+Generates a key randomly. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**RAND_priv_bytes()** of OpenSSL can be used to generate random keys.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
-| Type | Description |
-| --------------------- | ------------------------------- |
+| Type | Description |
+| --------------------------- | --------------------------------- |
| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------- |
+| 17620001 | memory error. |
+
**Example**
```js
import cryptoFramework from '@ohos.security.cryptoFramework';
let symAlgoName = 'AES128';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
-symKeyGenerator.generateSymKey().then((symKey) => {
- console.log('Generate symKey success, algName:' + symKey.algName);
+symKeyGenerator.generateSymKey()
+.then(symKey => {
+ console.info(`Generate symKey success, algName: ${symKey.algName}`);
+}, error => {
+ console.error(`Generate symKey failed, ${error.code}, ${error.message}`);
})
```
@@ -1136,16 +1276,22 @@ symKeyGenerator.generateSymKey().then((symKey) => {
convertKey(key : DataBlob, callback : AsyncCallback\) : void
-Converts a key. This API uses an asynchronous callback to return the result.
+Converts data into a symmetric key. This API uses an asynchronous callback to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ----------------- | ---- | ---------------------- |
-| key | [DataBlob](#datablob) | Yes | Key to convert. |
-| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the symmetric key generated.|
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------------- | ---- | ------------------------------------------------------------ |
+| key | [DataBlob](#datablob) | Yes | Data to convert. |
+| callback | AsyncCallback\<[SymKey](#symkey)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined** and **data** is the symmetric key generated. Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | --------------------------------------------------- |
+| 17620001 | memory error. |
**Example**
@@ -1164,12 +1310,12 @@ function genKeyMaterialBlob() {
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
-symKeyGenerator.convertKey(keyMaterial, (err, symKey) => {
- if (err) {
- console.error('Failed to convert symKey');
- return;
- }
- console.log('Convert symKey success, algName:' + symKey.algName);
+symKeyGenerator.convertKey(keyMaterialBlob, (err, symKey) => {
+ if (err) {
+ console.error(`Convert symKey failed, ${err.code}, ${err.message}`);
+ } else {
+ console.info(`Convert symKey success, algName: ${symKey.algName}`);
+ }
})
```
@@ -1177,22 +1323,28 @@ symKeyGenerator.convertKey(keyMaterial, (err, symKey) => {
convertKey(key : DataBlob) : Promise\
-Converts a key. This API uses a promise to return the result.
+Converts data into a symmetric key. This API uses a promise to return the result.
This API can be used only after a **symKeyGenerator** instance is created by using [createSymKeyGenerator](#cryptoframeworkcreatesymkeygenerator).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name| Type | Mandatory| Description |
-| ---- | -------- | ---- | -------------------- |
-| key | [DataBlob](#datablob) | Yes | Key to convert.|
+| Name| Type | Mandatory| Description |
+| ---- | --------------------- | ---- | -------------------- |
+| key | [DataBlob](#datablob) | Yes | Data to convert.|
**Return value**
-| Type | Description |
-| --------------------- | ------------------------------- |
+| Type | Description |
+| --------------------------- | --------------------------------- |
| Promise\<[SymKey](#symkey)> | Promise used to return the symmetric key generated.|
+**Error codes**
+
+| ID| Error Message |
+| -------- | --------------------------------------------- |
+| 17620001 | memory error. |
+
**Example**
```js
@@ -1210,14 +1362,18 @@ function genKeyMaterialBlob() {
let symAlgoName = '3DES192';
let symKeyGenerator = cryptoFramework.createSymKeyGenerator(symAlgoName);
let keyMaterialBlob = genKeyMaterialBlob();
-symKeyGenerator.convertKey(keyMaterial).then((symKey) => {
- console.log('Convert symKey success, algName:' + symKey.algName);
+symKeyGenerator.convertKey(keyMaterialBlob)
+.then(symKey => {
+ console.info(`Convert symKey success, algName: ${symKey.algName}`);
+}, error => {
+ console.error(`Convert symKey failed, ${error.code}, ${error.message}`);
})
```
## cryptoFramework.createAsyKeyGenerator
createAsyKeyGenerator(algName : string) : AsyKeyGenerator
+
Creates an **AsyKeyGenerator** instance based on the specified algorithm.
**System capability**: SystemCapability.Security.CryptoFramework
@@ -1226,12 +1382,12 @@ Creates an **AsyKeyGenerator** instance based on the specified algorithm.
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | -------------------------------- |
-| algName | string | Yes | Algorithm used by the **symkeyGenerator**.|
+| algName | string | Yes | Algorithm used to create the **symkeyGenerator**.|
**Return value**
-| Type | Description |
-| --------------- | -------------------------- |
+| Type | Description |
+| --------------- | ---------------------------- |
| asyKeyGenerator | **AsyKeyGenerator** instance created.|
**Example**
@@ -1250,23 +1406,22 @@ Provides APIs for using the **AsKeyGenerator**. Before using any API of the **As
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable| Writable| Description |
-| -------------- | -------------- | ---- | ---- | ----------------------------------|
-| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**. |
-
-
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | -------------------------------- |
+| algName | string | Yes | No | Algorithm used by the **AsKeyGenerator**.|
### generateKeyPair
generateKeyPair(callback : AsyncCallback\) : void;
+
Generates a key pair randomly. This API uses an asynchronous callback to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------- | ---- | ---------------------------- |
+| Name | Type | Mandatory| Description |
+| -------- | ----------------------- | ---- | ------------------------------ |
| callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.|
**Example**
@@ -1288,14 +1443,15 @@ asyKeyGenerator.generateKeyPair((err, keyPair) => {
### generateKeyPair
generateKeyPair() : Promise\
+
Generates a key pair randomly. This API uses a promise to return the result.
**System capability**: SystemCapability.Security.CryptoFramework
**Return value**
-| Type | Description |
-| --------------------- | ------------------------------- |
+| Type | Description |
+| ----------------- | --------------------------------- |
| Promise\ | Promise used to return the key pair generated.|
**Example**
@@ -1315,23 +1471,25 @@ keyGenPromise.then( keyPair => {
### convertKey
convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void
-Converts an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**.
+
+Converts data into an asymmetric key. This API uses an asynchronous callback to return the result. For details, see **Key Conversion**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | -------------------------- | ---- | ---------------------------- |
-| pubKey | DataBlob | No | Public key material to convert. |
-| priKey | DataBlob | No | Private key material to convert. |
+| Name | Type | Mandatory| Description |
+| -------- | ----------- | ---- | ------------------------------ |
+| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**. |
+| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**. |
| callback | AsyncCallback\ | Yes | Callback invoked to return the key pair obtained.|
**Example**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
-
+let pubKey; // Public key data in DER format complying with X.509 specifications. The data is omitted here.
+let priKey; // Private key data in DER format complying with PKCS#8 specifications. The data is omitted here.
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => {
if (err) {
@@ -1345,21 +1503,22 @@ asyKeyGenerator.convertKey(pubKey, priKey, (err, keyPair) => {
### convertKey
convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\
-Converts an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**.
+
+Converts data into an asymmetric key. This API uses a promise to return the result. For details, see **Key Conversion**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name| Type | Mandatory| Description |
-| ---- | -------- | ---- | -------------------- |
-| pubKey | DataBlob | No | Public key material to convert. |
-| priKey | DataBlob | No | Private key material to convert. |
+| Name | Type | Mandatory| Description |
+| ------ | -------- | ---- | ---------------- |
+| pubKey | DataBlob | Yes | Public key material to convert. If no public key is required, set this parameter to **null**.|
+| priKey | DataBlob | Yes | Private key material to convert. If no private key is required, set this parameter to **null**.|
**Return value**
-| Type | Description |
-| --------------------- | ------------------------------- |
+| Type | Description |
+| ----------------- | --------------------------------- |
| Promise\ | Promise used to return the key pair generated.|
**Example**
@@ -1368,6 +1527,8 @@ Converts an asymmetric key. This API uses a promise to return the result. For de
import cryptoFramework from "@ohos.security.cryptoFramework"
let asyKeyGenerator = cryptoFramework.createAsyKeyGenerator("ECC256");
+let pubKey; // pubKey is a public key generated by the asymmetric key generator. The generation process is omitted here.
+let priKey; // priKey is a private key generated by the asymmetric key generator. The generation process is omitted here.
let keyGenPromise = asyKeyGenerator.convertKey(pubKey, priKey);
keyGenPromise.then( keyPair => {
console.info("convertKey success.");
@@ -1378,28 +1539,32 @@ keyGenPromise.then( keyPair => {
**Key Conversion**
-- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 and PKCS #8 formats is returned, respectively. The data can be used for cross-application transfer or persistent storage.
+- After **getEncoded()** is called for the asymmetric public and private keys (RSA and ECC), binary data in X.509 format and binary data in PKCS #8 format are returned, respectively. The data can be used for cross-application transfer or persistent storage.
- The public key returned by **convertKey()** must comply with the ASN.1 syntax, X.509 specifications, and DER encoding format, and the private key must comply with the ASN.1 syntax, PKCS #8 specifications, and DER encoding format.
-- In **convertKey()**, **pubKey** and **priKey** are optional. Either **pubKey** or **priKey** can be passed in. As a result, the returned **KeyPair** instance contains only the key converted from the data you passed in.
+- In **convertKey()**, you can pass in either **pubKey** or **priKey**, or both of them. If one of them is passed in, the returned **KeyPair** instance contains only the key converted from the data you passed in.
## cryptoFramework.createCipher
createCipher(transformation : string) : Cipher
-Creates a [Cipher](#cipher) instance based on the specified algorithm.
-For details about the supported algorithms, see "Algorithm String" in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications).
+
+Creates a [Cipher](#cipher) instance based on the specified algorithm.
For details about the supported specifications, see [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------------- | ------ | -------- | ------------------------------------------------------------ |
-| transformation | string | Yes | Combination of the algorithm name, encryption mode, and padding algorithm of the **Cipher** instance to create. For example, **RSA1024\|PKCS1** or **RSA1024\|PKCS1_OAEP\|SHA256\|SHA256**.|
+| Name | Type | Mandatory| Description |
+| -------------- | ------ | ---- | ------------------------------------------------------------ |
+| transformation | string | Yes | Combination of the algorithm name (including the key length), encryption mode, and padding algorithm of the **Cipher** instance to create.
For details about, see **Algorithm String** in [Encryption and Decryption Specifications](../../security/cryptoFramework-overview.md#encryption-and-decryption-specifications). |
+
+> **NOTE**
+> 1. In symmetric encryption and decryption, the implementation of PKCS #5 is the same as that of PKCS #7. PKCS #5 and PKCS #7 use the same padding length and block length. That is, data is padded with 8 bytes in 3DES and 16 bytes in AES. **noPadding** indicates that no padding is performed.
You need to understand the differences between different block cipher modes and use the correct parameter specifications. For example, padding is required for ECB and CBC. Otherwise, ensure that the plaintext length is an integer multiple of the block size. No padding is recommended for other modes. In this case, the ciphertext length is the same as the plaintext length.
+> 2. If RSA is used for asymmetric encryption and decryption, two **Cipher** objects must be created to perform encryption and decryption separately. For symmetric encryption and decryption, one **cipher** object can be used to perform both encryption and decryption as long as the algorithm specifications are the same.
**Return value**
-| Type | Description |
-| ------ | ------------------------ |
+| Type | Description |
+| ----------------- | ------------------------ |
| [Cipher](#cipher) | [Cipher](#cipher) instance created.|
**Example**
@@ -1414,39 +1579,51 @@ try {
console.info(`cipher algName: ${cipher.algName}`);
} catch (error) {
console.error(`createCipher failed, ${error.code}, ${error.message}`);
- return;
}
```
## Cipher
-Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption. For details about the complete encryption and decryption process, see [Encryption and Decryption Operations](../../security/cryptoFramework-guidelines.md#encryption-and-decryption-operations).
+Provides APIs for cipher operations. The [init()](#init-2), [update()](#update-4), and [doFinal()](#dofinal-2) APIs in this class are called in sequence to implement symmetric encryption or decryption and asymmetric encryption or decryption.
For details about the complete encryption and decryption process, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting-data).
+
+A complete symmetric encryption/decryption process is slightly different from the asymmetric encryption/decryption process.
+
+- Symmetric encryption and decryption: **init()** and **doFinal()** are mandatory. **update()** is optional and can be called multiple times to encrypt or decrypt big data. After **doFinal()** is called to complete an encryption or decryption operation, **init()** can be called to start a new encryption or decryption operation.
+- RSA asymmetric encryption and decryption: **init()** and **doFinal()** are mandatory, and **update()** is not supported. **doFinal()** can be called multiple times to encrypt or decrypt big data. **init()** cannot be called repeatedly. If the encryption/decryption mode or padding mode is changed, a new **Cipher** object must be created.
### Attributes
**System capability**: SystemCapability.Security.CryptoFramework
-| Name | Type | Readable | Writable | Description |
-| ------- | ------ | -------- | ----------- | ---------------------------- |
-| algName | string | Yes | No | Algorithm to use.|
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| algName | string | Yes | No | Algorithm.|
### init
init(opMode : CryptoMode, key : Key, params : ParamsSpec, callback : AsyncCallback\) : void
-Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result.
+Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback to return the result. **init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory | Description |
-| -------- | ------------------------ | ------- | ------------------------ |
-| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
-| key | [Key](#key) | Yes | Key for encryption or decryption. |
-| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------- | ---- | ------------------------------------------------------------ |
+| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
+| key | [Key](#key) | Yes | Key for encryption or decryption. |
+| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. If the initialization is successful, **err** is **undefined**. Otherwise, **err** is an error object. |
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | --------------------------------------------------------- |
+| 17620001 | memory error. |
+| 17620002 | runtime error. |
+| 17630001 | crypto operation error.|
**Example**
@@ -1454,13 +1631,14 @@ Initializes a [cipher](#cipher) instance. This API uses an asynchronous callback
import cryptoFramework from '@ohos.security.cryptoFramework';
let symKey; // The process of generating the symmetric key is omitted here.
let cipher; // The process of creating a Cipher instance is omitted here.
+
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => {
if (err) {
- console.error('Failed to init cipher');
- return;
+ console.error(`Failed to init cipher, ${err.code}, ${err.message}`);
+ } else {
+ console.info(`Init cipher success`);
+ // Perform subsequent operations such as update.
}
- console.log('Init cipher success');
- // Perform subsequent operations such as update.
})
```
@@ -1468,23 +1646,31 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null, (err, ) => {
init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\
-Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
+Initializes a [cipher](#cipher) instance. This API uses a promise to return the result.
**init()**This API can be used only after a [Cipher](#cipher) instance is created by using [createCipher](#cryptoframeworkcreatecipher).
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| ------ | ---------- | ---- | ---------------------- |
-| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
-| key | [Key](#key) | Yes | Key for encryption or decryption.|
-| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in. |
+| Name | Type | Mandatory| Description |
+| ------ | ------------------------- | ---- | ------------------------------------------------------------ |
+| opMode | [CryptoMode](#cryptomode) | Yes | Operation (encryption or decryption) to perform. |
+| key | [Key](#key) | Yes | Key for encryption or decryption. |
+| params | [ParamsSpec](#paramsspec) | Yes | Parameters for encryption or decryption. For algorithm modes without parameters (such as ECB), **null** can be passed in.|
**Return value**
-| Type | Description |
-| ------------------- | --------------------------- |
-| Promise\ | Promise used to return the result.|
+| Type | Description |
+| -------------- | -------------------------------------- |
+| Promise\ | Promise that returns no value.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------------------------------------- |
+| 17620001 | memory error. |
+| 17620002 | runtime error. |
+| 17630001 | crypto operation error.|
**Example**
@@ -1492,9 +1678,12 @@ Initializes a [cipher](#cipher) instance. This API uses a promise to return the
import cryptoFramework from '@ohos.security.cryptoFramework';
let symKey; // The process of generating the symmetric key is omitted here.
let cipher; // The process of creating a Cipher instance is omitted here.
-cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => {
- console.log('Init cipher success');
+cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null)
+.then(() => {
+ console.info(`Init cipher success`);
// Perform subsequent operations such as update.
+}, error => {
+ console.error(`Failed to init cipher, ${error.code}, ${error.message}`);
})
```
@@ -1502,16 +1691,29 @@ cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, symKey, null).then(() => {
update(data : DataBlob, callback : AsyncCallback\) : void
-Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data. The number of times that **update()** is called varies depending on the data volume.
+Updates the data to encrypt or decrypt by segment. This API uses an asynchronous callback to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2).
+
+> **NOTE**
+> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encrypted/decrypted block data generated by this **update()** is output.
That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext.
+> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.
+> - RSA asymmetric encryption and decryption do not support **update()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------- | ---- | ------------------------------------------ |
-| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. |
-| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
+| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}. |
+| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the operation is successful, **err** is **undefined**, and **data** is **DataBlob** (containing the encrypted or decrypted data). Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ------------------------------------------- |
+| 17620001 | memory error. |
+| 17620002 | runtime error. |
+| 17630001 | crypto operation error. |
**Example**
@@ -1531,11 +1733,14 @@ let cipher; // The process of creating a Cipher instance is omitted here.
let plainText = {data : stringToUint8Array('this is test!')};
cipher.update(plainText, (err, output) => { // Example of the encryption process.
if (err) {
- console.error('Failed to update cipher');
- return;
+ console.error(`Failed to update cipher`);
+ } else {
+ console.info(`Update cipher success`);
+ if (output != null) {
+ // Concatenate output.data to the ciphertext.
+ }
+ // Perform subsequent operations such as doFinal().
}
- console.log('Update cipher success');
- // Perform subsequent operations such as doFinal.
})
```
@@ -1543,21 +1748,34 @@ cipher.update(plainText, (err, output) => { // Example of the encryption p
update(data : DataBlob) : Promise\
-Updates the data to encrypt or decrypt by segment. This API uses a promise to return the result. The number of times that **update()** is called varies depending on the data volume.
+Updates the data to encrypt or decrypt by segment. This API uses a promise to return the encrypted or decrypted data.
This API can be called only after the [Cipher](#cipher) instance is initialized by using [init()](init-2).
+
+> **NOTE**
+> - If you are not familiar with the block modes for symmetric encryption and decryption, add a judgment to determine whether the result of each **update()** and **doFinal()** is null. If the result is not null, obtain the data to concatenate the complete ciphertext or plaintext. The reason is the block mode and the related specifications affect the **update()** and [doFinal()](#dofinal-2) results.
For example, in ECB and CBC modes, data is encrypted or decrypted by block no matter whether the data passed in by **update()** is an integer multiple of the block length, and the encryption/decryption block result generated by this **update()** is output. That is, encrypted/decrypted data is returned as long as the data passed in by **update()** reaches the size of a block. Otherwise, **null** is returned and the data will be retained until a block is formed in the next **update()**/**doFinal()**.
When **doFinal()** is called, the data that has not been encrypted or decrypted will be padded based on the padding mode set in [createCipher](#cryptoframeworkcreatecipher) to an integer multiple of the block length, and then encrypted or decrypted.
For a mode in which a block cipher can be converted into a stream cipher, the length of the ciphertext may be the same as that of the plaintext.
+> - **update()** may be called multiple times or may not be called ([doFinal()](#dofinal-2) is called after [init](#init-2)), depending on the size of the data to encrypt or decrypt.
The algorithm library does not set a limit on the amount of data that can be passed in by **updated()** (once or accumulatively). For symmetric encryption and decryption of a large amount of data, you are advised to call **update()** multiple times to pass in the data by segment.
+> - RSA asymmetric encryption and decryption do not support **update()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name| Type | Mandatory| Description |
-| ---- | -------- | ---- | -------------------- |
-| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.|
+| Name| Type | Mandatory| Description |
+| ---- | --------------------- | ---- | -------------------- |
+| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It cannot be **null** or {data:Uint8Array (null)}.|
**Return value**
-| Type | Description |
-| ----------------------- | --------------------------- |
-| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
+| Type | Description |
+| ------------------------------- | ------------------------------------------------ |
+| Promise\<[DataBlob](#datablob)> | Promise used to returns the **DataBlob** (containing the encrypted or decrypted data).|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | -------------------------------------------- |
+| 17620001 | memory error. |
+| 17620002 | runtime error. |
+| 17630001 | crypto operation error. |
**Example**
@@ -1575,9 +1793,15 @@ function stringToUint8Array(str) {
let cipher; // The process of creating a Cipher instance is omitted here.
// The init() process is omitted here.
let plainText = {data : stringToUint8Array('this is test!')};
-cipher.update(data).then((output) => {
- console.log('Update cipher success');
- // Perform subsequent operations such as doFinal.
+cipher.update(plainText)
+.then((output) => {
+ console.info(`Update cipher success.`);
+ if (output != null) {
+ // Concatenate output.data to the ciphertext.
+ }
+ // Perform subsequent operations such as doFinal().
+}, error => {
+ console.info(`Update cipher failed.`);
})
```
@@ -1585,23 +1809,33 @@ cipher.update(data).then((output) => {
doFinal(data : DataBlob, callback : AsyncCallback\) : void
-Finalizes the data encryption or decryption operation. This API uses an asynchronous callback to return the result.
+ (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses an asynchronous callback to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use.
-The output of **doFinal** varies depending on the symmetric encryption and decryption mode.
+- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**.
**authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption.
+- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext.
-- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption.
-- For symmetric encryption and decryption in other modes, the output can be either of the following:
- (1) **Update()** returns part of the encryption and decryption result, and **doFinal()** returns the remaining encryption and decryption result.
- (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value.
+ (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses an asynchronous callback to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext.
+
+> **NOTE**
+> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**.
+> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | ---------------------------- | ---- | ------------------------------------------ |
-| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt.
If data is already passed in by [update()](#update-4), **data** can be **null**. |
-| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the encrypted or decrypted data.|
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------------------- | ---- | ------------------------------------------------------------ |
+| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null** in symmetric encryption or decryption, but cannot be {data:Uint8Array(null)}. |
+| callback | AsyncCallback\<[DataBlob](#datablob)> | Yes | Callback invoked to return the result. If the data is successfully encrypted or decrypted, **err** is **undefined**, and **data** is the **DataBlob** (encryption or decryption result of the remaining data). Otherwise, **err** is an error object.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | ----------------------- |
+| 17620001 | memory error. |
+| 17620002 | runtime error. |
+| 17630001 | crypto operation error. |
**Example**
@@ -1613,10 +1847,13 @@ let data; // The process of preparing the data to encrypt or decrypt i
// The init() and update() processes are omitted here.
cipher.doFinal(data, (err, output) => {
if (err) {
- console.error('Failed to final cipher');
- return;
+ console.error(`Failed to finalize cipher, ${err.code}, ${err.message}`);
+ } else {
+ console.info(`Finalize cipher success`);
+ if (output != null) {
+ // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag).
+ }
}
- console.log('Final cipher success');
})
```
@@ -1624,31 +1861,38 @@ cipher.doFinal(data, (err, output) => {
doFinal(data : DataBlob) : Promise\
-Finalizes the data encryption or decryption operation. This API uses a promise to return the result.
-
-The output of **doFinal** varies depending on the symmetric encryption and decryption mode.
-
-- For symmetric encryption in GCM or CCM mode, **doFinal** returns the combination of the remaining ciphertext and **authTag**. **authTag** is the last 16 bytes for the GCM mode or the last 12 bytes for the CCM mode. If **data** of **doFinal** is **null**, **doFinal** returns **authTag**. After **doFinal** is complete, **authTag** needs to be temporarily stored and filled in [**GcmParamsSpec**](#gcmparamsspec) or [**CcmParamsSpec**](#ccmparamsspec) during decryption.
+ (1) Encrypts or decrypts the remaining data (generated by the block ciper mode) and the data passed in by **doFinal()** to finalize the symmetric encryption or decryption. This API uses a promise to return the encrypted or decrypted data.
If a small amount of data needs to be encrypted or decrypted, you can use **doFinal()** to pass in data without using **update()**. If all the data has been passed in by [update()](#update-4), you can pass in **null** in **data** of **doFinal()**.
The output of **doFinal()** varies with the symmetric encryption/decryption mode in use.
-- For symmetric encryption and decryption in other modes, the output includes the following:
+- Symmetric encryption in GCM and CCM mode: The result consists of the ciphertext and **authTag** (the last 16 bytes for GCM and the last 12 bytes for CCM). If **null** is passed in by **data** of **doFinal()**, the result of **doFinal()** is **authTag**. **authTag** must be [GcmParamsSpec](#gcmparamsspec) or [CcmParamsSpec](#ccmparamsspec) used for decryption. The ciphertext is the **data** passed in for decryption.
+- Symmetric encryption and decryption in other modes and symmetric decryption in GCM and CCM modes: The result is the complete plaintext/ciphertext.
- (1) **Update()** returns part of the encryption and decryption results, and **doFinal()** returns the remaining encryption and decryption results.
+ (2) Encrypts or decrypts the input data for RSA asymmetric encryption/decryption. This API uses a promise to return the result. If a large amount of data needs to be encrypted/decrypted, call **doFinal()** multiple times and concatenate the result of each **doFinal()** to obtain the complete plaintext/ciphertext.
- (2) **Update()** returns all the encryption and decryption result, and **doFinal()** returns no value.
+> **NOTE**
+> - In symmetric encryption or decryption, calling **doFinal()** means the end of an encryption or decryption process, and the [Cipher](#cipher) instance state will be cleared. To start a new encryption or decryption operation, you must call [init()](#init-2) to pass in a complete parameter list for initialization.
For example, if the same symmetric key is used for a **Cipher** instance to perform encryption and then decryption. After the encryption is complete, the **params** in **init** for decryption must be set instead of being **null**.
+> - If a decryption fails, check whether the data to be encrypted and decrypted matches the parameters in **[init](#init-2)**. For the GCM mode, check whether the **authTag** obtained after encryption is obtained from the **GcmParamsSpec** for decryption.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name| Type | Mandatory| Description |
-| ---- | -------- | ---- | -------------------- |
-| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. If data is already passed in by [update()](#update-4), **data** can be **null**. |
+| Name| Type | Mandatory| Description |
+| ---- | --------------------- | ---- | -------------------- |
+| data | [DataBlob](#datablob) | Yes | Data to encrypt or decrypt. It can be **null**, but cannot be {data:Uint8Array(null)}.|
**Return value**
-| Type | Description |
-| ----------------------- | --------------------------- |
-| Promise\<[DataBlob](#datablob)> | Promise used to return the result.|
+| Type | Description |
+| ------------------------------- | ------------------------------------------------ |
+| Promise\<[DataBlob](#datablob)> | Promise used to return the **DataBlob**, which is the encryption or decryption result of the remaining data.|
+
+**Error codes**
+
+| ID| Error Message |
+| -------- | -------------------------------------------- |
+| 17620001 | memory error. |
+| 17620002 | runtime error. |
+| 17630001 | crypto operation error. |
**Example**
@@ -1658,22 +1902,37 @@ import cryptoFramework from '@ohos.security.cryptoFramework';
let cipher; // The process of creating a Cipher instance is omitted here.
let data; // The process of preparing the data to encrypt or decrypt is omitted here.
// The init() and update() processes are omitted here.
-cipher.doFinal(data).then((output) => {
- console.log('Final cipher success');
+cipher.doFinal(data)
+.then(output => {
+ console.info(`Finalize cipher success`);
+ if (output != null) {
+ // Concatenate output.data to obtain the complete plaintext/ciphertext (and authTag).
+ }
+}, error => {
+ console.error(`Failed to finalize cipher, ${error.code}, ${error.message}`);
})
```
-**Callback example**:
+**RSA encryption example (callback)**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
+function stringToUint8Array(str) {
+ let arr = [];
+ for (let i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ return new Uint8Array(arr);
+}
+
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
rsaGenerator.generateKeyPair(function (err, keyPair) {
let pubKey = keyPair.pubKey;
cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null, function (err, data) {
- let input = {data : stringToUint8Array(plan) };
+ let plainText = "this is cipher text";
+ let input = {data : stringToUint8Array(plainText) };
cipher.doFinal(input, function (err, data) {
AlertDialog.show({ message : "EncryptOutPut is " + data.data} );
});
@@ -1681,11 +1940,19 @@ rsaGenerator.generateKeyPair(function (err, keyPair) {
});
```
-**Promise example**:
+**RSA encryption example (promise)**
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
+function stringToUint8Array(str) {
+ let arr = [];
+ for (let i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ return new Uint8Array(arr);
+}
+
let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
let cipher = cryptoFramework.createCipher("RSA1024|PKCS1");
let keyGenPromise = rsaGenerator.generateKeyPair();
@@ -1693,13 +1960,16 @@ keyGenPromise.then(rsaKeyPair => {
let pubKey = rsaKeyPair.pubKey;
return cipher.init(cryptoFramework.CryptoMode.ENCRYPT_MODE, pubKey, null); // Pass in the private key and DECRYPT_MODE to initialize the decryption mode.
}).then(() => {
- let input = { data : stringToUint8Array(plan) };
+ let plainText = "this is cipher text";
+ let input = { data : stringToUint8Array(plainText) };
return cipher.doFinal(input);
}).then(dataBlob => {
console.info("EncryptOutPut is " + dataBlob.data);
});
```
+> **NOTE**
+> For more encryption and decryption examples, see [Encrypting and Decrypting Data](../../security/cryptoFramework-guidelines.md#encrypting-and-decrypting data).
## cryptoFramework.createSign
@@ -1717,9 +1987,9 @@ Creates a **Sign** instance.
**Return value**
-| Type| Description |
-| ---- | ------------------------------ |
-| Sign | **Sign** instance created.|
+| Type| Description |
+| ---- | -------------------------------- |
+| Sign | **Sign** instance created.|
**Example**
@@ -1728,46 +1998,58 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
let signer1 = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
-let singer2 = cryptoFramework.createSign("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256")
+let singer2 = cryptoFramework.createSign("RSA1024|PSS|SHA256|MGF1_SHA256")
```
## Sign
-Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**.
+Provides APIs for signing. Before using any API of the **Sign** class, you must create a **Sign** instance by using **createSign()**. The **Sign** class does not support repeated initialization. When a new key is used for signing, you must create a new **Sign** object and call **init()** for initialization.
+The signing mode is determined in **createSign()**, and the key is set by **init()**.
+If the data to be signed is short, you can call **sign()** to pass in the data for signing after **init()**.
+If the data to be signed is long, you can use **update()** to pass in the data by segment, and then use **sign()** to sign the entire data.
+If **update()** is used to pass in data by segment, **data** of **sign()** can be **null**.
+
+### Attributes
+
+**System capability**: SystemCapability.Security.CryptoFramework
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| algName | string | Yes | No | Algorithm to use.|
### init
init(priKey : PriKey, callback : AsyncCallback\) : void
-Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result.
+Initializes a **Sign** instance using a private key. This API uses an asynchronous callback to return the result. The **Sign** class does not support repeated calling of **init()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| priKey | Key |Yes| Private key used for the initialization.|
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------------- |
+| priKey | PriKey | Yes | Private key used for the initialization.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
### init
-init(opMode : CryptoMode, key : Key, params : ParamsSpec) : Promise\
+init(priKey : PriKey) : Promise\
-Initializes a **Sign** instance using a private key. This API uses a promise to return the result.
+Initializes a **Sign** instance using a private key. This API uses a promise to return the result. The **Sign** class does not support repeated calling of **init()**.
**System capability**: SystemCapability.Security.CryptoFramework
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| priKey | Key |Yes| Private key used for the initialization.|
+| Name| Type| Mandatory| Description |
+| ------ | ---- | ---- | ---------------- |
+| priKey | PriKey | Yes | Private key used for the initialization.|
**Return value**
-| Type | Description |
-| ------------- | ----------- |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
### update
@@ -1780,10 +2062,10 @@ Updates the data to be signed. This API uses an asynchronous callback to return
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| data | DataBlob | Yes | Message to pass in. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------- |
+| data | DataBlob | Yes | Data to pass in.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
### update
@@ -1797,12 +2079,12 @@ Updates the data to be signed. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
-| data | DataBlob | Yes | Message to pass in. |
+| data | DataBlob | Yes | Data to pass in.|
**Return value**
-| Type | Description |
-| ------------- | ----------- |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
### sign
@@ -1815,10 +2097,10 @@ Signs the data. This API uses an asynchronous callback to return the result.
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| data | DataBlob | Yes | Message to pass in. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------- |
+| data | DataBlob | Yes | Data to pass in.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
### sign
@@ -1832,53 +2114,92 @@ Signs the data. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
-| data | DataBlob | Yes | Message to pass in. |
+| data | DataBlob | Yes | Data to pass in.|
**Return value**
-| Type | Description |
-| ------------- | ----------- |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
**Callback example**:
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
-let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
-let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
-rsaGenerator.generateKeyPair(function (err, keyPair) {
- globalKeyPair = keyPair;
- let priKey = globalKeyPair.priKey;
- signer.init(priKey, function (err, data) {
- signer.update(input1, function (err, data) {
- signer.sign(input2, function (err, data) {
- SignMessageBlob = data;
- console.info("sign output is " + SignMessageBlob.data);
+function stringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ var tmpArray = new Uint8Array(arr);
+ return tmpArray;
+}
+
+let globalKeyPair;
+let SignMessageBlob;
+let plan1 = "This is Sign test plan1"; // The first segment of the data.
+let plan2 = "This is Sign test plan2"; // The second segment of the data.
+let input1 = { data : stringToUint8Array(plan1) };
+let input2 = { data : stringToUint8Array(plan2) };
+
+function signMessageCallback() {
+ let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
+ let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
+ rsaGenerator.generateKeyPair(function (err, keyPair) {
+ globalKeyPair = keyPair;
+ let priKey = globalKeyPair.priKey;
+ signer.init(priKey, function (err, data) {
+ signer.update(input1, function (err, data) { // Add the first segment of the data.
+ signer.sign(input2, function (err, data) { // Add the second segment of the data, and sign input1 and input2.
+ SignMessageBlob = data;
+ AlertDialog.show({message : "res" + SignMessageBlob.data});
+ });
});
});
});
-});
+}
```
**Promise example**:
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
-let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
-let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
-let keyGenPromise = rsaGenerator.generateKeyPair();
-keyGenPromise.then( keyPair => {
- globalKeyPair = keyPair;
- let priKey = globalKeyPair.priKey;
- return signer.init(priKey);
-}).then(() => {
- return signer.update(input1);
-}).then(() => {
- return signer.sign(input2);
-}).then(dataBlob => {
- SignMessageBlob = dataBlob;
- console.info("sign output is " + SignMessageBlob.data);
-});
+function stringToUint8Array(str) {
+ var arr = [];
+ for (var i = 0, j = str.length; i < j; ++i) {
+ arr.push(str.charCodeAt(i));
+ }
+ var tmpArray = new Uint8Array(arr);
+ return tmpArray;
+}
+
+let globalKeyPair;
+let SignMessageBlob;
+let plan1 = "This is Sign test plan1"; // The first segment of the data.
+let plan2 = "This is Sign test plan2"; // The second segment of the data.
+let input1 = { data : stringToUint8Array(plan1) };
+let input2 = { data : stringToUint8Array(plan2) };
+
+function signMessagePromise() {
+ let rsaGenerator = cryptoFramework.createAsyKeyGenerator("RSA1024|PRIMES_2");
+ let signer = cryptoFramework.createSign("RSA1024|PKCS1|SHA256");
+ let keyGenPromise = rsaGenerator.generateKeyPair();
+ keyGenPromise.then( keyPair => {
+ globalKeyPair = keyPair;
+ let priKey = globalKeyPair.priKey;
+ return signer.init(priKey);
+ }).then(() => {
+ return signer.update(input1); // Add the first segment of the data.
+ }).then(() => {
+ return signer.sign(input2); // Add the second segment of the data, and sign input1 and input2.
+ }).then(dataBlob => {
+ SignMessageBlob = dataBlob;
+ console.info("sign output is " + SignMessageBlob.data);
+ AlertDialog.show({message : "output" + SignMessageBlob.data});
+ });
+}
```
## cryptoFramework.createVerify
@@ -1897,9 +2218,9 @@ Creates a **Verify** instance.
**Return value**
-| Type| Description |
-| ---- | ------------------------------ |
-| Verify | **Verify** instance created.|
+| Type | Description |
+| ------ | ---------------------------------- |
+| Verify | **Verify** instance created.|
**Example**
@@ -1908,11 +2229,27 @@ import cryptoFramework from "@ohos.security.cryptoFramework"
let verifyer1 = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
-let verifyer2 = cryptoFramework.createVerify("RSA1024|PKCS1_OAEP|SHA256|MGF1_SHA256")
+let verifyer2 = cryptoFramework.createVerify("RSA1024|PSS|SHA256|MGF1_SHA256")
```
+
## Verify
Provides APIs for signature verification. Before using any API of the **Verify** class, you must create a **Verify** instance by using **createVerify()**.
+The **Verify** class does not support repeated initialization. When a new key is used for signature verification, you must create a new **Verify** object and call **init()** for initialization.
+The signature verification mode is determined in **createVerify()**, and key is set by **init()**.
+If the data to be verified is short, you can call **verify()** to pass in the signature data and original data after **init()**.
+If the data to be verified is long, you can use **update()** to pass in the data by segment, and then use **verify()** to verify the entire data.
+If **update()** is used to pass in data by segment, **data** of **verify()** can be **null**.
+
+### Attributes
+
+**System capability**: SystemCapability.Security.CryptoFramework
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| algName | string | Yes | No | Algorithm to be used for signature verification.|
+
+
### init
@@ -1924,12 +2261,13 @@ Initializes the **Verify** instance using a public key. This API uses an asynchr
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| pubKey | Key |Yes| Public key used for the initialization.|
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------------------------- |
+| pubKey | PubKey | Yes | Public key used for the initialization.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
### init
+
init(pubKey : PubKey) : Promise\
Initializes the **Verify** instance using a public key. This API uses a promise to return the result.
@@ -1938,14 +2276,14 @@ Initializes the **Verify** instance using a public key. This API uses a promise
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| pubKey | Key |Yes|Public key used for the initialization.|
+| Name| Type| Mandatory| Description |
+| ------ | ---- | ---- | ---------------------------- |
+| pubKey | PubKey | Yes | Public key used for the initialization.|
**Return value**
-| Type | Description |
-| --------------- | ------------ |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
### update
@@ -1958,10 +2296,10 @@ Updates the data for signature verification. This API uses an asynchronous callb
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| data | DataBlob | Yes | Message to pass in. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| -------- | -------------------- | ---- | ---------- |
+| data | DataBlob | Yes | Data to pass in.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
### update
@@ -1975,12 +2313,12 @@ Updates the data for signature verification. This API uses a promise to return t
| Name| Type | Mandatory| Description |
| ------ | -------- | ---- | ---------- |
-| data | DataBlob | Yes | Message to pass in. |
+| data | DataBlob | Yes | Data to pass in.|
**Return value**
-| Type | Description |
-| ------------- | ----------- |
+| Type | Description |
+| -------------- | ----------- |
| Promise\ | Promise used to return the result.|
### verify
@@ -1993,11 +2331,11 @@ Verifies the signature. This API uses an asynchronous callback to return the res
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| data | DataBlob | Yes | Message to pass in. |
-| signatureData | DataBlob | Yes | Signature data. |
-| callback | AsyncCallback\ | Yes | Callback invoked to return the result.|
+| Name | Type | Mandatory| Description |
+| ------------- | -------------------- | ---- | ---------- |
+| data | DataBlob | Yes | Data to pass in.|
+| signatureData | DataBlob | Yes | Signature data. |
+| callback | AsyncCallback\ | Yes | Callback invoked to return the result. |
### verify
@@ -2009,25 +2347,30 @@ Verifies the signature. This API uses a promise to return the result.
**Parameters**
-| Name| Type | Mandatory| Description |
-| ------ | -------- | ---- | ---------- |
-| data | DataBlob | Yes | Message to pass in.|
-| signatureData | DataBlob| Yes| Signature data.|
+| Name | Type | Mandatory| Description |
+| ------------- | -------- | ---- | ---------- |
+| data | DataBlob | Yes | Data to pass in.|
+| signatureData | DataBlob | Yes | Signature data. |
**Return value**
-| Type | Description |
-| --------------- | ------------ |
+| Type | Description |
+| ----------------- | ---------------------------- |
| Promise\ | Promise used to return the result.|
**Callback example**:
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
+let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
+let input1 = null;
+let input2 = null;
+let signMessageBlob = null; // Signed data, which is omitted here.
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA25");
verifyer.init(globalKeyPair.pubKey, function (err, data) {
verifyer.update(input1, function(err, data) {
- verifyer.verify(input2, SignMessageBlob, function(err, data) {
+ verifyer.verify(input2, signMessageBlob, function(err, data) {
console.info("verify result is " + data);
})
});
@@ -2035,19 +2378,25 @@ verifyer.init(globalKeyPair.pubKey, function (err, data) {
```
**Promise example**:
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
+let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let verifyer = cryptoFramework.createVerify("RSA1024|PKCS1|SHA256");
let verifyInitPromise = verifyer.init(globalKeyPair.pubKey);
+let input1 = null;
+let input2 = null;
+let signMessageBlob = null; // Signed data, which is omitted here.
verifyInitPromise.then(() => {
return verifyer.update(input1);
}).then(() => {
- return verifyer.verify(input2, SignMessageBlob);
+ return verifyer.verify(input2, signMessageBlob);
}).then(res => {
console.log("Verify result is " + res);
});
```
+
## cryptoFramework.createKeyAgreement
createKeyAgreement(algName : string) : KeyAgreement
@@ -2058,15 +2407,15 @@ Creates a **KeyAgreement** instance.
**Parameters**
-| Name | Type | Mandatory| Description |
-| ------- | ------ | ---- | ------------------------------------------------------------ |
-| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported. |
+| Name | Type | Mandatory| Description |
+| ------- | ------ | ---- | ------------------------------- |
+| algName | string | Yes | Key agreement algorithm to use. Only ECC is supported.|
**Return value**
-| Type| Description |
-| ---- | ------------------------------ |
-| KeyAgreement | **KeyAgreement** instance created.|
+| Type | Description |
+| ------------ | ---------------------------------------- |
+| KeyAgreement | **KeyAgreement** instance created.|
**Example**
@@ -2079,7 +2428,15 @@ let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
## KeyAgreement
-Provides APIs for key agreement operations. Before using any API of the **keyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**.
+Provides APIs for key agreement operations. Before using any API of the **KeyAgreement** class, you must create a **KeyAgreement** instance by using **createKeyAgreement()**.
+
+### Attributes
+
+**System capability**: SystemCapability.Security.CryptoFramework
+
+| Name | Type | Readable| Writable| Description |
+| ------- | ------ | ---- | ---- | ---------------------------- |
+| algName | string | Yes | No | Algorithm used for key agreement.|
### generateSecret
@@ -2091,13 +2448,14 @@ Generates a shared secret. This API uses an asynchronous callback to return the
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| priKey | PriKey |Yes| Private key used for key agreement.|
-| pubKey | PubKey |Yes| Public key used for key agreement.|
-| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret generated. |
+| Name | Type | Mandatory| Description |
+| -------- | ------------------------ | ---- | ---------------------- |
+| priKey | PriKey | Yes | Private key used for key agreement.|
+| pubKey | PubKey | Yes | Public key used for key agreement.|
+| callback | AsyncCallback\ | Yes | Callback invoked to return the shared secret.|
### generateSecret
+
generateSecret(priKey : PriKey, pubKey : PubKey) : Promise\
Generates a shared secret. This API uses a promise to return the result.
@@ -2106,21 +2464,23 @@ Generates a shared secret. This API uses a promise to return the result.
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------- | ---- | ------------------ |
-| priKey | PriKey |Yes| Private key used for key agreement.|
-| pubKey | PubKey |Yes| Public key used for key agreement.|
+| Name| Type | Mandatory| Description |
+| ------ | ------ | ---- | ---------------------- |
+| priKey | PriKey | Yes | Private key used for key agreement.|
+| pubKey | PubKey | Yes | Public key used for key agreement.|
**Return value**
-| Type | Description |
-| --------------- | ------------ |
-| Promise\ | Promise used to return the shared secret generated. |
+| Type | Description |
+| ------------------ | -------- |
+| Promise\ | Promise used to return the shared secret.|
**Callback example**:
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
+let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function (err, secret) {
if (err) {
@@ -2132,9 +2492,11 @@ keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey, function
```
**Promise example**:
+
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
+let globalKeyPair; // globalKeyPair is an asymmetric key object generated by the asymmetric key generator. The generation process is omitted here.
let keyAgreement = cryptoFramework.createKeyAgreement("ECC256");
let keyAgreementPromise = keyAgreement.generateSecret(globalKeyPair.priKey, globalKeyPair.pubKey);
keyAgreementPromise.then((secret) => {
diff --git a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md
index ccc1f7b4e26c0cbc6556f2ea767c5601ac3a477e..4cdef60fa628733e5be8cc6df783548b7b5bcd07 100644
--- a/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md
+++ b/en/application-dev/reference/apis/js-apis-data-DataShareResultSet.md
@@ -1,4 +1,4 @@
-# @ohos.data.dataShareResultSet
+# @ohos.data.dataShareResultSet (DataShare Result Set)
The **DataShareResultSet** module provides APIs for accessing the result set obtained from the database. You can access the values in the specified rows or the value of the specified data type.
diff --git a/en/application-dev/reference/apis/js-apis-data-ability.md b/en/application-dev/reference/apis/js-apis-data-ability.md
index 779d30c40263eecd1a8ecf70209a95008aa228dd..f41bea4da45a6f6c0224e126f698d45d274e25dc 100644
--- a/en/application-dev/reference/apis/js-apis-data-ability.md
+++ b/en/application-dev/reference/apis/js-apis-data-ability.md
@@ -1,4 +1,4 @@
-# DataAbilityPredicates
+# @ohos.data.dataAbility (DataAbility Predicates)
**DataAbility** provides APIs for creating predicates, which implement different query methods for relational database (RDB) stores.
@@ -23,16 +23,16 @@ Creates an **RdbPredicates** object from a **DataAbilityPredicates** object.
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | name | string | Yes| Name of a database table.|
- | dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. |
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| name | string | Yes| Name of a database table.|
+| dataAbilityPredicates | [DataAbilityPredicates](#dataabilitypredicates) | Yes| **DataAbilityPredicates** object. |
**Return value**
- | Type| Description|
- | -------- | -------- |
- | rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.|
+| Type| Description|
+| -------- | -------- |
+| rdb.[RdbPredicates](js-apis-data-rdb.md#rdbpredicates) | **RdbPredicates** object created.|
**Example**
@@ -56,16 +56,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -83,16 +83,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -110,9 +110,9 @@ Adds a left parenthesis to this **DataAbilityPredicates**.
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a left parenthesis.|
**Example**
@@ -135,9 +135,9 @@ Adds a right parenthesis to this **DataAbilityPredicates**.
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with a right parenthesis.|
**Example**
@@ -160,9 +160,9 @@ Adds the OR condition to this **DataAbilityPredicates**.
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the OR condition.|
**Example**
@@ -182,9 +182,9 @@ Adds the AND condition to this **DataAbilityPredicates**.
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object with the AND condition.|
**Example**
@@ -204,16 +204,16 @@ Sets a **DataAbilityPredicates** object to match a string containing the specifi
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | string | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | string | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -231,16 +231,16 @@ Sets a **DataAbilityPredicates** object to match a string that starts with the s
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | string | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | string | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -258,16 +258,16 @@ Sets a **DataAbilityPredicates** object to match a string that ends with the spe
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | string | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | string | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -285,15 +285,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is null.
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -311,15 +311,15 @@ Sets a **DataAbilityPredicates** object to match the field whose value is not nu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -337,16 +337,16 @@ Sets a **DataAbilityPredicates** object to match a string that is similar to the
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | string | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | string | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -364,16 +364,16 @@ Sets a **DataAbilityPredicates** object to match the specified string.
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | string | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | string | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -391,17 +391,17 @@ Sets a **DataAbilityPredicates** object to match a field whose data type is **Va
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.|
- | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.|
+| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -419,17 +419,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.|
- | high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| low | [ValueType](#valuetype) | Yes| Minimum value to match the **DataAbilityPredicates**.|
+| high | [ValueType](#valuetype) | Yes| Maximum value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -447,16 +447,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -474,16 +474,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -501,16 +501,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -528,16 +528,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type **Valu
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | [ValueType](#valuetype) | Yes| Value to match the **DataAbilityPredicates**.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -555,15 +555,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -581,15 +581,15 @@ Sets a **DataAbilityPredicates** object to match the column with values sorted i
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -607,9 +607,9 @@ Sets a **DataAbilityPredicates** object to filter out duplicate records.
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that can filter out duplicate records.|
**Example**
@@ -627,15 +627,15 @@ Set a **DataAbilityPredicates** object to specify the maximum number of records.
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | value | number | Yes| Maximum number of records.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| value | number | Yes| Maximum number of records.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the maximum number of records.|
**Example**
@@ -653,15 +653,15 @@ Sets a **DataAbilityPredicates** object to specify the start position of the ret
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| rowOffset | number | Yes| Number of rows to offset from the beginning. The value is a positive integer.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the start position of the returned result.|
**Example**
@@ -680,15 +680,15 @@ Sets a **DataAbilityPredicates** object to group rows that have the same value i
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | fields | Array<string> | Yes| Names of columns to group.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| fields | Array<string> | Yes| Names of columns to group.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that groups rows with the same value.|
**Example**
@@ -706,15 +706,15 @@ Sets a **DataAbilityPredicates** object to specify the index column.
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | indexName | string | Yes| Name of the index column.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| indexName | string | Yes| Name of the index column.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that specifies the index column.|
**Example**
@@ -732,17 +732,17 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
@@ -760,16 +760,16 @@ Sets a **DataAbilityPredicates** object to match the field with data type Array\
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | field | string | Yes| Column name in the table.|
- | value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| field | string | Yes| Column name in the table.|
+| value | Array<[ValueType](#valuetype)> | Yes| Array of **ValueType**s to match.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
+| Type| Description|
+| -------- | -------- |
+| [DataAbilityPredicates](#dataabilitypredicates) | **DataAbilityPredicates** object that matches the specified field.|
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-data-dataShare.md b/en/application-dev/reference/apis/js-apis-data-dataShare.md
index 2a476aaf33cc927b8c0ec5c392a083b6b42c8f80..82a333b14b2ea90e92540ee31142ea884c7f2593 100644
--- a/en/application-dev/reference/apis/js-apis-data-dataShare.md
+++ b/en/application-dev/reference/apis/js-apis-data-dataShare.md
@@ -1,4 +1,4 @@
-# @ohos.data.dataShare
+# @ohos.data.dataShare (DataShare)
The **DataShare** module allows an application to manage its own data and share data with other applications on the same device.
diff --git a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md
index 4d2df994d96b7b0986782774e9d531a12750cac7..78d896c54a2f1c1674825ddaff66088634129596 100644
--- a/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md
+++ b/en/application-dev/reference/apis/js-apis-data-dataSharePredicates.md
@@ -1,4 +1,4 @@
-# Data Share Predicates
+# @ohos.data.dataSharePredicates (DataShare Predicates)
You can use **DataSharePredicates** to specify conditions for [updating](js-apis-data-dataShare.md#update), [deleting](js-apis-data-dataShare.md#delete), and [querying](js-apis-data-dataShare.md#query) data when **DataShare** is used to manage data.
@@ -35,7 +35,7 @@ Currently, only the relational database (RDB) and key-value database (KVDB, sche
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
-| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
+| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
@@ -65,7 +65,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
-| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
+| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
@@ -439,8 +439,8 @@ Currently, only the RDB supports this **DataSharePredicates** object.
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ------------------------ |
| field | string | Yes | Column name in the database table. |
-| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.|
-| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.|
+| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.|
+| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.|
**Return value**
@@ -470,8 +470,8 @@ Currently, only the RDB supports this **DataSharePredicates** object.
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ------------------------ |
| field | string | Yes | Column name in the database table. |
-| low | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The lowest value of the range.|
-| high | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | The highest value of the range.|
+| low | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The lowest value of the range.|
+| high | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | The highest value of the range.|
**Return value**
@@ -501,7 +501,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | --------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
-| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
+| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
@@ -531,7 +531,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name| Type | Mandatory| Description |
| ------ | --------------------------------------------------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
-| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
+| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
@@ -561,7 +561,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | --------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
-| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
+| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
@@ -591,7 +591,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | --------- | ---- | ---------------------- |
| field | string | Yes | Column name in the database table. |
-| value | [ValueType](js-apis-data-ValuesBucket.md#valuetype) | Yes | Value to match.|
+| value | [ValueType](js-apis-data-valuesBucket.md#valuetype) | Yes | Value to match.|
**Return value**
@@ -790,7 +790,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | --------------------------------------- |
| field | string | Yes| Column name in the database table. |
-| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.|
+| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.|
**Return value**
@@ -820,7 +820,7 @@ Currently, only the RDB and KVDB (schema) support this **DataSharePredicates** o
| Name | Type | Mandatory| Description |
| ------- | ---------------- | ---- | --------------------------------------- |
| field | string | Yes | Column name in the database table. |
-| value | Array<[ValueType](js-apis-data-ValuesBucket.md#valuetype)> | Yes | Array of the values to match.|
+| value | Array<[ValueType](js-apis-data-valuesBucket.md#valuetype)> | Yes | Array of the values to match.|
**Return value**
diff --git a/en/application-dev/reference/apis/js-apis-data-distributedobject.md b/en/application-dev/reference/apis/js-apis-data-distributedobject.md
index 6f24aa3255f0340e0ad8ef248ae25d62092e0774..dc8bf8258b987e9e4ad2799516ee6aafeb487896 100644
--- a/en/application-dev/reference/apis/js-apis-data-distributedobject.md
+++ b/en/application-dev/reference/apis/js-apis-data-distributedobject.md
@@ -1,4 +1,4 @@
-# Distributed Data Object
+# @ohos.data.distributedDataObject (Distributed Data Object)
The **distributedDataObject** module provides basic data object management, including creating, querying, deleting, modifying, and subscribing to data objects, and distributed data object collaboration for the same application among multiple devices.
@@ -23,9 +23,9 @@ Creates a distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | source | object | Yes| Attribute of the distributed data object to create.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| source | object | Yes| Attribute of the distributed data object to create.|
**Return value**
| Type| Description|
@@ -49,9 +49,9 @@ Creates a random session ID.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Return value**
- | Type| Description|
- | -------- | -------- |
- | string | Session ID created.|
+| Type| Description|
+| -------- | -------- |
+| string | Session ID created.|
**Example**
```js
@@ -97,15 +97,15 @@ Sets a session ID for synchronization. Automatic synchronization is performed fo
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| sessionId | string | No| ID of a distributed data object on a trusted network. To remove a distributed data object from the network, set this parameter to "" or leave it empty.|
**Return value**
- | Type| Description|
- | -------- | -------- |
- | boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. |
+| Type| Description|
+| -------- | -------- |
+| boolean | Returns **true** if the session ID is set successfully;
returns **false** otherwise. |
**Example**
@@ -128,10 +128,10 @@ Subscribes to the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
- | callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| type | string | Yes| Event type to subscribe to. The value is **change**, which indicates data changes.|
+| callback | Callback<{ sessionId: string, fields: Array<string> }> | Yes| Callback used to return the changes of the distributed data object.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.|
**Example**
```js
@@ -157,10 +157,10 @@ Unsubscribes from the changes of this distributed data object.
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
- | callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| type | string | Yes| Event type to unsubscribe from. The value is **change**, which indicates data changes.|
+| callback | Callback<{ sessionId: string, fields: Array<string> }> | No| Callback to be unregistered. If this parameter is not set, all data change callbacks of the object will be unregistered.
**sessionId** indicates the session ID of the distributed data object.
**fields** indicates the changed attributes of the distributed data object.|
**Example**
@@ -182,10 +182,10 @@ Subscribes to the status change (online or offline) of this distributed data obj
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
- | callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| type | string | Yes| Event type to subscribe to. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
+| callback | Callback<{ sessionId: string, networkId: string, status: 'online' \| 'offline' }> | Yes| Callback used to return the status change.
**sessionId**: session ID of the distributed data object.
**networkId**: object device ID, that is, **deviceId**.
**status** indicates the object status, which can be online or offline.|
**Example**
```js
@@ -207,10 +207,10 @@ Unsubscribes from the status change (online or offline) of this distributed data
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
- | callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| type | string | Yes| Event type to unsubscribe from. The value is **status**, which indicates the status change (online or offline) of the distributed data object.|
+| callback | Callback<{ sessionId: string, deviceId: string, status: 'online' \| 'offline' }> | No| Callback used to return the status change. If this parameter is not specified, this API unsubscribes from all callbacks of this distributed data object.
**sessionId**: session ID of the distributed data object.
**deviceId** indicates the device ID of the distributed data object.
**status** indicates the status, which can be online or offline.|
**Example**
@@ -243,10 +243,10 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
- | callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| deviceId | string | Yes| ID of the device where data is stored. The value **local** indicates the local device.|
+| callback | AsyncCallback<[SaveSuccessResponse](#savesuccessresponse9)> | Yes| Callback used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
```js
@@ -279,15 +279,15 @@ The saved data will be released in the following cases:
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| deviceId | string | Yes| ID of the device where the data is saved. The default value is **local**, which indicates the local device. |
**Return value**
- | Type| Description|
- | -------- | -------- |
- | Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
+| Type| Description|
+| -------- | -------- |
+| Promise<[SaveSuccessResponse](#savesuccessresponse9)> | Promise used to return **SaveSuccessResponse**, which contains information such as session ID, version, and device ID.|
**Example**
@@ -317,9 +317,9 @@ If the object is stored on another device, the data on the local device will be
**System capability**: SystemCapability.DistributedDataManager.DataObject.DistributedObject
**Parameters**
- | Name| Type| Mandatory| Description|
- | -------- | -------- | -------- | -------- |
- | callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| callback | AsyncCallback<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | No| Callback used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
@@ -345,9 +345,9 @@ If the object is stored on another device, the data on the local device will be
**Return value**
- | Type| Description|
- | -------- | -------- |
- | Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
+| Type| Description|
+| -------- | -------- |
+| Promise<[RevokeSaveSuccessResponse](#revokesavesuccessresponse9)> | Promise used to return **RevokeSaveSuccessResponse**, which contains the session ID.|
**Example**
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 cad744cb266c3c5712de9d441fe0a56a1fc4ccbc..2b5f66fd6b58e4b29b4fd9201a5bbd9a03a41f34 100644
--- a/en/application-dev/reference/apis/js-apis-data-preferences.md
+++ b/en/application-dev/reference/apis/js-apis-data-preferences.md
@@ -1,4 +1,4 @@
-# Preferences
+# @ohos.data.preferences (Preferences)
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.
@@ -497,7 +497,7 @@ Obtains the value of a key. This API uses a promise to return the result. If the
**System capability**: SystemCapability.DistributedDataManager.Preferences.Core
**Parameters**
-
+
| Name | Type | Mandatory| Description |
| -------- | ----------------------- | ---- | ------------------------------------------------------------ |
| key | string | Yes | Key of the data to obtain. It cannot be empty. |
diff --git a/en/application-dev/reference/apis/js-apis-data-rdb.md b/en/application-dev/reference/apis/js-apis-data-rdb.md
index 89ebac58ef1f970c8c97c00bedb0fe5552491115..bcebd097f34c1337e5826e866302af9626696a32 100644
--- a/en/application-dev/reference/apis/js-apis-data-rdb.md
+++ b/en/application-dev/reference/apis/js-apis-data-rdb.md
@@ -1,4 +1,4 @@
-# @ohos.data.rdb
+# @ohos.data.rdb (RDB)
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.
diff --git a/en/application-dev/reference/apis/js-apis-data-relationalStore.md b/en/application-dev/reference/apis/js-apis-data-relationalStore.md
index 1d3451af2d899c34d1b73f2669c688cac7d6f464..e6b33f3544ead35cb0584365c1c806f02b30ad1f 100644
--- a/en/application-dev/reference/apis/js-apis-data-relationalStore.md
+++ b/en/application-dev/reference/apis/js-apis-data-relationalStore.md
@@ -62,8 +62,8 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
console.info("Failed to get RdbStore, err: " + err)
return
}
- if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
- console.log("RdbStore status is ON_CREATA")
+ if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
+ console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
@@ -97,8 +97,8 @@ data_rdb.getRdbStore(context, STORE_CONFIG, function (err, rdbStore) {
console.info("Failed to get RdbStore, err: " + err)
return
}
- if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
- console.log("RdbStore status is ON_CREATA")
+ if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
+ console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
@@ -154,8 +154,8 @@ const STORE_CONFIG = {
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
- if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
- console.log("RdbStore status is ON_CREATA")
+ if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
+ console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
@@ -188,8 +188,8 @@ const STORE_CONFIG = {
}
let promise = data_rdb.getRdbStore(context, STORE_CONFIG);
promise.then(async (rdbStore) => {
- if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATA) {
- console.log("RdbStore status is ON_CREATA")
+ if (rdbStore.openStatus == data_rdb.OpenStatus.ON_CREATE) {
+ console.log("RdbStore status is ON_CREATE")
} else if (rdbStore.openStatus == data_rdb.OpenStatus.ON_OPEN) {
console.log("RdbStore status is ON_OPEN")
} else {
diff --git a/en/application-dev/reference/apis/js-apis-data-resultset.md b/en/application-dev/reference/apis/js-apis-data-resultset.md
index 798ac7bba0926f47e1bc16eb6b672403bc082fa7..8cdecd1134a270075b3d4dd86a7e4e7a07fc7390 100644
--- a/en/application-dev/reference/apis/js-apis-data-resultset.md
+++ b/en/application-dev/reference/apis/js-apis-data-resultset.md
@@ -1,549 +1,17 @@
-# Result Set
+# resultSet
A result set is a set of results returned after the relational database (RDB) query APIs are called. You can use the **resultset** APIs to obtain required data.
-> **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.
+>
+> The APIs of this module are no longer maintained since API version 9. You are advised to use [@ohos.data.relationalStore#ResultSet](js-apis-data-relationalStore.md#resultset).
-## ResultSetV99+
-
-Provides methods to access the result set, which is obtained by querying the RDB store.
-
-### Usage
-
-You need to obtain the **resultSetV9** instance by using [RdbStoreV9.query()](js-apis-data-rdb.md#query).
-
-```js
-import dataRdb from '@ohos.data.rdb';
-let predicatesV9 = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-predicatesV9.equalTo("AGE", 18);
-let promise = rdbStoreV9.query(predicatesV9, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promise.then((resultSetV9) => {
- console.log(TAG + "resultSet columnNames:" + resultSetV9.columnNames);
- console.log(TAG + "resultSet columnCount:" + resultSetV9.columnCount);
-});
-```
-
-### Attributes9+
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-| Name | Type | Mandatory| Description |
-| ------------ | ------------------- | ---- | -------------------------------- |
-| columnNames | Array<string> | Yes | Names of all columns in the result set. |
-| columnCount | number | Yes | Number of columns in the result set. |
-| rowCount | number | Yes | Number of rows in the result set. |
-| rowIndex | number | Yes | Index of the current row in the result set. |
-| isAtFirstRow | boolean | Yes | Whether the cursor is in the first row of the result set. |
-| isAtLastRow | boolean | Yes | Whether the cursor is in the last row of the result set. |
-| isEnded | boolean | Yes | Whether the cursor is after the last row of the result set.|
-| isStarted | boolean | Yes | Whether the cursor has been moved. |
-| isClosed | boolean | Yes | Whether the result set is closed. |
-
-### getColumnIndex9+
-
-getColumnIndex(columnName: string): number
-
-Obtains the column index based on the column name.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ---------- | ------ | ---- | -------------------------- |
-| columnName | string | Yes | Column name specified.|
-
-**Return value**
-
-| Type | Description |
-| ------ | ------------------ |
-| number | Index of the column obtained.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-resultSetV9.goToFirstRow();
-const id = resultSetV9.getLong(resultSetV9.getColumnIndex("ID"));
-const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME"));
-const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE"));
-const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY"));
- ```
-
-### getColumnName9+
-
-getColumnName(columnIndex: number): string
-
-Obtains the column name based on the column index.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | ------ | ---- | -------------------------- |
-| columnIndex | number | Yes | Column index specified.|
-
-**Return value**
-
-| Type | Description |
-| ------ | ------------------ |
-| string | Column name obtained.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-const id = resultSetV9.getColumnName(0);
-const name = resultSetV9.getColumnName(1);
-const age = resultSetV9.getColumnName(2);
- ```
-
-### goTo9+
-
-goTo(offset:number): boolean
-
-Moves the cursor to the row based on the specified offset.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name| Type | Mandatory| Description |
-| ------ | ------ | ---- | ---------------------------- |
-| offset | number | Yes | Offset relative to the current position.|
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-**Example**
-
- ```js
-let predicatesV9goto = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promisequerygoto = rdbStoreV9.query(predicatesV9goto, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promisequerygoto.then((resultSetV9) => {
- resultSetV9.goTo(1);
- resultSetV9.close();
-}).catch((err) => {
- console.log('query failed');
-});
- ```
-
-### goToRow9+
-
-goToRow(position: number): boolean
-
-Moves the cursor to the specified row in the result set.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| -------- | ------ | ---- | ------------------------ |
-| position | number | Yes | Position to which the cursor is to be moved.|
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-**Example**
-
- ```js
-let predicatesV9gotorow = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promisequerygotorow = rdbStoreV9.query(predicatesV9gotorow, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promisequerygotorow.then((resultSetV9) => {
- resultSetV9.goToRow(5);
- resultSetV9.close();
-}).catch((err) => {
- console.log('query failed');
-});
- ```
-
-### goToFirstRow9+
-
-goToFirstRow(): boolean
-
-
-Moves the cursor to the first row of the result set.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-**Example**
-
- ```js
-let predicatesV9goFirst = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promisequerygoFirst = rdbStoreV9.query(predicatesV9goFirst, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promisequerygoFirst.then((resultSetV9) => {
- resultSetV9.goToFirstRow();
- resultSetV9.close();
-}).catch((err) => {
- console.log('query failed');
-});
- ```
-
-### goToLastRow9+
-
-goToLastRow(): boolean
-
-Moves the cursor to the last row of the result set.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-**Example**
-
- ```js
-let predicatesV9goLast = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promisequerygoLast = rdbStoreV9.query(predicatesV9goLast, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promisequerygoLast.then((resultSetV9) => {
- resultSetV9.goToLastRow();
- resultSetV9.close();
-}).catch((err) => {
- console.log('query failed');
-});
- ```
-
-### goToNextRow9+
-
-goToNextRow(): boolean
-
-Moves the cursor to the next row in the result set.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-**Example**
-
- ```js
-let predicatesV9goNext = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promisequerygoNext = rdbStoreV9.query(predicatesV9goNext, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promisequerygoNext.then((resultSetV9) => {
- resultSetV9.goToNextRow();
- resultSetV9.close();
-}).catch((err) => {
- console.log('query failed');
-});
- ```
-
-### goToPreviousRow9+
-
-goToPreviousRow(): boolean
-
-Moves the cursor to the previous row in the result set.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-**Example**
-
- ```js
-let predicatesV9goPrev = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promisequerygoPrev = rdbStoreV9.query(predicatesV9goPrev, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promisequerygoPrev.then((resultSetV9) => {
- resultSetV9.goToPreviousRow();
- resultSetV9.close();
-}).catch((err) => {
- console.log('query failed');
-});
- ```
-
-### getBlob9+
-
-getBlob(columnIndex: number): Uint8Array
-
-Obtains the value in the specified column in the current row as a byte array.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | ------ | ---- | ----------------------- |
-| columnIndex | number | Yes | Index of the specified column, starting from 0.|
-
-**Return value**
-
-| Type | Description |
-| ---------- | -------------------------------- |
-| Uint8Array | Value in the specified column as a byte array.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-const codes = resultSetV9.getBlob(resultSetV9.getColumnIndex("CODES"));
- ```
-
-### getString9+
-
-getString(columnIndex: number): string
-
-Obtains the value in the specified column in the current row as a string.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | ------ | ---- | ----------------------- |
-| columnIndex | number | Yes | Index of the specified column, starting from 0.|
-
-**Return value**
-
-| Type | Description |
-| ------ | ---------------------------- |
-| string | Value in the specified column as a string.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-const name = resultSetV9.getString(resultSetV9.getColumnIndex("NAME"));
- ```
-
-### getLong9+
-
-getLong(columnIndex: number): number
-
-Obtains the value in the specified column in the current row as a Long.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | ------ | ---- | ----------------------- |
-| columnIndex | number | Yes | Index of the specified column, starting from 0.|
-
-**Return value**
-
-| Type | Description |
-| ------ | -------------------------- |
-| number | Value in the specified column as a Long.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-const age = resultSetV9.getLong(resultSetV9.getColumnIndex("AGE"));
- ```
-
-### getDouble9+
-
-getDouble(columnIndex: number): number
-
-Obtains the value in the specified column in the current row as a double.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | ------ | ---- | ----------------------- |
-| columnIndex | number | Yes | Index of the specified column, starting from 0.|
-
-**Return value**
-
-| Type | Description |
-| ------ | ---------------------------- |
-| number | Value in the specified column as a double.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-const salary = resultSetV9.getDouble(resultSetV9.getColumnIndex("SALARY"));
- ```
-
-### isColumnNull9+
-
-isColumnNull(columnIndex: number): boolean
-
-Checks whether the value in the specified column of the current row is null.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Parameters**
-
-| Name | Type | Mandatory| Description |
-| ----------- | ------ | ---- | ----------------------- |
-| columnIndex | number | Yes | Index of the specified column, starting from 0.|
-
-**Return value**
-
-| Type | Description |
-| ------- | --------------------------------------------------------- |
-| boolean | Returns **true** if the value is null; returns **false** otherwise.|
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800013 | The column value is null or the column type is incompatible. |
-
-**Example**
-
- ```js
-const isColumnNull = resultSetV9.isColumnNull(resultSetV9.getColumnIndex("CODES"));
- ```
-
-### close9+
-
-close(): void
-
-Closes this result set.
-
-**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
-
-**Example**
-
- ```js
-let predicatesV9Close = new dataRdb.RdbPredicatesV9("EMPLOYEE");
-let promiseClose = rdbStoreV9.query(predicatesV9Close, ["ID", "NAME", "AGE", "SALARY", "CODES"]);
-promiseClose.then((resultSetV9) => {
- resultSetV9.close();
-}).catch((err) => {
- console.log('Failed to close the resultset');
-});
- ```
-
-**Error codes**
-
-For details about the error codes, see [RDB Error Codes](../errorcodes/errorcode-data-rdb.md).
-
-| ID| **Error Message** |
-| ------------ | ------------------------------------------------------------ |
-| 14800012 | The result set is empty or the specified location is invalid. |
-
-## ResultSet(deprecated)
+## ResultSet
Provides methods to access the result set, which is obtained by querying the RDB store.
-> **NOTE**
->
-> This object is supported since API version 7 and deprecated since API version 9. You are advised to use [ResultSetV9](#resultsetv99).
-
### Usage
You need to obtain a **resultSet** object by using [RdbStore.query()](js-apis-data-rdb.md#query).
@@ -559,11 +27,7 @@ promise.then((resultSet) => {
});
```
-### Attributes(deprecated)
-
-> **NOTE**
->
-> This parameter is supported since API version 7 and is deprecated since API version 9. You are advised to use [Attributes](#attributes9).
+### Attributes
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
@@ -579,29 +43,25 @@ promise.then((resultSet) => {
| isStarted | boolean | Yes| Whether the cursor has been moved.|
| isClosed | boolean | Yes| Whether the result set is closed.|
-### getColumnIndex(deprecated)
+### getColumnIndex
getColumnIndex(columnName: string): number
Obtains the column index based on the column name.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnIndex](#getcolumnindex9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnName | string | Yes| Column name specified.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnName | string | Yes| Column name specified.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| number | Index of the column obtained.|
+ | Type| Description|
+ | -------- | -------- |
+ | number | Index of the column obtained.|
**Example**
@@ -613,29 +73,25 @@ Obtains the column index based on the column name.
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
```
-### getColumnName(deprecated)
+### getColumnName
getColumnName(columnIndex: number): string
Obtains the column name based on the column index.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getColumnName](#getcolumnname9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnIndex | number | Yes| Column index specified.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnIndex | number | Yes| Column index specified.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| string | Column name obtained.|
+ | Type| Description|
+ | -------- | -------- |
+ | string | Column name obtained.|
**Example**
@@ -645,29 +101,25 @@ Obtains the column name based on the column index.
const age = resultSet.getColumnName(2);
```
-### goTo(deprecated)
+### goTo
goTo(offset:number): boolean
Moves the cursor to the row based on the specified offset.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goTo](#goto9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| offset | number | Yes| Offset relative to the current position.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | offset | number | Yes| Offset relative to the current position.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
@@ -682,29 +134,25 @@ Moves the cursor to the row based on the specified offset.
});
```
-### goToRow(deprecated)
+### goToRow
goToRow(position: number): boolean
Moves the cursor to the specified row in the result set.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToRow](#gotorow9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| position | number | Yes| Position to which the cursor is to be moved.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | position | number | Yes| Position to which the cursor is to be moved.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
@@ -719,23 +167,19 @@ Moves the cursor to the specified row in the result set.
});
```
-### goToFirstRow(deprecated)
+### goToFirstRow
goToFirstRow(): boolean
Moves the cursor to the first row of the result set.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToFirstRow](#gotofirstrow9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
@@ -750,23 +194,19 @@ Moves the cursor to the first row of the result set.
});
```
-### goToLastRow(deprecated)
+### goToLastRow
goToLastRow(): boolean
Moves the cursor to the last row of the result set.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToLastRow](#gotolastrow9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
@@ -781,23 +221,19 @@ Moves the cursor to the last row of the result set.
});
```
-### goToNextRow(deprecated)
+### goToNextRow
goToNextRow(): boolean
Moves the cursor to the next row in the result set.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToNextRow](#gotonextrow9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
@@ -812,23 +248,19 @@ Moves the cursor to the next row in the result set.
});
```
-### goToPreviousRow(deprecated)
+### goToPreviousRow
goToPreviousRow(): boolean
Moves the cursor to the previous row in the result set.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [goToPreviousRow](#gotopreviousrow9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the operation is successful; returns **false** otherwise.|
**Example**
@@ -843,29 +275,25 @@ Moves the cursor to the previous row in the result set.
});
```
-### getBlob(deprecated)
+### getBlob
getBlob(columnIndex: number): Uint8Array
Obtains the value in the specified column in the current row as a byte array.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getBlob](#getblob9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnIndex | number | Yes| Index of the specified column, starting from 0.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnIndex | number | Yes| Index of the specified column, starting from 0.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| Uint8Array | Value in the specified column as a byte array.|
+ | Type| Description|
+ | -------- | -------- |
+ | Uint8Array | Value in the specified column as a byte array.|
**Example**
@@ -873,29 +301,25 @@ Obtains the value in the specified column in the current row as a byte array.
const codes = resultSet.getBlob(resultSet.getColumnIndex("CODES"));
```
-### getString(deprecated)
+### getString
getString(columnIndex: number): string
Obtains the value in the specified column in the current row as a string.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getString](#getstring9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnIndex | number | Yes| Index of the specified column, starting from 0.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnIndex | number | Yes| Index of the specified column, starting from 0.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| string | Value in the specified column as a string.|
+ | Type| Description|
+ | -------- | -------- |
+ | string | Value in the specified column as a string.|
**Example**
@@ -903,29 +327,25 @@ Obtains the value in the specified column in the current row as a string.
const name = resultSet.getString(resultSet.getColumnIndex("NAME"));
```
-### getLong(deprecated)
+### getLong
getLong(columnIndex: number): number
Obtains the value in the specified column in the current row as a Long.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getLong](#getlong9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnIndex | number | Yes| Index of the specified column, starting from 0.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnIndex | number | Yes| Index of the specified column, starting from 0.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| number | Value in the specified column as a Long.|
+ | Type| Description|
+ | -------- | -------- |
+ | number | Value in the specified column as a Long.|
**Example**
@@ -933,29 +353,25 @@ Obtains the value in the specified column in the current row as a Long.
const age = resultSet.getLong(resultSet.getColumnIndex("AGE"));
```
-### getDouble(deprecated)
+### getDouble
getDouble(columnIndex: number): number
Obtains the value in the specified column in the current row as a double.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [getDouble](#getdouble9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnIndex | number | Yes| Index of the specified column, starting from 0.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnIndex | number | Yes| Index of the specified column, starting from 0.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| number | Value in the specified column as a double.|
+ | Type| Description|
+ | -------- | -------- |
+ | number | Value in the specified column as a double.|
**Example**
@@ -963,29 +379,25 @@ Obtains the value in the specified column in the current row as a double.
const salary = resultSet.getDouble(resultSet.getColumnIndex("SALARY"));
```
-### isColumnNull(deprecated)
+### isColumnNull
isColumnNull(columnIndex: number): boolean
Checks whether the value in the specified column of the current row is null.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [isColumnNull](#iscolumnnull9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Parameters**
-| Name| Type| Mandatory| Description|
-| -------- | -------- | -------- | -------- |
-| columnIndex | number | Yes| Index of the specified column, starting from 0.|
+ | Name| Type| Mandatory| Description|
+ | -------- | -------- | -------- | -------- |
+ | columnIndex | number | Yes| Index of the specified column, starting from 0.|
**Return value**
-| Type| Description|
-| -------- | -------- |
-| boolean | Returns **true** if the value is null; returns **false** otherwise.|
+ | Type| Description|
+ | -------- | -------- |
+ | boolean | Returns **true** if the value is null; returns **false** otherwise.|
**Example**
@@ -993,16 +405,12 @@ Checks whether the value in the specified column of the current row is null.
const isColumnNull = resultSet.isColumnNull(resultSet.getColumnIndex("CODES"));
```
-### close(deprecated)
+### close
close(): void
Closes this result set.
-> **NOTE**
->
-> This API is supported since API version 7 and deprecated since API version 9. You are advised to use [close](#close9).
-
**System capability**: SystemCapability.DistributedDataManager.RelationalStore.Core
**Example**
diff --git a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md
index 846f3f15481d700da9d738857bc217c64cbe6ac9..009ff71b091c7d91a92d92364450316e3aeecfa2 100644
--- a/en/application-dev/reference/apis/js-apis-data-valuesBucket.md
+++ b/en/application-dev/reference/apis/js-apis-data-valuesBucket.md
@@ -1,4 +1,4 @@
-# @ohos.data.ValuesBucket
+# @ohos.data.ValuesBucket (Value Bucket)
The **ValueBucket** module holds data in key-value (KV) pairs. You can use it to insert data into a database.
@@ -34,6 +34,6 @@ Defines the types of the key and value in a KV pair.
**System capability**: SystemCapability.DistributedDataManager.DataShare.Core
-| Key Type | Value Type |
-| ------------- | --------------------------------------------- |
-| string | [ValueType](#valuetype)\| Uint8Array \| null |
+| Key Type | Value Type |
+| ------------- | --------------------------------------------- |
+| string | [ValueType](#valuetype)\| Uint8Array \| null |
diff --git a/en/application-dev/reference/apis/js-apis-distributedKVStore.md b/en/application-dev/reference/apis/js-apis-distributedKVStore.md
index 81308054abd5ef5f55ad9d4c78b52f427c16792c..9c3e0e6c94da1406b29e69e27cb68595c2225dd4 100644
--- a/en/application-dev/reference/apis/js-apis-distributedKVStore.md
+++ b/en/application-dev/reference/apis/js-apis-distributedKVStore.md
@@ -1,4 +1,4 @@
-# Distributed KV Store
+# @ohos.data.distributedKVStore (Distributed KV Store)
The **distributedKVStore** module implements collaboration between databases for different devices that forms a Super Device. The APIs provided by this module can be used to save data to a distributed key-value (KV) store and perform operations, such as adding, deleting, modifying, querying, and synchronizing data in distributed KV stores.
@@ -2395,7 +2395,7 @@ Writes data to this single KV store. This API uses an asynchronous callback to r
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------ |
-| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write.|
+| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write.|
| callback | AsyncCallback<void> | Yes | Callback invoked to return the result. |
**Error codes**
@@ -2447,7 +2447,7 @@ Write data to this KV store. This API uses a promise to return the result.
| Name| Type | Mandatory| Description |
| ------ | ------------------------------------------------------------ | ---- | ------------------ |
-| value | Array<[ValuesBucket](js-apis-data-ValuesBucket.md#valuesbucket)> | Yes | Data to write. |
+| value | Array<[ValuesBucket](js-apis-data-valuesBucket.md#valuesbucket)> | Yes | Data to write. |
**Return value**
diff --git a/en/application-dev/reference/apis/js-apis-faultLogger.md b/en/application-dev/reference/apis/js-apis-faultLogger.md
index 6aa752374b38735bc3ace8cac13f7d76708b7e66..2a6c9e6c8670b70ce80b59b6eea5cf5defa98234 100644
--- a/en/application-dev/reference/apis/js-apis-faultLogger.md
+++ b/en/application-dev/reference/apis/js-apis-faultLogger.md
@@ -1,4 +1,4 @@
-# @ohos.faultLogger
+# @ohos.faultLogger (Fault Logger)
The **faultLogger** module implements fault logging functions.
diff --git a/en/application-dev/reference/apis/js-apis-geoLocationManager.md b/en/application-dev/reference/apis/js-apis-geoLocationManager.md
index 778fb02db02c051985c50e9325943ff31a12afc1..e102353bf8b19431fab51151c9c634916fa39ff4 100644
--- a/en/application-dev/reference/apis/js-apis-geoLocationManager.md
+++ b/en/application-dev/reference/apis/js-apis-geoLocationManager.md
@@ -1,4 +1,4 @@
-# @ohos.geoLocationManager
+# @ohos.geoLocationManager (Geolocation Manager)
The **geoLocationManager** module provides location service management functions.
diff --git a/en/application-dev/reference/apis/js-apis-geolocation.md b/en/application-dev/reference/apis/js-apis-geolocation.md
index a5c7034c0333cb640dbe1a51b7f5f6e6f63743ca..86b62bd76ff14cdd0aaa46d60f532b2b52220e4d 100644
--- a/en/application-dev/reference/apis/js-apis-geolocation.md
+++ b/en/application-dev/reference/apis/js-apis-geolocation.md
@@ -1,10 +1,11 @@
-# Geolocation
+# @ohos.geolocation (Geolocation)
-The Geolocation module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing.
+The **geolocation** module provides location services such as GNSS positioning, network positioning, geocoding, reverse geocoding, country code and geofencing.
> **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 provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead.
+>
+> - 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 provided by this module are no longer maintained since API version 9. You are advised to use [geoLocationManager](js-apis-geoLocationManager.md) instead.
## Applying for Permissions
diff --git a/en/application-dev/reference/apis/js-apis-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiappevent.md
index 24125f48cde82856302fc0b981b707c53387d54b..260c8c541809f723cee63a3cf7f7ce9374ff886d 100644
--- a/en/application-dev/reference/apis/js-apis-hiappevent.md
+++ b/en/application-dev/reference/apis/js-apis-hiappevent.md
@@ -1,4 +1,4 @@
-# HiAppEvent
+# @ohos.hiAppEvent (Application Event Logging)
The HiAppEvent module provides the application event logging functions, such as writing application events to the event file and managing the event logging configuration.
diff --git a/en/application-dev/reference/apis/js-apis-hichecker.md b/en/application-dev/reference/apis/js-apis-hichecker.md
index 5d122910002cfc228d009f3468c4b82d21d4e846..3a5687e9ee0b31e29450d72ad7f618a128b30050 100644
--- a/en/application-dev/reference/apis/js-apis-hichecker.md
+++ b/en/application-dev/reference/apis/js-apis-hichecker.md
@@ -1,4 +1,4 @@
-# @ohos.hichecker
+# @ohos.hichecker (HiChecker)
The **hichecker** module is provided for you to check issues that may be easily ignored during development of OpenHarmony applications (including system-built and third-party applications). Such issues include calling of time-consuming functions by key application threads, event distribution and execution timeout in application processes, and ability resource leakage in application processes. The issues are recorded in logs or lead to process crashes explicitly so that you can find and rectify them.
diff --git a/en/application-dev/reference/apis/js-apis-hidebug.md b/en/application-dev/reference/apis/js-apis-hidebug.md
index 3bab9f0be3145354d784d3b3a89cf7054037dcf8..189d855e894451790976eee2c3816cf17ae950b9 100644
--- a/en/application-dev/reference/apis/js-apis-hidebug.md
+++ b/en/application-dev/reference/apis/js-apis-hidebug.md
@@ -1,4 +1,4 @@
-# @ohos.hidebug
+# @ohos.hidebug (HiDebug)
The **hidebug** module provides APIs for you to obtain the memory usage of an application, including the static heap memory (native heap) and proportional set size (PSS) occupied by the application process. You can also export VM memory slices and collect VM CPU profiling data.
diff --git a/en/application-dev/reference/apis/js-apis-hilog.md b/en/application-dev/reference/apis/js-apis-hilog.md
index 01dbef8ce6e24f53485c8b0a780bf1872c5e7963..54355b12b723cf9cad06f5a4064568d5d772bea5 100644
--- a/en/application-dev/reference/apis/js-apis-hilog.md
+++ b/en/application-dev/reference/apis/js-apis-hilog.md
@@ -1,4 +1,4 @@
-# @ohos.hilog
+# @ohos.hilog (HiLog)
The **hilog** module allows your applications or services to output logs based on the specified type, level, and format string. Such logs help you learn the running status of applications and better debug programs.
diff --git a/en/application-dev/reference/apis/js-apis-hitracechain.md b/en/application-dev/reference/apis/js-apis-hitracechain.md
index 17f888aca89c40458c7de2ba1344beb48b0d1286..b72b026ce908bbde85e385f46212d32e4a7fd61b 100644
--- a/en/application-dev/reference/apis/js-apis-hitracechain.md
+++ b/en/application-dev/reference/apis/js-apis-hitracechain.md
@@ -1,4 +1,4 @@
-# @ohos.hiTraceChain (Distributed Call Chain Tracing)
+# @ohos.hiTraceChain (Distributed Call Chain Tracing)
The **hiTraceChain** module implements call chain tracing throughout a service process. It provides functions such as starting and stopping call chain tracing and configuring trace points.
diff --git a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md
index 9179b9a2f079e3bf719c71827fa820ac35e0b61c..86e09db17bda0e6efa68bbeeb973a26f4a4ff467 100644
--- a/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md
+++ b/en/application-dev/reference/apis/js-apis-hiviewdfx-hiappevent.md
@@ -1,4 +1,4 @@
-# @ohos.hiviewdfx.hiAppEvent
+# @ohos.hiviewdfx.hiAppEvent (Application Event Logging)
The **hiAppEvent** module provides application event-related functions, including flushing application events to a disk, querying and clearing application events, and customizing application event logging configuration.
diff --git a/en/application-dev/reference/apis/js-apis-inputconsumer.md b/en/application-dev/reference/apis/js-apis-inputconsumer.md
index c2d5a421c87595094308e70c3bf317c8572b37bf..4de59dd1322f1cc83203ad38bc63746c81d56e8a 100644
--- a/en/application-dev/reference/apis/js-apis-inputconsumer.md
+++ b/en/application-dev/reference/apis/js-apis-inputconsumer.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.inputConsumer
+# @ohos.multimodalInput.inputConsumer (Input Consumer)
The **inputConsumer** module implements listening for combination key events.
diff --git a/en/application-dev/reference/apis/js-apis-inputdevice.md b/en/application-dev/reference/apis/js-apis-inputdevice.md
index 2f286827a664af0d8dff2e7c8d133ca97f5e0ab7..c131d9bbd3e50790624d4eca0ea41c94d7022dd2 100644
--- a/en/application-dev/reference/apis/js-apis-inputdevice.md
+++ b/en/application-dev/reference/apis/js-apis-inputdevice.md
@@ -1,16 +1,12 @@
-# @ohos.multimodalInput.inputDevice
-
+# @ohos.multimodalInput.inputDevice (Input Device)
The **inputDevice** module implements listening for connection, disconnection, and update events of input devices and displays information about input devices. For example, it can be used to listen for mouse insertion and removal and obtain information such as the ID, name, and pointer speed of the mouse.
-
> **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.
-
## Modules to Import
-
```js
import inputDevice from '@ohos.multimodalInput.inputDevice';
```
diff --git a/en/application-dev/reference/apis/js-apis-inputevent.md b/en/application-dev/reference/apis/js-apis-inputevent.md
index f7eec22c115ee6e23263fce286973a3832efc3d5..d2d55fa57ee6bd71288d03aa3f42e24bebb80bea 100644
--- a/en/application-dev/reference/apis/js-apis-inputevent.md
+++ b/en/application-dev/reference/apis/js-apis-inputevent.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.inputEvent
+# @ohos.multimodalInput.inputEvent (Input Event)
The **inputEvent** module describes basic events reported by an input device.
diff --git a/en/application-dev/reference/apis/js-apis-inputeventclient.md b/en/application-dev/reference/apis/js-apis-inputeventclient.md
index dbd66538a80290886a1f1cc86ed6b6daea679b41..354f10e3802d163343b658bef56ab4e03689d2c3 100644
--- a/en/application-dev/reference/apis/js-apis-inputeventclient.md
+++ b/en/application-dev/reference/apis/js-apis-inputeventclient.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.inputEventClient (Key Injection)
+# @ohos.multimodalInput.inputEventClient (Key Event Injection)
The **inputEventClient** module implements injection of key events.
diff --git a/en/application-dev/reference/apis/js-apis-inputmonitor.md b/en/application-dev/reference/apis/js-apis-inputmonitor.md
index 7bd41f5d0be2922df090f71651b1c4a15aafecb1..304fa76946de0e4279be5095bd1dae46f79c7ca6 100644
--- a/en/application-dev/reference/apis/js-apis-inputmonitor.md
+++ b/en/application-dev/reference/apis/js-apis-inputmonitor.md
@@ -1,11 +1,10 @@
-# Input Monitor
+# @ohos.multimodalInput.inputMonitor (Input Monitor)
-The Input Monitor module implements listening for events of input devices (namely, touchscreen and mouse).
+The **inputMonitor** module implements listening for events of input devices (namely, touchscreen and mouse).
> **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 provided by this module are system APIs.
diff --git a/en/application-dev/reference/apis/js-apis-keycode.md b/en/application-dev/reference/apis/js-apis-keycode.md
index 6f5ff70edc6cdcbb7fcc3a5ce90432eaaf6b312c..e69775942629948eab964f4f91795ddfe7dfeda7 100644
--- a/en/application-dev/reference/apis/js-apis-keycode.md
+++ b/en/application-dev/reference/apis/js-apis-keycode.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.keyCode
+# @ohos.multimodalInput.keyCode (Key Code)
The **keyCode** module provides keycodes for a key device.
diff --git a/en/application-dev/reference/apis/js-apis-keyevent.md b/en/application-dev/reference/apis/js-apis-keyevent.md
index 6d65e9bfe403d380d354b8cefa981204a4102a46..32c18a558572b8f971b8faf6277c3300e86f9649 100644
--- a/en/application-dev/reference/apis/js-apis-keyevent.md
+++ b/en/application-dev/reference/apis/js-apis-keyevent.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.keyEvent
+# @ohos.multimodalInput.keyEvent (Key Event)
The **keyEvent** module provides key events reported by an input device.
diff --git a/en/application-dev/reference/apis/js-apis-mouseevent.md b/en/application-dev/reference/apis/js-apis-mouseevent.md
index 81403eff20f8dd8c21d0b7b30bf0989c146de455..92935d6f31e788eb0b71ec6529fbc94264e3d8d1 100644
--- a/en/application-dev/reference/apis/js-apis-mouseevent.md
+++ b/en/application-dev/reference/apis/js-apis-mouseevent.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.mouseEvent
+# @ohos.multimodalInput.mouseEvent (Mouse Event)
The **mouseEvent** module provides mouse events reported by an input device.
diff --git a/en/application-dev/reference/apis/js-apis-net-connection.md b/en/application-dev/reference/apis/js-apis-net-connection.md
index 5df384d16ab9e802971b36cc2527ab36538f143f..d5a5f1585a5ae153694833b611861cc49325c4e7 100644
--- a/en/application-dev/reference/apis/js-apis-net-connection.md
+++ b/en/application-dev/reference/apis/js-apis-net-connection.md
@@ -1,4 +1,4 @@
-# # @ohos.net.connection
+# @ohos.net.connection (Network Connection Management)
The **connection** module provides basic network management capabilities. You can obtain the default active data network or the list of all active data networks, enable or disable the airplane mode, and obtain network capability information.
diff --git a/en/application-dev/reference/apis/js-apis-net-ethernet.md b/en/application-dev/reference/apis/js-apis-net-ethernet.md
index 924d8157a82c8125506cf3a995c1d934cce2c7cc..d41845ec1859507bb96a071dff2a57e16f4cf12b 100644
--- a/en/application-dev/reference/apis/js-apis-net-ethernet.md
+++ b/en/application-dev/reference/apis/js-apis-net-ethernet.md
@@ -1,4 +1,4 @@
-# @ohos.net.ethernet
+# @ohos.net.ethernet (Ethernet Connection Management)
The **ethernet** module provides wired network capabilities, which allow users to set the IP address, subnet mask, gateway, and Domain Name System (DNS) server of a wired network.
diff --git a/en/application-dev/reference/apis/js-apis-net-sharing.md b/en/application-dev/reference/apis/js-apis-net-sharing.md
index a688bf46448c6371ba5c0bd2e740ed276c0bbe20..144ffa9c6e2d405c83e7cf14fdb7278c616759d3 100644
--- a/en/application-dev/reference/apis/js-apis-net-sharing.md
+++ b/en/application-dev/reference/apis/js-apis-net-sharing.md
@@ -1,4 +1,4 @@
-# @ohos.net.sharing
+# @ohos.net.sharing (Network Sharing)
The **sharing** module allows you to share your device's Internet connection with other connected devices by means of Wi-Fi hotspot, Bluetooth, and USB sharing. It also allows you to query the network sharing state and shared mobile data volume.
diff --git a/en/application-dev/reference/apis/js-apis-observer.md b/en/application-dev/reference/apis/js-apis-observer.md
index ad7d19b4ab7a3cfa6593c81f2c70b52f403aa4d1..ae5b7999bd7e579179920a73fcaea6116890ff70 100644
--- a/en/application-dev/reference/apis/js-apis-observer.md
+++ b/en/application-dev/reference/apis/js-apis-observer.md
@@ -1,6 +1,6 @@
-# Observer
+# @ohos.telephony.observer (Observer)
-The observer module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change.
+The **observer** module provides event subscription management functions. You can register or unregister an observer that listens for the following events: network status change, signal status change, call status change, cellular data connection status, uplink and downlink data flow status of cellular data services, and SIM status change.
>**NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-pointer.md b/en/application-dev/reference/apis/js-apis-pointer.md
index c6888254790880a4e310564f5d9faccc00d2778c..fc74447111636244fb54e604dba5c458a6e6e061 100644
--- a/en/application-dev/reference/apis/js-apis-pointer.md
+++ b/en/application-dev/reference/apis/js-apis-pointer.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.pointer
+# @ohos.multimodalInput.pointer (Mouse Pointer)
The **pointer** module provides APIs related to pointer attribute management.
@@ -121,9 +121,13 @@ Checks the visible status of the mouse pointer. This API uses a promise to retur
**Example**
```js
-pointer.isPointerVisible().then((visible) => {
- console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`);
-});
+try {
+ pointer.isPointerVisible().then((visible) => {
+ console.log(`Get pointer visible success, visible: ${JSON.stringify(visible)}`);
+ });
+} catch (error) {
+ console.log(`Get pointer visible failed, error: ${JSON.stringify(error, [`code`, `message`])}`);
+}
```
## pointer.setPointerSpeed9+
diff --git a/en/application-dev/reference/apis/js-apis-power.md b/en/application-dev/reference/apis/js-apis-power.md
index f1a94349e34b8892fe0d96cebc25b5485514e92a..4dc07d44197a78f01cb3e9018293cc1da88bea38 100644
--- a/en/application-dev/reference/apis/js-apis-power.md
+++ b/en/application-dev/reference/apis/js-apis-power.md
@@ -1,4 +1,4 @@
-# @ohos.power
+# @ohos.power (System Power Management)
The **power** module provides APIs for rebooting and shutting down the system, as well as querying the screen status.
diff --git a/en/application-dev/reference/apis/js-apis-privacyManager.md b/en/application-dev/reference/apis/js-apis-privacyManager.md
index cf518ed93a2aea668985ae96031b12d48e284811..4d7ffb05e886f6b908a771b091f83983452bcfed 100644
--- a/en/application-dev/reference/apis/js-apis-privacyManager.md
+++ b/en/application-dev/reference/apis/js-apis-privacyManager.md
@@ -1,4 +1,4 @@
-# Privacy Management
+# @ohos.privacyManager (Privacy Management)
The **privacyManager** module provides APIs for privacy management, such as management of permission usage records.
diff --git a/en/application-dev/reference/apis/js-apis-radio.md b/en/application-dev/reference/apis/js-apis-radio.md
index 91c6be9cd7d076dbb72a502e64363d729668972f..dfb1dd75061b1bb272170b5dbd7c202d320ce304 100644
--- a/en/application-dev/reference/apis/js-apis-radio.md
+++ b/en/application-dev/reference/apis/js-apis-radio.md
@@ -1,6 +1,6 @@
-# Radio
+# @ohos.telephony.radio (Network Search)
-The radio module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card.
+The **radio** module provides basic network search management functions. You can obtain the radio access technology (RAT) used in the CS and PS domains, network status, current network selection mode, ISO country code of the registered network, ID of the slot in which the primary card is located, list of signal strengths of the registered network, carrier name, and IMEI, MEID, and unique device ID of the SIM card in the specified slot. Besides, you can check whether the current device supports 5G\(NR\) and whether the radio service is enabled on the primary SIM card.
>**NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-resource-manager.md b/en/application-dev/reference/apis/js-apis-resource-manager.md
index 5d215b54b33730d147c72c7e1e5981710640c543..7dc343709c19421175b4f99e6308c1c0ad90e5dd 100644
--- a/en/application-dev/reference/apis/js-apis-resource-manager.md
+++ b/en/application-dev/reference/apis/js-apis-resource-manager.md
@@ -1,4 +1,4 @@
-# Resource Manager
+# @ohos.resourceManager (Resource Manager)
The Resource Manager module provides APIs to obtain information about application resources based on the current configuration, including the language, region, screen direction, MCC/MNC, as well as device capability and density.
diff --git a/en/application-dev/reference/apis/js-apis-rpc.md b/en/application-dev/reference/apis/js-apis-rpc.md
index 94757432a9c16fa471fb98629b63387594542e65..8fc776d5508dccfd04155a3952936743de8e711c 100644
--- a/en/application-dev/reference/apis/js-apis-rpc.md
+++ b/en/application-dev/reference/apis/js-apis-rpc.md
@@ -1,6 +1,6 @@
-# @ohos.rpc
+# @ohos.rpc (RPC)
-The **RPC** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver.
+The **rpc** module implements communication between processes, including inter-process communication (IPC) on a single device and remote procedure call (RPC) between processes on difference devices. IPC is implemented based on the Binder driver, and RPC is based on the DSoftBus driver.
> **NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-runninglock.md b/en/application-dev/reference/apis/js-apis-runninglock.md
index 29f70bf59b848b54f23451a8fd34373d4d28db5e..ee70e09ca874602bf8e41f3d4001b61caa5a0344 100644
--- a/en/application-dev/reference/apis/js-apis-runninglock.md
+++ b/en/application-dev/reference/apis/js-apis-runninglock.md
@@ -1,4 +1,4 @@
-# @ohos.runningLock
+# @ohos.runningLock (Runninglock)
The **runningLock** module provides APIs for creating, querying, holding, and releasing running locks.
diff --git a/en/application-dev/reference/apis/js-apis-screen-lock.md b/en/application-dev/reference/apis/js-apis-screen-lock.md
index 9dcef8737df6eec61080fdbc7569ed7d4eb4a238..c726ec7c8fdd4cd6f16d71f5a6892bc565b66cf6 100644
--- a/en/application-dev/reference/apis/js-apis-screen-lock.md
+++ b/en/application-dev/reference/apis/js-apis-screen-lock.md
@@ -1,4 +1,4 @@
-# @ohos.screenLock
+# @ohos.screenLock (Screenlock)
The **screenlock** module is a system module in OpenHarmony. It provides APIs for screen lock applications to subscribe to screen lock status changes as well as callbacks for them to receive the results. It also provides APIs for third-party applications to unlock the screen, obtain the screen locked status, and check whether a lock screen password has been set.
diff --git a/en/application-dev/reference/apis/js-apis-screen.md b/en/application-dev/reference/apis/js-apis-screen.md
index 0f5d909e9b038c65bcd353afae633495a9bd2c4b..e9022ac7d23c3f213487da532d92a369c17a5c48 100644
--- a/en/application-dev/reference/apis/js-apis-screen.md
+++ b/en/application-dev/reference/apis/js-apis-screen.md
@@ -1,6 +1,6 @@
-# Screen
+# @ohos.screen (Screen)
-The **Screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens.
+The **screen** module implements basic screen management. You can use the APIs of this module to obtain a **Screen** object, listen for screen changes, and create and destroy virtual screens.
> **NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-sim.md b/en/application-dev/reference/apis/js-apis-sim.md
index 81c05044174b46f17b6d5224f923167256290e4f..eb88ca8c05459fca0ba2ecd4dfcab60d49677aae 100644
--- a/en/application-dev/reference/apis/js-apis-sim.md
+++ b/en/application-dev/reference/apis/js-apis-sim.md
@@ -1,6 +1,6 @@
-# SIM Management
+# @ohos.telephony.sim (SIM Management)
-The SIM management module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card.
+The **sim** module provides basic SIM card management functions. You can obtain the name, number, ISO country code, home PLMN number, service provider name, SIM card status, type, installation status, activation status, and lock status of the SIM card in the specified slot. Besides, you can set the name, number, and lock status of the SIM card, activate or deactivate the SIM card, and change the PIN or unlock the PIN or PUK of the SIM card.
>**NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-sms.md b/en/application-dev/reference/apis/js-apis-sms.md
index c26311312c5cc2360ddf4f3784f66bba05b0f5b1..901e3b258b7aa73530935baa81a6366f7aa50e65 100644
--- a/en/application-dev/reference/apis/js-apis-sms.md
+++ b/en/application-dev/reference/apis/js-apis-sms.md
@@ -1,6 +1,6 @@
-# SMS
+# @ohos.telephony.sms (SMS)
-The SMS module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages.
+The **sms** module provides basic SMS management functions. You can create and send SMS messages, and obtain and set the default SIM card for sending and receiving SMS messages. Besides, you can obtain and set the SMSC address, and check whether the current device can send and receive SMS messages.
>**NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-socket.md b/en/application-dev/reference/apis/js-apis-socket.md
index 989cc9985727b1e43c828f354f76a3be8dae492f..bd14137464ce195f5c61b9d6a53ce6ef79cd3f10 100644
--- a/en/application-dev/reference/apis/js-apis-socket.md
+++ b/en/application-dev/reference/apis/js-apis-socket.md
@@ -1,4 +1,4 @@
-# @ohos.net.socket
+# @ohos.net.socket (Socket Connection)
The **socket** module implements socket connection management and operation.
diff --git a/en/application-dev/reference/apis/js-apis-storage-statistics.md b/en/application-dev/reference/apis/js-apis-storage-statistics.md
index 86675315d63423d728d2db90afd6b049614ee80a..c54d9d4b01fec93df43f92f47eab8aaae951fb4e 100644
--- a/en/application-dev/reference/apis/js-apis-storage-statistics.md
+++ b/en/application-dev/reference/apis/js-apis-storage-statistics.md
@@ -1,4 +1,4 @@
-# App Storage Statistics
+# @ohos.storageStatistics (App Storage Statistics)
The **storageStatistics** module provides APIs for obtaining storage space information, including the space of built-in and plug-in memory cards, space occupied by different types of data, and space of application data.
diff --git a/en/application-dev/reference/apis/js-apis-system-battery.md b/en/application-dev/reference/apis/js-apis-system-battery.md
index 31959da80f23b90f54ea10883417eec202152d1a..d673a500027654075ff330c916cd22add25abaf6 100644
--- a/en/application-dev/reference/apis/js-apis-system-battery.md
+++ b/en/application-dev/reference/apis/js-apis-system-battery.md
@@ -1,6 +1,6 @@
-# Battery Info
+# @system.battery (Battery Information)
-This module allows you to query the charging status and remaining power of a device.
+The **battery** module allows you to query the charging status and remaining power of a device.
> **NOTE**
> - The APIs of this module are no longer maintained since API version 6. It is recommended that you use [`@ohos.batteryInfo`](js-apis-battery-info.md) instead.
diff --git a/en/application-dev/reference/apis/js-apis-system-brightness.md b/en/application-dev/reference/apis/js-apis-system-brightness.md
index 2773c74397046c44784b65cc458be75eef8c21ea..939e7d7021bc8f93ad7359004de58f525feeee05 100644
--- a/en/application-dev/reference/apis/js-apis-system-brightness.md
+++ b/en/application-dev/reference/apis/js-apis-system-brightness.md
@@ -1,6 +1,6 @@
-# Screen Brightness
+# @system.brightness (Screen Brightness)
-This module provides APIs for querying and adjusting the screen brightness and mode.
+The **brightness** module provides APIs for querying and adjusting the screen brightness and mode.
> **NOTE**
> - The APIs of this module are no longer maintained since API version 7. It is recommended that you use [`@ohos.brightness`](js-apis-brightness.md) instead.
diff --git a/en/application-dev/reference/apis/js-apis-system-capability.md b/en/application-dev/reference/apis/js-apis-system-capability.md
new file mode 100644
index 0000000000000000000000000000000000000000..7949bae9880af5a8e428e62440595a4a6e990da7
--- /dev/null
+++ b/en/application-dev/reference/apis/js-apis-system-capability.md
@@ -0,0 +1,79 @@
+# @ohos.systemCapability (SystemCapability)
+
+System capability (SysCap) refers to a relatively independent feature in the operating system. Different devices provide different system capabilities, and multiple APIs implement a system capability. You can determine whether an API can be used based on system capabilities. This module provides APIs for querying the set of system capabilities.
+
+> **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.
+> - The APIs provided by this module are system APIs.
+
+
+## Modules to Import
+
+```ts
+import systemcapability from '@ohos.systemCapability'
+```
+
+## systemcapability.querySystemCapabilities
+
+querySystemCapabilities(callback: AsyncCallback): void;
+
+Queries system capabilities. This API uses an asynchronous callback to return the result.
+
+**System capability**: SystemCapability.Developtools.Syscap
+
+**Parameters**
+
+| Name| Type| Mandatory| Description|
+| -------- | -------- | -------- | -------- |
+| callback | AsyncCallback | Yes| Callback invoked to return the result.|
+
+
+**Example**
+
+```ts
+try {
+ systemcapability.querySystemCapabilities(function (err, data) {
+ if (err == undefined) {
+ console.log("get system capabilities:" + data)
+ } else {
+ console.log(" get system capabilities err:" + err.code)
+ }});
+}catch(e){
+ console.log("get unexpected error: " + e);
+}
+```
+
+
+## systemcapability.querySystemCapabilities
+
+querySystemCapabilities(): Promise<string>
+
+Queries system capabilities. This API uses a promise to return the result.
+
+**System capability**: SystemCapability.Startup.SystemInfo
+
+**Return value**
+
+| Type| Description|
+| -------- | -------- |
+| Promise<string> | Promise used to return the result.|
+
+**Example**
+
+```ts
+try {
+ var p = systemcapability.querySystemCapabilities();
+ p.then(function (value) {
+ console.log("get system capabilities: " + value);
+ }).catch(function (err) {
+ console.log("get system capabilities error: " + err.code);
+ });
+}catch(e){
+ console.log("get unexpected error: " + e);
+}
+```
+
+
+> **NOTE**
+> - The system capabilities returned by the preceding APIs are in the form of an encoded numeric string.
diff --git a/en/application-dev/reference/apis/js-apis-system-cipher.md b/en/application-dev/reference/apis/js-apis-system-cipher.md
index 6812d87828d55851d375eadba9dab6b2de55560a..dddb6a685f00a8a5a1829e489d43af4a198bdffa 100644
--- a/en/application-dev/reference/apis/js-apis-system-cipher.md
+++ b/en/application-dev/reference/apis/js-apis-system-cipher.md
@@ -1,6 +1,6 @@
-# Encryption Algorithm
+# @system.cipher (Cipher Algorithm)
-> **NOTE**
+> **NOTE**
>
> The initial APIs of this module are supported since API version 3. Newly added APIs will be marked with a superscript to indicate their earliest API version.
@@ -31,7 +31,7 @@ Defines the input parameters of **cipher.rsa()**.
| Name | Type | Mandatory| Description |
| -------------- | ------------------------------------ | ---- | ------------------------------------------------------------ |
| action | string | Yes | Action to perform. The options are as follows:
1. **encrypt**: Encrypts data.
2. **decrypt**: Decrypts data.|
-| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length. For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding.|
+| text | string | Yes | Text to be encrypted or decrypted.
The text to be encrypted must be a common text and cannot exceed the length calculated based on the formula (keySize/8 - 66). **keySize** indicates the key length.
For example, if the key length is 1024 bytes, the text cannot exceed 62 bytes (1024/8 - 66 = 62). The text to be decrypted must be a binary value encoded in Base64. The default format is used for Base64 encoding. |
| key | string | Yes | RSA key. It is a public key in encryption and a private key in decryption. |
| transformation | string | No | RSA padding. The default value is **RSA/None/OAEPWithSHA256AndMGF1Padding**.|
| success | (data: [CipherResponse](#cipherresponse)) => void | No | Called when data is encrypted or decrypted successfully. |
diff --git a/en/application-dev/reference/apis/js-apis-telephony-data.md b/en/application-dev/reference/apis/js-apis-telephony-data.md
index e9b54c774d2bc1e43de0dd7edb55e47bcf9c3b57..f1c9ad362175bd709d27bc4c7aec0059b413221e 100644
--- a/en/application-dev/reference/apis/js-apis-telephony-data.md
+++ b/en/application-dev/reference/apis/js-apis-telephony-data.md
@@ -1,6 +1,6 @@
-# Cellular Data
+# @ohos.telephony.data (Cellular Data)
-The cellular data module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled.
+The **data** module provides basic mobile data management functions. You can obtain and set the default slot of the SIM card used for mobile data, and obtain the uplink and downlink connection status of cellular data services and connection status of the packet switched (PS) domain. Besides, you can check whether cellular data services and data roaming are enabled.
>**NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-thermal.md b/en/application-dev/reference/apis/js-apis-thermal.md
index a8e25a0149aa8d6257363db0321a563cfaa81eb6..514e7062cd649d8bf5b92261bceeb7cbed870166 100644
--- a/en/application-dev/reference/apis/js-apis-thermal.md
+++ b/en/application-dev/reference/apis/js-apis-thermal.md
@@ -1,4 +1,4 @@
-# @ohos.thermal
+# @ohos.thermal (Thermal Management)
The **thermal** module provides thermal level-related callback and query APIs to obtain the information required for thermal control.
diff --git a/en/application-dev/reference/apis/js-apis-touchevent.md b/en/application-dev/reference/apis/js-apis-touchevent.md
index 54b4eb2aa3aa9922867abb82cb11737995751a81..ae49b428e00c4c22ed126ecc539290a692b69696 100644
--- a/en/application-dev/reference/apis/js-apis-touchevent.md
+++ b/en/application-dev/reference/apis/js-apis-touchevent.md
@@ -1,4 +1,4 @@
-# @ohos.multimodalInput.touchEvent
+# @ohos.multimodalInput.touchEvent (Touch Event)
The **touchEvent** module provides touch events reported by an input device.
diff --git a/en/application-dev/reference/apis/js-apis-update.md b/en/application-dev/reference/apis/js-apis-update.md
index 412623cd7bf7d9a8fb55a17499bea8327d84f91a..ffb07ba4f21cc5f154bcf25062f86845c97577dc 100644
--- a/en/application-dev/reference/apis/js-apis-update.md
+++ b/en/application-dev/reference/apis/js-apis-update.md
@@ -1,4 +1,4 @@
-# @ohos.update
+# @ohos.update (Update)
The **update** module applies to updates throughout the entire system, including built-in resources and preset applications, but not third-party applications.
diff --git a/en/application-dev/reference/apis/js-apis-usb-deprecated.md b/en/application-dev/reference/apis/js-apis-usb-deprecated.md
index b3be9875df2554c6df5b8c358c9243d734d87874..68a127a08bdfd1df0ca558866dc3cde577e2b25a 100644
--- a/en/application-dev/reference/apis/js-apis-usb-deprecated.md
+++ b/en/application-dev/reference/apis/js-apis-usb-deprecated.md
@@ -1,8 +1,8 @@
-# USB
+# @ohos.usb (USB Management)
-The USB module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control.
+The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control.
-> **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.
diff --git a/en/application-dev/reference/apis/js-apis-usb.md b/en/application-dev/reference/apis/js-apis-usb.md
index db5f65e888e6b40a07362bc74a8c2375d6bf22f2..9035d2d040209f44a019fb69b3da6edc49b481b3 100644
--- a/en/application-dev/reference/apis/js-apis-usb.md
+++ b/en/application-dev/reference/apis/js-apis-usb.md
@@ -1,4 +1,4 @@
-# @ohos.usbV9
+# @ohos.usbV9 (USB Management)
The **usb** module provides USB device management functions, including USB device list query, bulk data transfer, control transfer, and permission control on the host side as well as port management, and function switch and query on the device side.
diff --git a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md
index 9a45d1fe8f9644f0072fdfdb44c31f66c19e3d59..7005776c804fa21fe899f82d29253c2436b4f5ea 100644
--- a/en/application-dev/reference/apis/js-apis-useriam-faceauth.md
+++ b/en/application-dev/reference/apis/js-apis-useriam-faceauth.md
@@ -1,4 +1,4 @@
-# Facial Authentication
+# @ohos.userIAM.faceAuth (Facial Authentication)
The **userIAM.faceAuth** module provides APIs for face enrollment.
@@ -34,17 +34,17 @@ A constructor used to create a **FaceAuthManager** object.
**Example**
- ```js
- import userIAM_faceAuth from '@ohos.userIAM.faceAuth';
+```js
+import userIAM_faceAuth from '@ohos.userIAM.faceAuth';
- let faceAuthManager = new userIAM_faceAuth.FaceAuthManager();
- ```
+let faceAuthManager = new userIAM_faceAuth.FaceAuthManager();
+```
### setSurfaceId
setSurfaceId(surfaceId: string): void;
-Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process.
+Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid) for the face preview page in the face enrollment process. This API must be used with [AddCredential](./js-apis-osAccount.md#addcredential8).
**System capability**: SystemCapability.UserIAM.UserAuth.FaceAuth
@@ -56,17 +56,28 @@ Sets an [XComponent surface ID](../arkui-ts/ts-basic-components-xcomponent.md#ge
| -------------- | ---------------------------------- | ---- | -------------------------- |
| surfaceId | string | Yes | ID of the surface held by the [XComponent](../arkui-ts/ts-basic-components-xcomponent.md#getxcomponentsurfaceid).|
+For details about the following error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 201 | Permission verification failed. |
+| 202 | The caller is not a system application. |
+| 12700001 | The operation is failed. |
+
**Example**
- ```js
- import faceAuth from '@ohos.userIAM.faceAuth';
-
- let surfaceId = "123456";
- let manager = new faceAuth.FaceAuthManager();
- try {
- manager.setSurfaceId(surfaceId);
- console.info("Set the surface ID successfully");
- } catch (e) {
- console.error("Failed to set the surface ID, error = " + e);
- }
- ```
+```js
+import userIAM_faceAuth from '@ohos.userIAM.faceAuth';
+
+// The surfaceId is obtained from the XComponent control. The surfaceId here is only an example.
+let surfaceId = "123456";
+let manager = new userIAM_faceAuth.FaceAuthManager();
+try {
+ manager.setSurfaceId(surfaceId);
+ console.info("Set the surface ID successfully");
+} catch (e) {
+ console.error("Failed to set the surface ID, error = " + e);
+}
+```
diff --git a/en/application-dev/reference/apis/js-apis-useriam-userauth.md b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
index ce73ba0bcd0ed53bb75bcb873cf35dd8f6910f6d..29044d135b43286a8b3df624584750022f6576b8 100644
--- a/en/application-dev/reference/apis/js-apis-useriam-userauth.md
+++ b/en/application-dev/reference/apis/js-apis-useriam-userauth.md
@@ -1,4 +1,4 @@
-# User Authentication
+# @ohos.userIAM.userAuth (User Authentication)
The **userIAM.userAuth** module provides user authentication capabilities in identity authentication scenarios, such as device unlocking, payment, and app login.
@@ -12,268 +12,115 @@ The **userIAM.userAuth** module provides user authentication capabilities in ide
import userIAM_userAuth from '@ohos.userIAM.userAuth';
```
-## Sample Code
-
-```js
-// API version 9
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
-export default {
- getVersion() {
- try {
- let version = userIAM_userAuth.getVersion();
- console.info("auth version = " + version);
- } catch (error) {
- console.info("get version failed, error = " + error);
- }
- },
-
- start() {
- console.info("start auth");
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.on("result", {
- callback: (result: userIAM_userAuth.AuthResultInfo) => {
- console.log("authV9 result " + result.result);
- console.log("authV9 token " + result.token);
- console.log("authV9 remainAttempts " + result.remainAttempts);
- console.log("authV9 lockoutDuration " + result.lockoutDuration);
- }
- });
- // If tips are needed
- auth.on("tip", {
- callback : (result : userIAM_userAuth.TipInfo) => {
- switch (result.tip) {
- case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
- // Do something;
- case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
- // Do something;
- // ...
- default:
- // Do others.
- }
- }
- });
- auth.start();
- console.log("authV9 start success");
- } catch (error) {
- console.log("authV9 error = " + error);
- // do error
- }
- },
+## AuthResultInfo9+
- getAvailableStatus() {
- console.info("start check auth support");
- try {
- userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
- console.info("current auth trust level is supported");
- } catch (error) {
- console.info("current auth trust level is not supported, error = " + error);
- }
- },
+Defines the authentication result.
- cancel() {
- console.info("start cancel auth");
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.start();
- auth.cancel();
- console.info("cancel auth success");
- } catch (error) {
- console.info("cancel auth failed, error = " + error);
- }
- }
-}
-```
+| Name | Type | Mandatory| Description |
+| ------------ | ---------- | ---- | -------------------- |
+| result | number | Yes | Authentication result. |
+| token | Uint8Array | No | Token that has passed the user identity authentication.|
+| remainAttempts | number | No | Number of remaining authentication times allowed.|
+| lockoutDuration | number | No | Time for which the authentication operation is frozen.|
-```js
-// API version 8
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
-let auth = new userIAM_userAuth.UserAuth();
+## TipInfo9+
-export default {
- getVersion() {
- console.info("start get version");
- let version = auth.getVersion();
- console.info("auth version = " + version);
- },
-
- startAuth() {
- console.info("start auth");
- auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
- onResult: (result, extraInfo) => {
- try {
- console.info("auth onResult result = " + result);
- console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
- if (result == userIAM_userAuth.ResultCode.SUCCESS) {
- // Add the logic to be executed when the authentication is successful.
- } else {
- // Add the logic to be executed when the authentication fails.
- }
- } catch (e) {
- console.info("auth onResult error = " + e);
- }
- },
-
- onAcquireInfo: (module, acquire, extraInfo) => {
- try {
- console.info("auth onAcquireInfo module = " + module);
- console.info("auth onAcquireInfo acquire = " + acquire);
- console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
- } catch (e) {
- console.info("auth onAcquireInfo error = " + e);
- }
- }
- });
- },
-
- checkAuthSupport() {
- console.info("start check auth support");
- let checkCode = this.auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
- if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) {
- console.info("check auth support success");
- // Add the logic to be executed if the specified authentication type is supported.
- } else {
- console.error("check auth support fail, code = " + checkCode);
- // Add the logic to be executed if the specified authentication type is not supported.
- }
- },
-
- cancelAuth() {
- console.info("start cancel auth");
- // Obtain contextId using auth().
- let contextId = auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
- onResult: (result, extraInfo) => {
- console.info("auth onResult result = " + result);
- },
-
- onAcquireInfo: (module, acquire, extraInfo) => {
- console.info("auth onAcquireInfo module = " + module);
- }
- });
- let cancelCode = this.auth.cancel(contextId);
- if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) {
- console.info("cancel auth success");
- } else {
- console.error("cancel auth fail");
- }
- }
-}
-```
+Defines the authentication tip information.
-```js
-// API version 6
-import userIAM_userAuth from '@ohos.userIAM.userAuth';
+**System capability**: SystemCapability.UserIAM.UserAuth.Core
-export default {
- startAuth() {
- console.info("start auth");
- let auth = userIAM_userAuth.getAuthenticator();
- auth.execute("FACE_ONLY", "S2").then((code)=>{
- console.info("auth success");
- // Add the logic to be executed when the authentication is successful.
- }).catch((code)=>{
- console.error("auth fail, code = " + code);
- // Add the logic to be executed when the authentication fails.
- });
- }
-}
-```
+| Name | Type | Mandatory| Description |
+| ------------ | ---------- | ---- | -------------------- |
+| module | number | Yes | ID of the module that sends the tip information. |
+| tip | number | Yes | Tip to be given during the authentication process. |
## EventInfo9+
-Defines the event information used in authentication.
+Enumerates the authentication event information types.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Type | Description |
+| Value | Description |
| --------- | ----------------------- |
-| [AuthResultInfo](#authresultinfo9) | Authentication result information. |
+| [AuthResultInfo](#authresultinfo9) | Authentication result. |
| [TipInfo](#tipinfo9) | Authentication tip information. |
+## AuthEventKey9+
+
+Defines the keyword of the authentication event type. It is used as a parameter of [on](#on9).
+
+| Value | Description |
+| ---------- | ----------------------- |
+| "result" | If the first parameter of [on](#on9) is **result**, the [callback](#callback9) returns the authentication result.|
+| "tip" | If the first parameter of [on](#on9) is **tip**, the [callback](#callback9) returns the authentication tip information.|
+
## AuthEvent9+
-Provides callbacks to return authentication events.
+Provides an asynchronous callback to return the authentication event information.
### callback9+
-callback: (result : EventInfo) => void
+callback(result : EventInfo) : void
-Called to return the authentication result or authentication tips.
+Called to return the authentication result or authentication tip information.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------- | -------------------------- | ---- | -------------------------------------------------------- |
-| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. |
+| Name | Type | Mandatory| Description |
+| --------- | -------------------------- | ---- | ------------------------------ |
+| result | [EventInfo](#eventinfo9) | Yes | Authentication result or tip information. |
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.on("result", {
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+let authType = userIAM_userAuth.UserAuthType.FACE;
+let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+// Obtain the authentication result through a callback.
+try {
+ let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ auth.on("result", {
callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.log("authV9 result " + result.result);
console.log("authV9 token " + result.token);
console.log("authV9 remainAttempts " + result.remainAttempts);
console.log("authV9 lockoutDuration " + result.lockoutDuration);
}
- });
- auth.start();
- console.log("authV9 start success");
- } catch (error) {
- console.log("authV9 error = " + error);
- // do error
- }
- ```
-
-## AuthResultInfo9+
-
-Defines the authentication result information.
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-| Name | Type | Mandatory| Description |
-| ------------ | ---------- | ---- | -------------------- |
-| result | number | Yes | Authentication result. |
-| token | Uint8Array | No | Token that has passed the user identity authentication.|
-| remainAttempts | number | No | Number of remaining authentication times allowed.|
-| lockoutDuration | number | No | Time for which the authentication operation is frozen.|
-
-## TipInfo9+
-
-Defines the authentication tip information.
-
-**System capability**: SystemCapability.UserIAM.UserAuth.Core
-
-| Name | Type | Mandatory| Description |
-| ------------ | ---------- | ---- | -------------------- |
-| module | number | No | Authentication module. |
-| tip | number | No | Tip to be given during the authentication process. |
-
-## AuthEventKey9+
-
-Defines the keyword of an authentication event.
-
-| Value | Description |
-| ---------- | ----------------------- |
-| "result" | Indicates authentication result.|
-| "tip" | If **AuthEventKey** is **result**, the callback returns the authentication tip information.|
+ });
+ auth.start();
+ console.log("authV9 start success");
+} catch (error) {
+ console.log("authV9 error = " + error);
+ // do error
+}
+// Obtain the authentication tip information through a callback.
+try {
+ let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ auth.on("tip", {
+ callback : (result : userIAM_userAuth.TipInfo) => {
+ switch (result.tip) {
+ case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
+ // Do something;
+ case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
+ // Do something.
+ default:
+ // Do others.
+ }
+ }
+ });
+ auth.start();
+ console.log("authV9 start success");
+} catch (error) {
+ console.log("authV9 error = " + error);
+ // do error
+}
+```
## AuthInstance9+
@@ -281,9 +128,12 @@ Implements user authentication.
### on9+
-on(name : AuthEventKey, callback : AuthEvent) : void
+on : (name : AuthEventKey, callback : AuthEvent) => void
-Enables authentication event listening.
+Subscribes to the user authentication events of the specified type.
+
+> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to subscribe to events.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
@@ -291,151 +141,210 @@ Enables authentication event listening.
| Name | Type | Mandatory| Description |
| --------- | -------------------------- | ---- | ------------------------- |
-| name | AuthEventKey | Yes | Keyword of the authentication event to listen for. |
-| callback | AuthEvent | Yes | Callback invoked to return the authentication event. |
+| name | [AuthEventKey](#autheventkey9) | Yes | Authentication event type. If the value is **result**, the callback returns the authentication result. If the value is **tip**, the callback returns the authentication tip information.|
+| callback | [AuthEvent](#authevent9) | Yes | Callback invoked to return the authentication result or tip information.|
+
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 401 | Incorrect parameters. |
+| 12500002 | General operation error. |
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.on("result", {
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+let authType = userIAM_userAuth.UserAuthType.FACE;
+let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+try {
+ let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ // Subscribe to the authentication result.
+ auth.on("result", {
callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.log("authV9 result " + result.result);
console.log("authV9 token " + result.token);
console.log("authV9 remainAttempts " + result.remainAttempts);
console.log("authV9 lockoutDuration " + result.lockoutDuration);
}
- });
- // If tips are needed
- auth.on("tip", {
+ });
+ // Subscribe to authentication tip information.
+ auth.on("tip", {
callback : (result : userIAM_userAuth.TipInfo) => {
switch (result.tip) {
case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_BRIGHT:
// Do something;
case userIAM_userAuth.FaceTips.FACE_AUTH_TIP_TOO_DARK:
// Do something;
- // ...
default:
// Do others.
}
}
- });
- auth.start();
- console.log("authV9 start success");
- } catch (error) {
- console.log("authV9 error = " + error);
- // do error
- }
- ```
+ });
+ auth.start();
+ console.log("authV9 start success");
+} catch (error) {
+ console.log("authV9 error = " + error);
+ // do error
+}
+```
### off9+
-off(name : AuthEventKey) : void
+off : (name : AuthEventKey) => void
-Disables authentication event listening.
+Unsubscribes from the user authentication events of the specific type.
+
+> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API to unsubscribe from events.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Mandatory| Description |
| --------- | -------------------------- | ---- | ------------------------- |
-| name | AuthEventKey | Yes | Keyword of the authentication event. |
+| name | [AuthEventKey](#autheventkey9) | Yes | Type of the authentication event to unsubscribe from. If the value is **result**, the authentication result is unsubscribed from. If the value is **tip**, the authentication tip information is unsubscribed from.|
+
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 401 | Incorrect parameters. |
+| 12500002 | General operation error. |
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+let authType = userIAM_userAuth.UserAuthType.FACE;
+let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+let auth;
+try {
+ auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ console.log("get auth instance success");
+} catch (error) {
+ console.log("get auth instance failed" + error);
+}
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.on("result", {
+try {
+ // Subscribe to the authentication result.
+ auth.on("result", {
callback: (result: userIAM_userAuth.AuthResultInfo) => {
console.log("authV9 result " + result.result);
console.log("authV9 token " + result.token);
console.log("authV9 remainAttempts " + result.remainAttempts);
console.log("authV9 lockoutDuration " + result.lockoutDuration);
}
- });
- console.log("turn on authentication event listening success");
- } catch (error) {
- console.log("turn off authentication event listening failed " + error);
- // do error
- }
-
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.off("result");
- console.info("turn off authentication event listening success");
- } catch (error) {
- console.info("turn off authentication event listening failed, error = " + error);
- }
- ```
+ });
+ console.log("subscribe authentication event success");
+} catch (error) {
+ console.log("subscribe authentication event failed " + error);
+}
+// Unsubscribe from the authentication result.
+try {
+ auth.off("result");
+ console.info("cancel subscribe authentication event success");
+} catch (error) {
+ console.info("cancel subscribe authentication event failed, error = " + error);
+}
+```
### start9+
-start() : void
+start : () => void
Starts authentication.
+> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API.
+
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 201 | Permission verification failed. |
+| 401 | Incorrect parameters. |
+| 12500001 | Authentication failed. |
+| 12500002 | General operation error. |
+| 12500003 | The operation is canceled. |
+| 12500004 | The operation is time-out. |
+| 12500005 | The authentication type is not supported. |
+| 12500006 | The authentication trust level is not supported. |
+| 12500007 | The authentication task is busy. |
+| 12500009 | The authenticator is locked. |
+| 12500010 | The type of credential has not been enrolled. |
+
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
-
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.start();
- console.info("authV9 start auth success");
- } catch (error) {
- console.info("authV9 start auth failed, error = " + error);
- }
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+let authType = userIAM_userAuth.UserAuthType.FACE;
+let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+
+try {
+ let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ auth.start();
+ console.info("authV9 start auth success");
+} catch (error) {
+ console.info("authV9 start auth failed, error = " + error);
+}
+```
### cancel9+
-cancel(): void
+cancel : () => void
-Cancels the authentication.
+Cancels this authentication.
+
+> **NOTE**
+> Use the [AuthInstance](#authinstance9) instance obtained to invoke this API. The [AuthInstance](#authinstance9) instance must be the one being authenticated.
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
**System capability**: SystemCapability.UserIAM.UserAuth.Core
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 201 | Permission verification failed. |
+| 401 | Incorrect parameters. |
+| 12500002 | General operation error. |
+
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
-
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- auth.start();
- auth.cancel();
- console.info("cancel auth success");
- } catch (error) {
- console.info("cancel auth failed, error = " + error);
- }
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+let authType = userIAM_userAuth.UserAuthType.FACE;
+let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+
+try {
+ let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ auth.cancel();
+ console.info("cancel auth success");
+} catch (error) {
+ console.info("cancel auth failed, error = " + error);
+}
+```
## userIAM_userAuth.getAuthInstance9+
@@ -444,7 +353,7 @@ getAuthInstance(challenge : Uint8Array, authType : UserAuthType, authTrustLevel
Obtains an **AuthInstance** instance for user authentication.
> **NOTE**
-> Each **AuthInstance** can be used to initiate an authentication only once.
+> An **AuthInstance** instance can be used for an authentication only once.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
@@ -460,23 +369,35 @@ Obtains an **AuthInstance** instance for user authentication.
| Type | Description |
| ----------------------------------------- | ------------ |
-| [AuthInstance](#authinstance9) | **Authenticator** object obtained.|
+| [AuthInstance](#authinstance9) | **Authenticator** instance obtained.|
+
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 401 | Incorrect parameters. |
+| 12500002 | General operation error. |
+| 12500005 | The authentication type is not supported. |
+| 12500006 | The authentication trust level is not supported. |
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
- let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
- let authType = userIAM_userAuth.UserAuthType.FACE;
- let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
- try {
- let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
- console.info("get auth instance success");
- } catch (error) {
- console.info("get auth instance success failed, error = " + error);
- }
- ```
+let challenge = new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8]);
+let authType = userIAM_userAuth.UserAuthType.FACE;
+let authTrustLevel = userIAM_userAuth.AuthTrustLevel.ATL1;
+
+try {
+ let auth = userIAM_userAuth.getAuthInstance(challenge, authType, authTrustLevel);
+ console.info("get auth instance success");
+} catch (error) {
+ console.info("get auth instance success failed, error = " + error);
+}
+```
## userIAM_userAuth.getVersion9+
@@ -494,24 +415,33 @@ Obtains the version of this authenticator.
| ------ | ---------------------- |
| number | Authenticator version obtained.|
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 201 | Permission verification failed. |
+| 12500002 | General operation error. |
+
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
- try {
- let version = userIAM_userAuth.getVersion();
- console.info("auth version = " + version);
- } catch (error) {
- console.info("get version failed, error = " + error);
- }
- ```
+try {
+ let version = userIAM_userAuth.getVersion();
+ console.info("auth version = " + version);
+} catch (error) {
+ console.info("get version failed, error = " + error);
+}
+```
## userIAM_userAuth.getAvailableStatus9+
getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel): void
-Checks whether the authentication capability of the specified trust level is available.
+Checks whether the specified authentication capability is supported.
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
@@ -522,54 +452,65 @@ Checks whether the authentication capability of the specified trust level is ava
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------- | ---- | -------------------------- |
| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.|
-| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. |
+| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. |
+
+For details about the error codes, see [User Authentication Error Codes](../errorcodes/errorcode-useriam.md).
+
+**Error codes**
+
+| ID| Error Message|
+| -------- | ------- |
+| 201 | Permission verification failed. |
+| 401 | Incorrect parameters. |
+| 12500002 | General operation error. |
+| 12500005 | The authentication type is not supported. |
+| 12500006 | The authentication trust level is not supported. |
+| 12500010 | The type of credential has not been enrolled. |
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
- try {
- userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
- console.info("current auth trust level is supported");
- } catch (error) {
- console.info("current auth trust level is not supported, error = " + error);
- }
- ```
+try {
+ userIAM_userAuth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
+ console.info("current auth trust level is supported");
+} catch (error) {
+ console.info("current auth trust level is not supported, error = " + error);
+}
+```
- ## ResultCodeV99+
+## UserAuthResultCode9+
-Enumerates the operation results.
+Enumerates the authentication result codes.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Default Value| Description |
+| Name | Value | Description |
| ----------------------- | ------ | -------------------- |
-| SUCCESS | 12500000 | The operation is successful. |
-| FAIL | 12500001 | The operation failed. |
-| GENERAL_ERROR | 12500002 | A common operation error occurred. |
-| CANCELED | 12500003 | The operation is canceled. |
-| TIMEOUT | 12500004 | The operation timed out. |
+| SUCCESS | 12500000 | The authentication is successful. |
+| FAIL | 12500001 | The authentication failed. |
+| GENERAL_ERROR | 12500002 | A general operation error occurred. |
+| CANCELED | 12500003 | The authentication is canceled. |
+| TIMEOUT | 12500004 | The authentication timed out. |
| TYPE_NOT_SUPPORT | 12500005 | The authentication type is not supported. |
| TRUST_LEVEL_NOT_SUPPORT | 12500006 | The authentication trust level is not supported. |
| BUSY | 12500007 | Indicates the busy state. |
-| INVALID_PARAMETERS | 12500008 | Invalid parameters are detected. |
| LOCKED | 12500009 | The authentication executor is locked. |
| NOT_ENROLLED | 12500010 | The user has not entered the authentication information.|
## UserAuth8+
-Provides methods to manage an **Authenticator** object.
+Provides APIs to manage an **Authenticator** object.
### constructor(deprecated)
constructor()
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9).
+A constructor used to create an authenticator instance.
-A constructor used to create an **authenticator** object.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAuthInstance](#useriam_userauthgetauthinstance9).
**System capability**: SystemCapability.UserIAM.UserAuth.Core
@@ -577,25 +518,24 @@ A constructor used to create an **authenticator** object.
| Type | Description |
| ---------------------- | -------------------- |
-| [UserAuth](#userauth8) | **Authenticator** object obtained.|
+| [UserAuth](#userauth8) | **Authenticator** instance obtained.|
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
- let auth = new userIAM_userAuth.UserAuth();
- ```
+let auth = new userIAM_userAuth.UserAuth();
+```
### getVersion(deprecated)
getVersion() : number
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9).
+Obtains the version of this authenticator.
-Obtains the authentication executor version.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getVersion](#useriam_userauthgetversion9).
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
@@ -609,23 +549,22 @@ Obtains the authentication executor version.
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
- let auth = new userIAM_userAuth.UserAuth();
- let version = auth.getVersion();
- console.info("auth version = " + version);
- ```
+let auth = new userIAM_userAuth.UserAuth();
+let version = auth.getVersion();
+console.info("auth version = " + version);
+```
### getAvailableStatus(deprecated)
getAvailableStatus(authType : UserAuthType, authTrustLevel : AuthTrustLevel) : number
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9).
+Checks whether the specified authentication capability is supported.
-Obtains the available status of the specified authentication trust level.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [getAvailableStatus](#useriam_userauthgetavailablestatus9).
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
@@ -636,40 +575,37 @@ Obtains the available status of the specified authentication trust level.
| Name | Type | Mandatory| Description |
| -------------- | ---------------------------------- | ---- | -------------------------- |
| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.|
-| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level of the authentication result. |
+| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. |
**Return value**
| Type | Description |
| ------ | ------------------------------------------------------------ |
-| number | Available status obtained. For details, see [ResultCode](#resultcodedeprecated).|
+| number | Query result. If the authentication capability is supported, **SUCCESS** is returned. Otherwise, a [ResultCode](#resultcodedeprecated) is returned.|
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let auth = new userIAM_userAuth.UserAuth();
- let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
- if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) {
- console.info("check auth support success");
- // Add the logic to be executed if the specified authentication type is supported.
- } else {
- console.error("check auth support fail, code = " + checkCode);
- // Add the logic to be executed if the specified authentication type is not supported.
- }
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let auth = new userIAM_userAuth.UserAuth();
+let checkCode = auth.getAvailableStatus(userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1);
+if (checkCode == userIAM_userAuth.ResultCode.SUCCESS) {
+ console.info("check auth support success");
+} else {
+ console.error("check auth support fail, code = " + checkCode);
+}
+```
### auth(deprecated)
auth(challenge: Uint8Array, authType: UserAuthType, authTrustLevel: AuthTrustLevel, callback: IUserAuthCallback): Uint8Array
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9).
-
Performs user authentication. This API uses a callback to return the result.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [start](#start9).
+
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
**System capability**: SystemCapability.UserIAM.UserAuth.Core
@@ -680,8 +616,8 @@ Performs user authentication. This API uses a callback to return the result.
| -------------- | ---------------------------------------- | ---- | ------------------------ |
| challenge | Uint8Array | Yes | Challenge value, which can be null. |
| authType | [UserAuthType](#userauthtype8) | Yes | Authentication type. Only **FACE** is supported.|
-| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Trust level. |
-| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. |
+| authTrustLevel | [AuthTrustLevel](#authtrustlevel8) | Yes | Authentication trust level. |
+| callback | [IUserAuthCallback](#iuserauthcallbackdeprecated) | Yes | Callback used to return the result. |
**Return value**
@@ -691,36 +627,35 @@ Performs user authentication. This API uses a callback to return the result.
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let auth = new userIAM_userAuth.UserAuth();
- auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
- onResult: (result, extraInfo) => {
- try {
- console.info("auth onResult result = " + result);
- console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
- if (result == userIAM_userAuth.ResultCode.SUCCESS) {
- // Add the logic to be executed when the authentication is successful.
- } else {
- // Add the logic to be executed when the authentication fails.
- }
- } catch (e) {
- console.info("auth onResult error = " + e);
- }
- }
- });
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let auth = new userIAM_userAuth.UserAuth();
+auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
+ onResult: (result, extraInfo) => {
+ try {
+ console.info("auth onResult result = " + result);
+ console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
+ if (result == userIAM_userAuth.ResultCode.SUCCESS) {
+ // Add the logic to be executed when the authentication is successful.
+ } else {
+ // Add the logic to be executed when the authentication fails.
+ }
+ } catch (e) {
+ console.info("auth onResult error = " + e);
+ }
+ }
+});
+```
### cancelAuth(deprecated)
cancelAuth(contextID : Uint8Array) : number
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9).
+Cancels an authentication based on the context ID.
-Cancels an authentication.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [cancel](#cancel9).
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
@@ -730,100 +665,86 @@ Cancels an authentication.
| Name | Type | Mandatory| Description |
| --------- | ---------- | ---- | ------------------------------------------ |
-| contextID | Uint8Array | Yes | Context ID, which is obtained by using [auth](#authdeprecated).|
+| contextID | Uint8Array | Yes | Context ID, which is obtained by [auth](#authdeprecated).|
**Return value**
| Type | Description |
| ------ | ------------------------ |
-| number | Whether the authentication is canceled.|
+| number | Returns **SUCCESS** if the cancellation is successful. Returns a [ResultCode](#resultcodedeprecated) otherwise.|
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- // contextId can be obtained using auth(). In this example, it is defined here.
- let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
- let auth = new userIAM_userAuth.UserAuth();
- let cancelCode = auth.cancelAuth(contextId);
- if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) {
- console.info("cancel auth success");
- } else {
- console.error("cancel auth fail");
- }
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+// contextId can be obtained by auth(). In this example, it is defined here.
+let contextId = new Uint8Array([0, 1, 2, 3, 4, 5, 6, 7]);
+let auth = new userIAM_userAuth.UserAuth();
+let cancelCode = auth.cancelAuth(contextId);
+if (cancelCode == userIAM_userAuth.ResultCode.SUCCESS) {
+ console.info("cancel auth success");
+} else {
+ console.error("cancel auth fail");
+}
+```
## IUserAuthCallback(deprecated)
-> **NOTE**
->
->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9).
+Provides callbacks to return the authentication result.
-Defines the object of the result returned by the callback during authentication.
+> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthEvent](#authevent9).
### onResult(deprecated)
onResult: (result : number, extraInfo : AuthResult) => void
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9).
+Called to return the authentication result.
-Obtains the authentication result.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9).
**System capability**: SystemCapability.UserIAM.UserAuth.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| --------- | -------------------------- | ---- | ------------------------------------------------------------ |
-| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated). |
+| Name | Type | Mandatory| Description |
+| --------- | -------------------------- | ---- | ------------------------------------------------ |
+| result | number | Yes | Authentication result. For details, see [ResultCode](#resultcodedeprecated).|
| extraInfo | [AuthResult](#authresultdeprecated) | Yes | Extended information, which varies depending on the authentication result.
If the authentication is successful, the user authentication token will be returned in **extraInfo**.
If the authentication fails, the remaining number of authentication times will be returned in **extraInfo**.
If the authentication executor is locked, the freeze time will be returned in **extraInfo**.|
-
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let auth = new userIAM_userAuth.UserAuth();
- auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
- onResult: (result, extraInfo) => {
- try {
- console.info("auth onResult result = " + result);
- console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
- if (result == userIAM_userAuth.ResultCode.SUCCESS) {
- // Add the logic to be executed when the authentication is successful.
- } else {
- // Add the logic to be executed when the authentication fails.
- }
- } catch (e) {
- console.info("auth onResult error = " + e);
- }
- },
-
- onAcquireInfo: (module, acquire, extraInfo) => {
- try {
- console.info("auth onAcquireInfo module = " + module);
- console.info("auth onAcquireInfo acquire = " + acquire);
- console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
- } catch (e) {
- console.info("auth onAcquireInfo error = " + e);
- }
- }
- });
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
+
+let auth = new userIAM_userAuth.UserAuth();
+auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
+ onResult: (result, extraInfo) => {
+ try {
+ console.info("auth onResult result = " + result);
+ console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
+ if (result == userIAM_userAuth.ResultCode.SUCCESS) {
+ // Add the logic to be executed when the authentication is successful.
+ } else {
+ // Add the logic to be executed when the authentication fails.
+ }
+ } catch (e) {
+ console.info("auth onResult error = " + e);
+ }
+ }
+});
+```
### onAcquireInfo(deprecated)
onAcquireInfo ?: (module : number, acquire : number, extraInfo : any) => void
-> **NOTE**
->
->This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9).
+Called to acquire authentication tip information. This API is optional.
-Obtains the tip code information during authentication. This function is optional.
+> **NOTE**
+> This API is supported since API version 8 and deprecated since API version 9. You are advised to use [callback](#callback9).
**System capability**: SystemCapability.UserIAM.UserAuth.Core
@@ -831,89 +752,74 @@ Obtains the tip code information during authentication. This function is optiona
| Name | Type | Mandatory| Description |
| --------- | ------ | ---- | ------------------------------ |
-| module | number | Yes | Type of the authentication executor. |
-| acquire | number | Yes | Interaction information of the authentication executor during the authentication process.|
+| module | number | Yes | ID of the module that sends the tip information. |
+| acquire | number | Yes | Authentication tip information.|
| extraInfo | any | Yes | Reserved field. |
**Example**
- ```js
- import userIAM_userAuth from '@ohos.userIAM.userAuth';
-
- let auth = new userIAM_userAuth.UserAuth();
- auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
- onResult: (result, extraInfo) => {
- try {
- console.info("auth onResult result = " + result);
- console.info("auth onResult extraInfo = " + JSON.stringify(extraInfo));
- if (result == userIAM_userAuth.ResultCode.SUCCESS) {
- // Add the logic to be executed when the authentication is successful.
- } else {
- // Add the logic to be executed when the authentication fails.
- }
- } catch (e) {
- console.info("auth onResult error = " + e);
- }
- },
-
- onAcquireInfo: (module, acquire, extraInfo) => {
- try {
- console.info("auth onAcquireInfo module = " + module);
- console.info("auth onAcquireInfo acquire = " + acquire);
- console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
- } catch (e) {
- console.info("auth onAcquireInfo error = " + e);
- }
- }
- });
- ```
+```js
+import userIAM_userAuth from '@ohos.userIAM.userAuth';
-## AuthResult(deprecated)
+let auth = new userIAM_userAuth.UserAuth();
+auth.auth(null, userIAM_userAuth.UserAuthType.FACE, userIAM_userAuth.AuthTrustLevel.ATL1, {
+ onAcquireInfo: (module, acquire, extraInfo) => {
+ try {
+ console.info("auth onAcquireInfo module = " + module);
+ console.info("auth onAcquireInfo acquire = " + acquire);
+ console.info("auth onAcquireInfo extraInfo = " + JSON.stringify(extraInfo));
+ } catch (e) {
+ console.info("auth onAcquireInfo error = " + e);
+ }
+ }
+});
+```
-> **NOTE**
->
->This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9).
+## AuthResult(deprecated)
Represents the authentication result object.
+> **NOTE**
+> This object is supported since API version 8 and deprecated since API version 9. You are advised to use [AuthResultInfo](#authresultinfo9).
+
**System capability**: SystemCapability.UserIAM.UserAuth.Core
| Name | Type | Mandatory| Description |
-| ------------ | ---------- | ---- | -------------------- |
-| token | Uint8Array | No | Identity authentication token. |
+| ------------ | ---------- | ---- | -------------------|
+| token | Uint8Array | No | Authentication token information.|
| remainTimes | number | No | Number of remaining authentication operations.|
| freezingTime | number | No | Time for which the authentication operation is frozen.|
## ResultCode(deprecated)
-> **NOTE**
-> This object is deprecated since API version 9. You are advised to use [ResultCodeV9](#resultcodev99).
+Enumerates the authentication result codes.
-Enumerates the operation results.
+> **NOTE**
+> This object is deprecated since API version 9. You are advised to use [UserAuthResultCode](#userauthresultcode9).
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Default Value| Description |
+| Name | Value| Description |
| ----------------------- | ------ | -------------------- |
| SUCCESS | 0 | The operation is successful. |
-| FAIL | 1 | The operation failed. |
-| GENERAL_ERROR | 2 | A common operation error occurred. |
-| CANCELED | 3 | The operation is canceled. |
-| TIMEOUT | 4 | The operation timed out. |
+| FAIL | 1 | The authentication failed. |
+| GENERAL_ERROR | 2 | A general operation error occurred. |
+| CANCELED | 3 | The authentication is canceled. |
+| TIMEOUT | 4 | The authentication timed out. |
| TYPE_NOT_SUPPORT | 5 | The authentication type is not supported. |
| TRUST_LEVEL_NOT_SUPPORT | 6 | The authentication trust level is not supported. |
| BUSY | 7 | Indicates the busy state. |
+| INVALID_PARAMETERS | 8 | Invalid parameters are detected. |
| LOCKED | 9 | The authentication executor is locked. |
| NOT_ENROLLED | 10 | The user has not entered the authentication information.|
-
## FaceTips8+
Enumerates the tip codes used during the facial authentication process.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Default Value| Description |
+| Name | Value | Description |
| ----------------------------- | ------ | ------------------------------------ |
| FACE_AUTH_TIP_TOO_BRIGHT | 1 | The obtained facial image is too bright due to high illumination. |
| FACE_AUTH_TIP_TOO_DARK | 2 | The obtained facial image is too dark due to low illumination. |
@@ -934,7 +840,7 @@ Enumerates the tip codes used during the fingerprint authentication process.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Default Value| Description |
+| Name | Value | Description |
| --------------------------------- | ------ | -------------------------------------------------- |
| FINGERPRINT_AUTH_TIP_GOOD | 0 | The obtained fingerprint image is in good condition. |
| FINGERPRINT_AUTH_TIP_DIRTY | 1 | Large fingerprint image noise is detected due to suspicious or detected dirt on the sensor.|
@@ -950,7 +856,7 @@ Enumerates the identity authentication types.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Default Value| Description |
+| Name | Value | Description |
| ----------- | ------ | ---------- |
| FACE | 2 | Facial authentication.|
| FINGERPRINT | 4 | Fingerprint authentication.|
@@ -961,7 +867,7 @@ Enumerates the trust levels of the authentication result.
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name| Default Value| Description |
+| Name| Value | Description |
| ---- | ------ | ------------------------- |
| ATL1 | 10000 | Trust level 1.|
| ATL2 | 20000 | Trust level 2.|
@@ -972,18 +878,18 @@ Enumerates the trust levels of the authentication result.
getAuthenticator(): Authenticator
+Obtains an **Authenticator** instance for user authentication.
+
> **NOTE**
> This API is deprecated since API version 8. You are advised to use [constructor](#constructordeprecated).
-Obtains an **Authenticator** object for user authentication.
-
**System capability**: SystemCapability.UserIAM.UserAuth.Core
**Return value**
| Type | Description |
| ----------------------------------------- | ------------ |
-| [Authenticator](#authenticatordeprecated) | **Authenticator** object obtained.|
+| [Authenticator](#authenticatordeprecated) | **Authenticator** instance obtained.|
**Example**
```js
@@ -992,61 +898,61 @@ Obtains an **Authenticator** object for user authentication.
## Authenticator(deprecated)
+Defines the **Authenticator** object.
+
> **NOTE**
> This object is deprecated since API version 8. You are advised to use [UserAuth](#userauth8).
-Provides methods to manage an **Authenticator** object.
-
-
### execute(deprecated)
execute(type: AuthType, level: SecureLevel, callback: AsyncCallback<number>): void
+Performs user authentication. This API uses asynchronous callback to return the result.
+
> **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated).
-Performs user authentication. This API uses asynchronous callback to return the result.
-
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
**System capability**: SystemCapability.UserIAM.UserAuth.Core
**Parameters**
-| Name | Type | Mandatory| Description |
-| -------- | --------------------------- | ---- | ------------------------------------------------------------ |
+| Name | Type | Mandatory| Description |
+| -------- | --------------------------- | ---- | -------------------------- |
| type | AuthType | Yes | Authentication type. Only **FACE_ONLY** is supported.
**ALL** is reserved and not supported by the current version.|
-| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
-| callback | AsyncCallback<number> | No | Callback used to return the result. |
+| level | SecureLevel | Yes | Security level of the authentication. It can be **S1** (lowest), **S2**, **S3**, or **S4** (highest).
Devices capable of 3D facial recognition support S3 and lower-level authentication.
Devices capable of 2D facial recognition support S2 and lower-level authentication.|
+| callback | AsyncCallback<number> | Yes | Callback used to return the result. |
- Parameters returned in callback
+Parameters returned in callback
| Type | Description |
| ------ | ------------------------------------------------------------ |
| number | Authentication result. For details, see [AuthenticationResult](#authenticationresultdeprecated).|
**Example**
- ```js
- let authenticator = userIAM_userAuth.getAuthenticator();
- authenticator.execute("FACE_ONLY", "S2", (error, code)=>{
- if (code === userIAM_userAuth.ResultCode.SUCCESS) {
- console.info("auth success");
- return;
- }
- console.error("auth fail, code = " + code);
- });
- ```
+
+```js
+let authenticator = userIAM_userAuth.getAuthenticator();
+authenticator.execute("FACE_ONLY", "S2", (error, code)=>{
+ if (code === userIAM_userAuth.ResultCode.SUCCESS) {
+ console.info("auth success");
+ return;
+ }
+ console.error("auth fail, code = " + code);
+});
+```
### execute(deprecated)
-execute(type:AuthType, level:SecureLevel): Promise<number>
+execute(type : AuthType, level : SecureLevel): Promise<number>
+
+Performs user authentication. This API uses a promise to return the result.
> **NOTE**
> This API is deprecated since API version 8. You are advised to use [auth](#authdeprecated).
-Performs user authentication. This API uses a promise to return the result.
-
**Required permissions**: ohos.permission.ACCESS_BIOMETRIC
**System capability**: SystemCapability.UserIAM.UserAuth.Core
@@ -1066,25 +972,25 @@ Performs user authentication. This API uses a promise to return the result.
**Example**
- ```js
- let authenticator = userIAM_userAuth.getAuthenticator();
- authenticator.execute("FACE_ONLY", "S2").then((code)=>{
- console.info("auth success");
- }).catch((error)=>{
- console.error("auth fail, code = " + error);
- });
- ```
+```js
+let authenticator = userIAM_userAuth.getAuthenticator();
+authenticator.execute("FACE_ONLY", "S2").then((code)=>{
+ console.info("auth success");
+}).catch((error)=>{
+ console.error("auth fail, code = " + error);
+});
+```
## AuthenticationResult(deprecated)
+Enumerates the authentication results.
+
> **NOTE**
> This object is discarded since API version 8. You are advised to use [ResultCode](#resultcodedeprecated).
-Enumerates the authentication results.
-
**System capability**: SystemCapability.UserIAM.UserAuth.Core
-| Name | Default Value| Description |
+| Name | Value | Description |
| ------------------ | ------ | -------------------------- |
| NO_SUPPORT | -1 | The device does not support the current authentication mode.|
| SUCCESS | 0 | The authentication is successful. |
diff --git a/en/application-dev/reference/apis/js-apis-util.md b/en/application-dev/reference/apis/js-apis-util.md
index 8897b51f07b4e00feae752e792820e6b9b32370f..09e3c245326f4bc9008e20535edfa4f0a2c3d2d0 100755
--- a/en/application-dev/reference/apis/js-apis-util.md
+++ b/en/application-dev/reference/apis/js-apis-util.md
@@ -1,6 +1,6 @@
-# @ohos.util
+# @ohos.util (Utilities)
-This module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types.
+The **util** module provides common utility functions, such as **TextEncoder** and **TextDecoder** for string encoding and decoding, **RationalNumber** for rational number operations, **LruBuffer** for buffer management, **Scope** for range determination, **Base64** for Base64 encoding and decoding, and **Types** for checks of built-in object types.
> **NOTE**
>
diff --git a/en/application-dev/reference/apis/js-apis-webSocket.md b/en/application-dev/reference/apis/js-apis-webSocket.md
index 660c42d8a3c44b0cb962dce1d5245957f37c5c63..2b2fa3af70da2fd1725ef0221b8fd7cf5654f531 100644
--- a/en/application-dev/reference/apis/js-apis-webSocket.md
+++ b/en/application-dev/reference/apis/js-apis-webSocket.md
@@ -1,8 +1,8 @@
-# @ohos.net.webSocket
+# @ohos.net.webSocket (WebSocket Connection)
The **webSocket** module implements WebSocket connection management and operation.
-> **NOTE:**
+> **NOTE**
> The initial APIs of this module are supported since API version 6. Newly added APIs will be marked with a superscript to indicate their earliest API version.
>
diff --git a/en/application-dev/reference/apis/js-apis-webview.md b/en/application-dev/reference/apis/js-apis-webview.md
index 92f40c92f26257e614135694d49d69608ea32a23..83d89392cd8ade90901018fbe5721ce53ba54f2e 100644
--- a/en/application-dev/reference/apis/js-apis-webview.md
+++ b/en/application-dev/reference/apis/js-apis-webview.md
@@ -1,6 +1,6 @@
-# @ohos.web.webview (Webview)
+# @ohos.web.webview
The **Webview** module provides APIs for web control.
@@ -19,6 +19,46 @@ The **Webview** module provides APIs for web control.
```ts
import web_webview from '@ohos.web.webview';
```
+
+### once
+
+once(type: string, callback: Callback\): void
+
+Registers a one-time callback for web events of the specified type.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| ------- | ---------------- | ---- | -------------------- |
+| type | string | Yes | Web event type. The value can be **"webInited"**, indicating completion of web initialization. |
+| headers | Callback\ | Yes | Callback to register.|
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview'
+
+web_webview.once("webInited", () => {
+ console.log("setCookie")
+ web_webview.WebCookieManager.setCookie("www.example.com", "a=b")
+})
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
+
## WebMessagePort
Implements a **WebMessagePort** object to send and receive messages.
@@ -61,7 +101,7 @@ struct WebComponent {
### postMessageEvent
-postMessageEvent(message: string): void
+postMessageEvent(message: WebMessage): void
Sends a message. For the complete sample code, see [postMessage](#postmessage).
@@ -71,7 +111,7 @@ Sends a message. For the complete sample code, see [postMessage](#postmessage).
| Name | Type | Mandatory| Description |
| ------- | ------ | ---- | :------------- |
-| message | string | Yes | Message to send.|
+| message | [WebMessage](#webmessage) | Yes | Message to send.|
**Error codes**
@@ -113,7 +153,7 @@ struct WebComponent {
### onMessageEvent
-onMessageEvent(callback: (result: string) => void): void
+onMessageEvent(callback: (result: WebMessage) => void): void
Registers a callback to receive messages from the HTML5 side. For the complete sample code, see [postMessage](#postmessage).
@@ -123,7 +163,7 @@ Registers a callback to receive messages from the HTML5 side. For the complete s
| Name | Type | Mandatory| Description |
| -------- | -------- | ---- | :------------------- |
-| result | string | Yes | Message received.|
+| result | [WebMessage](#webmessage) | Yes | Message received.|
**Error codes**
@@ -152,7 +192,17 @@ struct WebComponent {
try {
this.ports = this.controller.createWebMessagePorts();
this.ports[1].onMessageEvent((msg) => {
- console.log("received message from html5, on message:" + msg);
+ if (typeof(msg) == "string") {
+ console.log("received string message from html5, string is:" + msg);
+ } else if (typeof(msg) == "object") {
+ if (msg instanceof ArrayBuffer) {
+ console.log("received arraybuffer from html5, length is:" + msg.byteLength);
+ } else {
+ console.log("not support");
+ }
+ } else {
+ console.log("not support");
+ }
})
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
@@ -166,13 +216,40 @@ struct WebComponent {
## WebviewController
-Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs in the **WebviewController** can be invoked only after it has been bound to the target **\** component.
+Implements a **WebviewController** to control the behavior of the **\** component. A **WebviewController** can control only one **\** component, and the APIs (except static APIs) in the **WebviewController** can be invoked only after it has been bound to the target **\** component.
+
+### initializeWebEngine
+
+static initializeWebEngine(): void
+
+Loads the dynamic link library (DLL) file of the web engine. This API can be called before the **\** component is initialized to improve the startup performance.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Example**
+
+The following code snippet exemplifies calling this API after the EntryAbility is created.
+
+```ts
+// xxx.ts
+import UIAbility from '@ohos.app.ability.UIAbility';
+import web_webview from '@ohos.web.webview';
+
+export default class EntryAbility extends UIAbility {
+ onCreate(want, launchParam) {
+ console.log("EntryAbility onCreate")
+ web_webview.WebviewController.initializeWebEngine()
+ globalThis.abilityWant = want
+ console.log("EntryAbility onCreate done")
+ }
+}
+```
### Creating an Object
```ts
// xxx.ets
-import web_webview from '@ohos.web.webview'
+import web_webview from '@ohos.web.webview';
@Entry
@Component
@@ -1397,8 +1474,21 @@ struct WebComponent {
// 2. Send one of the message ports to the HTML side, which can then save and use the port.
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
// 3. Register a callback for the other message port on the application side.
- this.ports[1].onMessageEvent((result: string) => {
- var msg = 'Got msg from HTML: ' + result;
+ this.ports[1].onMessageEvent((result: WebMessage) => {
+ var msg = 'Got msg from HTML:';
+ if (typeof(result) == "string") {
+ console.log("received string message from html5, string is:" + result);
+ msg = msg + result;
+ } else if (typeof(result) == "object") {
+ if (result instanceof ArrayBuffer) {
+ console.log("received arraybuffer from html5, length is:" + result.byteLength);
+ msg = msg + "lenght is " + result.byteLength;
+ } else {
+ console.log("not support");
+ }
+ } else {
+ console.log("not support");
+ }
this.receivedFromHtml = msg;
})
} catch (error) {
@@ -1456,7 +1546,21 @@ window.addEventListener('message', function (event) {
The h5Port = event.ports[0]; // 1. Save the port number sent from the eTS side.
h5Port.onmessage = function (event) {
// 2. Receive the message sent from the eTS side.
- var msg = 'Got message from ets:' + event.data;
+ var msg = 'Got message from ets:';
+ var result = event.data;
+ if (typeof(result) == "string") {
+ console.log("received string message from html5, string is:" + result);
+ msg = msg + result;
+ } else if (typeof(result) == "object") {
+ if (result instanceof ArrayBuffer) {
+ console.log("received arraybuffer from html5, length is:" + result.byteLength);
+ msg = msg + "lenght is " + result.byteLength;
+ } else {
+ console.log("not support");
+ }
+ } else {
+ console.log("not support");
+ }
output.innerHTML = msg;
}
}
@@ -1759,7 +1863,7 @@ struct WebComponent {
getTitle(): string
-Obtains the title of the file selector.
+Obtains the title of the current web page.
**System capability**: SystemCapability.Web.Webview.Core
@@ -1767,7 +1871,7 @@ Obtains the title of the file selector.
| Type | Description |
| ------ | -------------------- |
-| string | Title of the file selector.|
+| string | Title of the current web page.|
**Error codes**
@@ -2123,6 +2227,222 @@ struct WebComponent {
}
```
+### scrollTo
+
+scrollTo(x:number, y:number): void
+
+Scrolls the page to the specified absolute position.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description |
+| ------ | -------- | ---- | ---------------------- |
+| x | number | Yes | X coordinate of the absolute position. If the value is a negative number, the value 0 is used.|
+| y | number | Yes | Y coordinate of the absolute position. If the value is a negative number, the value 0 is used.|
+
+**Error codes**
+
+For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17100001 | Init error. The WebviewController must be associated with a Web component. |
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview';
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+
+ build() {
+ Column() {
+ Button('scrollTo')
+ .onClick(() => {
+ try {
+ this.controller.scrollTo(50, 50);
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
+
+```html
+
+
+
+
+ Demo
+
+
+
+Scroll Test
+
+
+```
+
+### scrollBy
+
+scrollBy(deltaX:number, deltaY:number): void
+
+Scrolls the page by the specified amount.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description |
+| ------ | -------- | ---- | ---------------------- |
+| deltaX | number | Yes | Amount to scroll by along the x-axis. The positive direction is rightward.|
+| deltaY | number | Yes | Amount to scroll by along the y-axis. The positive direction is downward.|
+
+**Error codes**
+
+For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17100001 | Init error. The WebviewController must be associated with a Web component. |
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview';
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+
+ build() {
+ Column() {
+ Button('scrollBy')
+ .onClick(() => {
+ try {
+ this.controller.scrollBy(50, 50);
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
+
+```html
+
+
+
+
+ Demo
+
+
+
+Scroll Test
+
+
+```
+
+### slideScroll
+
+slideScroll(vx:number, vy:number): void
+
+Simulates a slide-to-scroll action on the page at the specified velocity.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Parameters**
+
+| Name| Type| Mandatory| Description |
+| ------ | -------- | ---- | ---------------------- |
+| vx | number | Yes | Horizontal velocity component of the slide-to-scroll action, where the positive direction is rightward.|
+| vy | number | Yes | Vertical velocity component of the slide-to-scroll action, where the positive direction is downward.|
+
+**Error codes**
+
+For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
+
+| ID| Error Message |
+| -------- | ------------------------------------------------------------ |
+| 17100001 | Init error. The WebviewController must be associated with a Web component. |
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview';
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+
+ build() {
+ Column() {
+ Button('slideScroll')
+ .onClick(() => {
+ try {
+ this.controller.slideScroll(500, 500);
+ } catch (error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ })
+ Web({ src: 'www.example.com', controller: this.controller })
+ }
+ }
+}
+```
+
+```html
+
+
+
+
+ Demo
+
+
+
+Scroll Test
+
+
+```
+
### getOriginalUrl
getOriginalUrl(): string
@@ -2244,7 +2564,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
-| 401 | Invalid input parameter. |
**Example**
@@ -2275,7 +2594,7 @@ struct WebComponent {
### hasImage
-hasImage(callback: AsyncCallback): void
+hasImage(callback: AsyncCallback\): void
Checks whether this page contains images. This API uses an asynchronous callback to return the result.
@@ -2294,7 +2613,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
-| 401 | Invalid input parameter. |
**Example**
@@ -2312,7 +2630,7 @@ struct WebComponent {
Button('hasImageCb')
.onClick(() => {
try {
- this.controller.hasImage((err, data) => {
+ this.controller.hasImage((error, data) => {
if (error) {
console.info(`hasImage error: ` + JSON.stringify(error))
return;
@@ -2331,7 +2649,7 @@ struct WebComponent {
### hasImage
-hasImage(): Promise
+hasImage(): Promise\
Checks whether this page contains images. This API uses a promise to return the result.
@@ -2350,7 +2668,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web compoent. |
-| 401 | Invalid input parameter. |
**Example**
@@ -2396,7 +2713,7 @@ Clears the cache in the application. This API will clear the cache for all webvi
| Name | Type | Mandatory| Description |
| -------- | ------- | ---- | -------------------------------------------------------- |
-| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **false** means to only clear the cache in the RAM.|
+| clearRom | boolean | Yes | Whether to clear the cache in the ROM and RAM at the same time. The value **true** means to clear the cache in the ROM and RAM at the same time, and **false** means to only clear the cache in the RAM.|
**Error codes**
@@ -2405,7 +2722,6 @@ For details about the error codes, see [Webview Error Codes](../errorcodes/error
| ID| Error Message |
| -------- | ------------------------------------------------------------ |
| 17100001 | Init error. The WebviewController must be associated with a Web component. |
-| 401 | Invalid input parameter. |
**Example**
@@ -2483,9 +2799,58 @@ struct WebComponent {
}
```
+### customizeSchemes
+
+static customizeSchemes(schemes: Array\): void
+
+Customizes the URL schemes (also known as protocols). It is recommended that this API be called before any **\** component is initialized.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+**Parameters**
+
+| Name | Type | Mandatory| Description |
+| -------- | ------- | ---- | -------------------------------------- |
+| schemes | Array\<[WebCustomScheme](#webcustomscheme)\> | Yes | Array of up to 10 custom schemes.|
+
+**Example**
+
+```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview';
+
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController();
+ responseweb: WebResourceResponse = new WebResourceResponse()
+ scheme1: web_webview.WebCustomScheme = {schemeName: "name1", isSupportCORS: true, isSupportFetch: true}
+ scheme2: web_webview.WebCustomScheme = {schemeName: "name2", isSupportCORS: true, isSupportFetch: true}
+ scheme3: web_webview.WebCustomScheme = {schemeName: "name3", isSupportCORS: true, isSupportFetch: true}
+
+ aboutToAppear():void {
+ try {
+ web_webview.WebviewController.customizeSchemes([this.scheme1, this.scheme2, this.scheme3])
+ } catch(error) {
+ console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
+ }
+ }
+
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .onInterceptRequest((event) => {
+ console.log('url:' + event.request.getRequestUrl())
+ return this.responseweb
+ })
+ }
+ }
+}
+```
+
## WebCookieManager
-Implements a **WebCookie** object to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookie** object.
+Implements a **WebCookieManager** instance to manage behavior of cookies in **\** components. All **\** components in an application share a **WebCookieManager** instance.
### getCookie
@@ -3600,7 +3965,7 @@ Implements a **WebAsyncController** object, which can be used to control the beh
@Component
struct WebComponent {
controller: WebController = new WebController();
- webAsyncController: WebAsyncController = new web_webview.WebAsyncController(this.controller)
+ webAsyncController: web_webview.WebAsyncController = new web_webview.WebAsyncController(this.controller)
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
@@ -3635,8 +4000,8 @@ Stores this web page. This API uses an asynchronous callback to return the resul
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
-| baseName | string | Yes| Save path. The value cannot be null.
-| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
+| baseName | string | Yes| Save path. The value cannot be null. |
+| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
| callback | AsyncCallback\ | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
**Example**
@@ -3677,14 +4042,14 @@ Stores this web page. This API uses a promise to return the result.
| Name | Type | Mandatory | Description |
| -------- | ---------------------------------------- | ---- | ----------------------------------- |
-| baseName | string | Yes| Save path. The value cannot be null.
-| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
+| baseName | string | Yes| Save path. The value cannot be null. |
+| autoName | boolean | Yes| Whether to automatically generate a file name.
The value **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory. |
**Return value**
-| Type | Description |
-| ---------------------------------------- | ---------------------------------------- |
-| Promise | Promise used to return the save path if the operation is successful and null otherwise.|
+| Type | Description |
+| ---------------- | ------------------------------------------------------------ |
+| Promise\ | Promise used to return the save path if the operation is successful and null otherwise. |
**Example**
@@ -4100,6 +4465,15 @@ Provides the element information of the area being clicked. For details about th
| type | [HitTestTypeV9](#hittesttypev9) | Yes| No| Element type of the area being clicked.|
| extra | string | Yes| No|Extra information of the area being clicked. If the area being clicked is an image or a link, the extra information is the URL of the image or link.|
+## WebMessage
+
+Describes the data types supported for [WebMessagePort](#webmessageport).
+
+| Type | Description |
+| -------- | -------------------------------------- |
+| string | String type.|
+| ArrayBuffer | Binary type.|
+
## WebStorageOrigin
Provides usage information of the Web SQL Database.
@@ -4143,14 +4517,6 @@ Obtains the page record with the specified index in the history stack.
| --------------------------- | ------------ |
| [HistoryItem](#historyitem) | Historical page record.|
-**Error codes**
-
-For details about the error codes, see [Webview Error Codes](../errorcodes/errorcode-webview.md).
-
-| ID| Error Message |
-| -------- | ----------------------- |
-| 401 | Invalid input parameter |
-
**Example**
```ts
@@ -4172,7 +4538,7 @@ struct WebComponent {
let list = this.controller.getBackForwardEntries();
let historyItem = list.getItemAtIndex(list.currentIndex);
console.log("HistoryItem: " + JSON.stringify(historyItem));
- this.icon = item.icon;
+ this.icon = historyItem.icon;
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
@@ -4196,4 +4562,14 @@ Describes a historical page record.
| historyRawUrl | string | Yes | No | Original URL of the historical page. |
| title | string | Yes | No | Title of the historical page. |
-###
+## WebCustomScheme
+
+Defines a custom URL scheme.
+
+**System capability**: SystemCapability.Web.Webview.Core
+
+| Name | Type | Readable| Writable| Description |
+| -------------- | --------- | ---- | ---- | ---------------------------- |
+| schemeName | string | Yes | Yes | Name of the custom URL scheme. The value can contain a maximum of 32 characters and include only lowercase letters, digits, periods (.), plus signs (+), and hyphens (-). |
+| isSupportCORS | boolean | Yes | Yes | Whether to support cross-origin resource sharing (CORS). |
+| isSupportFetch | boolean | Yes | Yes | Whether to support fetch requests. |
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 0e9b480a1326760e25e56bca698bd8e8581bbb68..e2afb3e5eaa55dfb4d4509db3c87ba55821cd748 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
@@ -467,13 +467,13 @@ Sets whether to enable geolocation access. By default, this feature is enabled.
mediaPlayGestureAccess(access: boolean)
-Sets whether a manual click is required for video playback.
+Sets whether video playback must be started by user gestures. This API is not applicable to videos that do not have an audio track or whose audio track is muted.
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
| ------ | ------- | ---- | ---- | ----------------- |
-| access | boolean | Yes | true | Whether a manual click is required for video playback.|
+| access | boolean | Yes | true | Whether video playback must be started by user gestures.|
**Example**
@@ -522,6 +522,109 @@ Sets whether to enable the multi-window permission.
}
```
+### horizontalScrollBarAccess9+
+
+horizontalScrollBarAccess(horizontalScrollBar: boolean)
+
+Sets whether to display the horizontal scrollbar, including the system default scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed.
+
+**Parameters**
+
+| Name | Type | Mandatory | Default Value | Description |
+| ----------- | ------- | ---- | ----- | ------------ |
+| horizontalScrollBar | boolean | Yes | true | Whether to display the horizontal scrollbar.|
+
+**Example**
+
+ ```ts
+ // xxx.ets
+ @Entry
+ @Component
+ struct WebComponent {
+ controller: WebController = new WebController()
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .horizontalScrollBarAccess(true)
+ }
+ }
+ }
+ ```
+
+ ```html
+
+
+
+
+ Demo
+
+
+
+ Scroll Test
+
+
+ ```
+
+### verticalScrollBarAccess9+
+
+verticalScrollBarAccess(verticalScrollBar: boolean)
+
+Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed.
+
+**Parameters**
+
+| Name | Type | Mandatory | Default Value | Description |
+| ----------- | ------- | ---- | ----- | ------------ |
+| verticalScrollBarAccess | boolean | Yes | true | Whether to display the vertical scrollbar.|
+
+**Example**
+
+ ```ts
+ // xxx.ets
+ @Entry
+ @Component
+ struct WebComponent {
+ controller: WebController = new WebController()
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .verticalScrollBarAccess(true)
+ }
+ }
+ }
+ ```
+
+ ```html
+
+
+
+
+ Demo
+
+
+
+ Scroll Test
+
+
+ ```
+
+
### cacheMode
cacheMode(cacheMode: CacheMode)
@@ -707,13 +810,13 @@ Sets whether to block online downloads.
defaultFixedFontSize(size: number)
-Sets the default fixed font size of the web page.
+Sets the default fixed font size for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value| Description |
| ------ | -------- | ---- | ------ | ---------------------------- |
-| size | number | Yes | 13 | Default fixed font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.|
+| size | number | Yes | 13 | Default fixed font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. |
**Example**
@@ -724,11 +827,11 @@ Sets the default fixed font size of the web page.
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
- @State size: number = 16
+ @State fontSize: number = 16
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
- .defaultFixedFontSize(this.size)
+ .defaultFixedFontSize(this.fontSize)
}
}
}
@@ -738,13 +841,13 @@ Sets the default fixed font size of the web page.
defaultFontSize(size: number)
-Sets the default font size of the web page.
+Sets the default font size for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value| Description |
| ------ | -------- | ---- | ------ | ------------------------ |
-| size | number | Yes | 16 | Default font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.|
+| size | number | Yes | 16 | Default font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. |
**Example**
@@ -755,11 +858,11 @@ Sets the default font size of the web page.
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
- @State size: number = 13
+ @State fontSize: number = 13
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
- .defaultFontSize(this.size)
+ .defaultFontSize(this.fontSize)
}
}
}
@@ -769,13 +872,44 @@ Sets the default font size of the web page.
minFontSize(size: number)
-Sets the minimum font size of the web page.
+Sets the minimum font size for the web page.
+
+**Parameters**
+
+| Name| Type| Mandatory| Default Value| Description |
+| ------ | -------- | ---- | ------ | ------------------------ |
+| size | number | Yes | 8 | Minimum font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. |
+
+**Example**
+
+ ```ts
+ // xxx.ets
+ import web_webview from '@ohos.web.webview'
+ @Entry
+ @Component
+ struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController()
+ @State fontSize: number = 13
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .minFontSize(this.fontSize)
+ }
+ }
+ }
+ ```
+
+### minLogicalFontSize9+
+
+minLogicalFontSize(size: number)
+
+Sets the minimum logical font size for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value| Description |
| ------ | -------- | ---- | ------ | ------------------------ |
-| size | number | Yes | 8 | Minimum font size of the web page. The value is a non-negative integer ranging from 1 to 72. If the value is less than 1, the value 1 is used. If the value is greater than 72, the value 72 is used.|
+| size | number | Yes | 8 | Minimum logical font size to set, in px. The value ranges from -2^31 to 2^31-1. In actual rendering, values greater than 72 are handled as 72, and values less than 1 are handled as 1. |
**Example**
@@ -786,27 +920,28 @@ Sets the minimum font size of the web page.
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
- @State size: number = 13
+ @State fontSize: number = 13
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
- .minFontSize(this.size)
+ .minLogicalFontSize(this.fontSize)
}
}
}
```
+
### webFixedFont9+
webFixedFont(family: string)
-Sets the fixed font family of the web page.
+Sets the fixed font family for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value | Description |
| ------ | -------- | ---- | --------- | ---------------------------- |
-| family | string | Yes | monospace | Fixed font family of the web page.|
+| family | string | Yes | monospace | Fixed font family to set.|
**Example**
@@ -831,13 +966,13 @@ Sets the fixed font family of the web page.
webSansSerifFont(family: string)
-Sets the sans serif font family of the web page.
+Sets the sans serif font family for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value | Description |
| ------ | -------- | ---- | ---------- | --------------------------------- |
-| family | string | Yes | sans-serif | Sans serif font family of the web page.|
+| family | string | Yes | sans-serif | Sans serif font family to set.|
**Example**
@@ -862,13 +997,13 @@ Sets the sans serif font family of the web page.
webSerifFont(family: string)
-Sets the serif font family of the web page.
+Sets the serif font family for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value| Description |
| ------ | -------- | ---- | ------ | ---------------------------- |
-| family | string | Yes | serif | Serif font family of the web page.|
+| family | string | Yes | serif | Serif font family to set.|
**Example**
@@ -893,13 +1028,13 @@ Sets the serif font family of the web page.
webStandardFont(family: string)
-Sets the standard font family of the web page.
+Sets the standard font family for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value | Description |
| ------ | -------- | ---- | ---------- | ------------------------------- |
-| family | string | Yes | sans serif | Standard font family of the web page.|
+| family | string | Yes | sans serif | Standard font family to set.|
**Example**
@@ -924,13 +1059,13 @@ Sets the standard font family of the web page.
webFantasyFont(family: string)
-Sets the fantasy font family of the web page.
+Sets the fantasy font family for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value | Description |
| ------ | -------- | ---- | ------- | ------------------------------ |
-| family | string | Yes | fantasy | Fantasy font family of the web page.|
+| family | string | Yes | fantasy | Fantasy font family to set.|
**Example**
@@ -955,13 +1090,13 @@ Sets the fantasy font family of the web page.
webCursiveFont(family: string)
-Sets the cursive font family of the web page.
+Sets the cursive font family for the web page.
**Parameters**
| Name| Type| Mandatory| Default Value | Description |
| ------ | -------- | ---- | ------- | ------------------------------ |
-| family | string | Yes | cursive | Cursive font family of the web page.|
+| family | string | Yes | cursive | Cursive font family to set.|
**Example**
@@ -982,6 +1117,100 @@ Sets the cursive font family of the web page.
}
```
+### darkMode9+
+
+darkMode(mode: WebDarkMode)
+
+Sets the web dark mode. By default, web dark mode is disabled. When it is enabled, the **\** component enables the dark theme defined for web pages if the theme has been defined in **prefer-color-scheme** of a media query, and remains unchanged otherwise. To enable the forcible dark mode, use this API with [forceDarkAccess](#forcedarkaccess9).
+
+**Parameters**
+
+| Name| Type| Mandatory| Default Value | Description |
+| ------ | ----------- | ---- | --------------- | ------------------ |
+| mode | [WebDarkMode](#webdarkmode9) | Yes | WebDarkMode.Off | Web dark mode to set.|
+
+**Example**
+
+ ```ts
+ // xxx.ets
+ import web_webview from '@ohos.web.webview'
+ @Entry
+ @Component
+ struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController()
+ @State mode: WebDarkMode = WebDarkMode.On
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .darkMode(this.mode)
+ }
+ }
+ }
+ ```
+
+### forceDarkAccess9+
+
+forceDarkAccess(access: boolean)
+
+Sets whether to enable forcible dark mode for the web page. By default, this feature is turned off. This API is applicable only when dark mode is enabled in [darkMode](#darkmode9).
+
+**Parameters**
+
+| Name| Type| Mandatory| Default Value | Description |
+| ------ | ------- | ---- | ----- | ------------------ |
+| access | boolean | Yes | false | Whether to enable forcible dark mode for the web page.|
+
+**Example**
+
+ ```ts
+ // xxx.ets
+ import web_webview from '@ohos.web.webview'
+ @Entry
+ @Component
+ struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController()
+ @State mode: WebDarkMode = WebDarkMode.On
+ @State access: boolean = true
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .darkMode(this.mode)
+ .forceDarkAccess(this.access)
+ }
+ }
+ }
+ ```
+
+### pinchSmooth9+
+
+pinchSmooth(isEnabled: boolean)
+
+Sets whether to enable smooth pinch mode for the web page.
+
+**Parameters**
+
+| Name | Type| Mandatory| Default Value| Description |
+| --------- | -------- | ---- | ------ | -------------------------- |
+| isEnabled | boolean | Yes | false | Whether to enable smooth pinch mode for the web page.|
+
+**Example**
+
+ ```ts
+// xxx.ets
+import web_webview from '@ohos.web.webview'
+@Entry
+@Component
+struct WebComponent {
+ controller: web_webview.WebviewController = new web_webview.WebviewController()
+ build() {
+ Column() {
+ Web({ src: 'www.example.com', controller: this.controller })
+ .pinchSmooth(true)
+ }
+ }
+}
+ ```
+
## Events
The universal events are not supported.
@@ -998,7 +1227,7 @@ Triggered when **alert()** is invoked to display an alert dialog box on the web
| ------- | --------------------- | --------------- |
| 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. |
+| result | [JsResult](#jsresult) | User operation. |
**Return value**
@@ -1056,7 +1285,7 @@ Triggered when this page is about to exit after the user refreshes or closes the
| ------- | --------------------- | --------------- |
| 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. |
+| result | [JsResult](#jsresult) | User operation. |
**Return value**
@@ -1117,7 +1346,7 @@ Triggered when **confirm()** is invoked by the web page.
| ------- | --------------------- | --------------- |
| 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. |
+| result | [JsResult](#jsresult) | User operation. |
**Return value**
@@ -1177,7 +1406,7 @@ onPrompt(callback: (event?: { url: string; message: string; value: string; resul
| ------- | --------------------- | --------------- |
| 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. |
+| result | [JsResult](#jsresult) | User operation. |
**Return value**
@@ -1361,7 +1590,7 @@ Triggered when an HTTP error (the response code is greater than or equal to 400)
| Name | Type | Description |
| ------- | ---------------------------------------- | --------------- |
| request | [WebResourceRequest](#webresourcerequest) | Encapsulation of a web page request. |
-| error | [WebResourceError](#webresourceerror) | Encapsulation of a web page resource loading error.|
+| response | [WebResourceResponse](#webresourceresponse) | Encapsulation of a resource response.|
**Example**
@@ -1564,7 +1793,7 @@ Triggered when loading of the web page is complete. This API is used by an appli
}
```
-### onRenderExited
+### onRenderExited9+
onRenderExited(callback: (event?: { renderExitReason: RenderExitReason }) => void)
@@ -1831,7 +2060,7 @@ Invoked when an HTTP authentication request is received.
| Name | Type | Description |
| ------- | ------------------------------------ | ---------------- |
-| handler | [HttpAuthHandler](#httpauthhandler9) | The user's operation. |
+| handler | [HttpAuthHandler](#httpauthhandler9) | User operation. |
| host | string | Host to which HTTP authentication credentials apply.|
| realm | string | Realm to which HTTP authentication credentials apply. |
@@ -1900,7 +2129,7 @@ Invoked when an SSL error occurs during resource loading.
| Name | Type | Description |
| ------- | ------------------------------------ | -------------- |
-| handler | [SslErrorHandler](#sslerrorhandler9) | The user's operation.|
+| handler | [SslErrorHandler](#sslerrorhandler9) | User operation.|
| error | [SslError](#sslerror9) | Error code. |
**Example**
@@ -1945,7 +2174,7 @@ Invoked when an SSL error occurs during resource loading.
### onClientAuthenticationRequest9+
-onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array\, issuers : Array\}) => void)
+onClientAuthenticationRequest(callback: (event: {handler : ClientAuthenticationHandler, host : string, port : number, keyTypes : Array, issuers : Array}) => void)
Invoked when an SSL client certificate request is received.
@@ -1953,11 +2182,11 @@ Invoked when an SSL client certificate request is received.
| Name | Type | Description |
| -------- | ---------------------------------------- | --------------- |
-| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | The user's operation. |
+| handler | [ClientAuthenticationHandler](#clientauthenticationhandler9) | User operation. |
| host | string | Host name of the server that requests a certificate. |
| port | number | Port number of the server that requests a certificate. |
-| keyTypes | Array\ | Acceptable asymmetric private key types. |
-| issuers | Array\ | Issuer of the certificate that matches the private key.|
+| keyTypes | Array | Acceptable asymmetric private key types. |
+| issuers | Array | Issuer of the certificate that matches the private key.|
**Example**
```ts
@@ -2008,7 +2237,7 @@ Invoked when a permission request is received.
| Name | Type | Description |
| ------- | ---------------------------------------- | -------------- |
-| request | [PermissionRequest](#permissionrequest9) | The user's operation.|
+| request | [PermissionRequest](#permissionrequest9) | User operation.|
**Example**
@@ -2051,7 +2280,7 @@ Invoked when a permission request is received.
onContextMenuShow(callback: (event?: { param: WebContextMenuParam, result: WebContextMenuResult }) => boolean)
-Invoked when a context menu is displayed upon a long press on a specific element (such as an image or link).
+Shows a context menu after the user clicks the right mouse button or long presses a specific element, such as an image or a link.
**Parameters**
@@ -2131,7 +2360,7 @@ Registers a callback for receiving a request to obtain the geolocation informati
| Name | Type | Description |
| ----------- | ------------------------------- | -------------- |
| origin | string | Index of the origin. |
-| geolocation | [JsGeolocation](#jsgeolocation) | The user's operation.|
+| geolocation | [JsGeolocation](#jsgeolocation) | User operation.|
**Example**
@@ -2285,6 +2514,7 @@ Registers a callback for window creation.
```ts
// xxx.ets
+ import web_webview from '@ohos.web.webview'
@Entry
@Component
struct WebComponent {
@@ -2626,7 +2856,7 @@ Notifies the **\** component of the user's confirm operation in the dialog
## FullScreenExitHandler9+
-Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see onFullScreenEnter.
+Implements a **FullScreenExitHandler** object for listening for exiting full screen mode. For the sample code, see [onFullScreenEnter](#onfullscreenenter9).
### exitFullScreen9+
@@ -2830,15 +3060,15 @@ Obtains the MIME type of the resource response.
### setResponseData9+
-setResponseData(data: string)
+setResponseData(data: string | number)
Sets the data in the resource response.
**Parameters**
-| Name | Type | Mandatory | Default Value | Description |
-| ---- | ------ | ---- | ---- | ----------- |
-| data | string | Yes | - | Resource response data to set.|
+| Name| Type | Mandatory| Default Value| Description |
+| ------ | ---------------- | ---- | ------ | ------------------------------------------------------------ |
+| data | string \| number | Yes | - | Resource response data to set. When set to a number, the value indicates a file handle.|
### setResponseEncoding9+
@@ -2900,6 +3130,18 @@ Sets the status code of the resource response.
| ---- | ------ | ---- | ---- | ------------- |
| code | number | Yes | - | Status code to set.|
+### setResponseIsReady9+
+
+setResponseIsReady(IsReady: boolean)
+
+Sets whether the resource response data is ready.
+
+**Parameters**
+
+| Name | Type| Mandatory| Default Value| Description |
+| ------- | -------- | ---- | ------ | -------------------------- |
+| IsReady | boolean | Yes | true | Whether the resource response data is ready.|
+
## FileSelectorResult9+
Notifies the **\** component of the file selection result. For the sample code, see [onShowFileSelector](#onshowfileselector9).
@@ -3098,11 +3340,46 @@ Grants the permission for resources requested by the web page.
| Name | Type | Mandatory | Default Value | Description |
| --------- | --------------- | ---- | ---- | ------------- |
-| resources | Array\ | Yes | - | List of accessible resources requested by the web page.|
+| resources | Array\ | Yes | - | List of resources that can be requested by the web page with the permission to grant.|
+
+## ContextMenuSourceType9+
+| Name | Description |
+| -------------------- | ---------- |
+| None | Other event sources. |
+| Mouse | Mouse event. |
+| LongPress | Long press event. |
+
+## ContextMenuMediaType9+
+
+| Name | Description |
+| ------------ | ----------- |
+| None | Non-special media or other media types.|
+| Image | Image. |
+
+## ContextMenuInputFieldType9+
+
+| Name | Description |
+| ------------ | ----------- |
+| None | Non-input field. |
+| PlainText | Plain text field, such as the text, search, or email field. |
+| Password | Password field. |
+| Number | Numeric field. |
+| Telephone | Phone number field.|
+| Other | Field of any other type. |
+
+## ContextMenuEditStateFlags9+
+
+| Name | Description |
+| ------------ | ----------- |
+| NONE | Editing is not allowed. |
+| CAN_CUT | The cut operation is allowed. |
+| CAN_COPY | The copy operation is allowed. |
+| CAN_PASTE | The paste operation is allowed. |
+| CAN_SELECT_ALL | The select all operation is allowed.|
## WebContextMenuParam9+
-Provides the information about the context menu that is displayed when a page element is long pressed. For the sample code, see [onContextMenuShow](#oncontextmenushow9).
+Implements a context menu, which is displayed after the user clicks the right mouse button or long presses a specific element, such as an image or a link. For the sample code, see [onContextMenuShow](#oncontextmenushow9).
### x9+
@@ -3176,9 +3453,81 @@ Checks whether image content exists.
| ------- | ------------------------- |
| boolean | The value **true** means that there is image content in the element being long pressed, and **false** means the opposite.|
+### getMediaType9+
+
+getMediaType(): ContextMenuMediaType
+
+Obtains the media type of this web page element.
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- | ----------- |
+| [ContextMenuMediaType](#contextmenumediatype9) | Media type of the web page element.|
+
+### getSelectionText9+
+
+getSelectionText(): string
+
+Obtains the selected text.
+
+**Return value**
+
+| Type | Description |
+| ------- | ------------------------- |
+| string | Selected text for the context menu. If no text is selected, null is returned.|
+
+### getSourceType9+
+
+getSourceType(): ContextMenuSourceType
+
+Obtains the event source of the context menu.
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- | ----------- |
+| [ContextMenuSourceType](#contextmenusourcetype9) | Event source of the context menu.|
+
+### getInputFieldType9+
+
+getInputFieldType(): ContextMenuInputFieldType
+
+Obtains the input field type of this web page element.
+
+**Return value**
+
+| Type | Description |
+| ---------------------------------------- | ----------- |
+| [ContextMenuInputFieldType](#contextmenuinputfieldtype9) | Input field type.|
+
+### isEditable9+
+
+isEditable(): boolean
+
+Checks whether this web page element is editable.
+
+**Return value**
+
+| Type | Description |
+| ------- | ------------------------- |
+| boolean | Returns **true** if the web page element is editable; returns **false** otherwise.|
+
+### getEditStateFlags9+
+
+getEditStateFlags(): number
+
+Obtains the edit state flag of this web page element.
+
+**Return value**
+
+| Type | Description |
+| ------- | ------------------------- |
+| number | Edit state flag of the web page element. For details, see [ContextMenuEditStateFlags](#contextmenueditstateflags9).|
+
## WebContextMenuResult9+
-Implements a **WebContextMenuResult** object. For the sample code, see onContextMenuShow.
+Implements a **WebContextMenuResult** object. For the sample code, see [onContextMenuShow](#oncontextmenushow9).
### closeContextMenu9+
@@ -3192,6 +3541,30 @@ copyImage(): void
Copies the image specified in **WebContextMenuParam**.
+### copy9+
+
+copy(): void
+
+Performs the copy operation related to this context menu.
+
+### paste9+
+
+paste(): void
+
+Performs the paste operation related to this context menu.
+
+### cut9+
+
+cut(): void
+
+Performs the cut operation related to this context menu.
+
+### selectAll9+
+
+selectAll(): void
+
+Performs the select all operation related to this context menu.
+
## JsGeolocation
Implements the **PermissionRequest** object. For the sample code, see [onGeolocationShow Event](#ongeolocationshow).
@@ -3208,24 +3581,28 @@ Sets the geolocation permission status of a web page.
| ------ | ------- | ---- | ---- | ---------------------------------------- |
| origin | string | Yes | - | Index of the origin. |
| allow | boolean | Yes | - | Geolocation permission status. |
-| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. The **[GeolocationPermissions](#geolocationpermissions9)** API can be used to manage the geolocation permission status saved to the system.|
+| retain | boolean | Yes | - | Whether the geolocation permission status can be saved to the system. You can manage the geolocation permissions saved to the system through [GeolocationPermissions9+](../apis/js-apis-webview.md#geolocationpermissions).|
## WebController
Implements a **WebController** to control the behavior of the **\** component. A **WebController** can control only one **\** component, and the APIs in the **WebController** can be invoked only after it has been bound to the target **\** component.
+This API is deprecated since API version 9. You are advised to use [WebviewController9+](../apis/js-apis-webview.md#webviewcontroller).
+
### Creating an Object
```
webController: WebController = new WebController()
```
-### requestFocus
+### requestFocus(deprecated)
requestFocus()
Requests focus for this web page.
+This API is deprecated since API version 9. You are advised to use [requestFocus9+](../apis/js-apis-webview.md#requestfocus).
+
**Example**
```ts
@@ -3247,12 +3624,14 @@ Requests focus for this web page.
}
```
-### accessBackward
+### accessBackward(deprecated)
accessBackward(): boolean
Checks whether going to the previous page can be performed on the current page.
+This API is deprecated since API version 9. You are advised to use [accessBackward9+](../apis/js-apis-webview.md#accessbackward).
+
**Return value**
| Type | Description |
@@ -3281,12 +3660,14 @@ Checks whether going to the previous page can be performed on the current page.
}
```
-### accessForward
+### accessForward(deprecated)
accessForward(): boolean
Checks whether going to the next page can be performed on the current page.
+This API is deprecated since API version 9. You are advised to use [accessForward9+](../apis/js-apis-webview.md#accessforward).
+
**Return value**
| Type | Description |
@@ -3315,12 +3696,14 @@ Checks whether going to the next page can be performed on the current page.
}
```
-### accessStep
+### accessStep(deprecated)
accessStep(step: number): boolean
Performs a specific number of steps forward or backward from the current page.
+This API is deprecated since API version 9. You are advised to use [accessStep9+](../apis/js-apis-webview.md#accessstep).
+
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
@@ -3356,12 +3739,14 @@ Performs a specific number of steps forward or backward from the current page.
}
```
-### backward
+### backward(deprecated)
backward(): void
Goes to the previous page based on the history stack. This API is generally used together with **accessBackward**.
+This API is deprecated since API version 9. You are advised to use [backward9+](../apis/js-apis-webview.md#backward).
+
**Example**
```ts
@@ -3383,12 +3768,14 @@ Goes to the previous page based on the history stack. This API is generally used
}
```
-### forward
+### forward(deprecated)
forward(): void
Goes to the next page based on the history stack. This API is generally used together with **accessForward**.
+This API is deprecated since API version 9. You are advised to use [forward9+](../apis/js-apis-webview.md#forward).
+
**Example**
```ts
@@ -3444,12 +3831,14 @@ Performs a specific number of steps forward or backward on the current page base
}
```
-### deleteJavaScriptRegister
+### deleteJavaScriptRegister(deprecated)
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.
+This API is deprecated since API version 9. You are advised to use [deleteJavaScriptRegister9+](../apis/js-apis-webview.md#deletejavascriptregister).
+
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
@@ -3478,12 +3867,14 @@ Deletes a specific application JavaScript object that is registered with the win
}
```
-### getHitTest
+### getHitTest(deprecated)
getHitTest(): HitTestType
Obtains the element type of the area being clicked.
+This API is deprecated since API version 9. You are advised to use [getHitTest9+](../apis/js-apis-webview.md#gethittest).
+
**Return value**
| Type | Description |
@@ -3678,7 +4069,7 @@ Obtains the default user agent of the current web page.
}
```
-### loadData
+### loadData(deprecated)
loadData(options: { data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string })
@@ -3688,6 +4079,8 @@ 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**.
+This API is deprecated since API version 9. You are advised to use [loadData9+](../apis/js-apis-webview.md#loaddata).
+
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
@@ -3723,7 +4116,7 @@ If **baseUrl** is set to an HTTP or HTTPS URL, the encoded string will be proces
}
```
-### loadUrl
+### loadUrl(deprecated)
loadUrl(options: { url: string | Resource, headers?: Array\ })
@@ -3733,6 +4126,8 @@ The object injected through **loadUrl** is valid only in the current document. I
The object injected through **registerJavaScriptProxy** is still valid on a new page redirected through **loadUrl**.
+This API is deprecated since API version 9. You are advised to use [loadUrl9+](../apis/js-apis-webview.md#loadurl).
+
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
@@ -3761,12 +4156,14 @@ The object injected through **registerJavaScriptProxy** is still valid on a new
}
```
-### onActive
+### onActive(deprecated)
onActive(): void
Invoked when the **\** component enters the active state.
+This API is deprecated since API version 9. You are advised to use [onActive9+](../apis/js-apis-webview.md#onactive).
+
**Example**
```ts
@@ -3788,12 +4185,14 @@ Invoked when the **\** component enters the active state.
}
```
-### onInactive
+### onInactive(deprecated)
onInactive(): void
Invoked when the **\** component enters the inactive state.
+This API is deprecated since API version 9. You are advised to use [onInactive9+](../apis/js-apis-webview.md#oninactive).
+
**Example**
```ts
@@ -3815,11 +4214,13 @@ Invoked when the **\** component enters the inactive state.
}
```
-### zoom
+### zoom(deprecated)
zoom(factor: number): void
Sets a zoom factor for the current web page.
+This API is deprecated since API version 9. You are advised to use [zoom9+](../apis/js-apis-webview.md#zoom).
+
**Parameters**
| Name | Type | Mandatory | Description |
@@ -3914,12 +4315,14 @@ Zooms out of this web page by 20%.
}
```
-### refresh
+### refresh(deprecated)
refresh()
Invoked when the **\** component refreshes the web page.
+This API is deprecated since API version 9. You are advised to use [refresh9+](../apis/js-apis-webview.md#refresh).
+
**Example**
```ts
@@ -3941,11 +4344,13 @@ Invoked when the **\** component refreshes the web page.
}
```
-### registerJavaScriptProxy
+### registerJavaScriptProxy(deprecated)
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.
+Registers a JavaScript object with the window. APIs of this object can then be invoked in the window. You must invoke the [refresh](#refresh) API for the registration to take effect.
+
+This API is deprecated since API version 9. You are advised to use [registerJavaScriptProxy9+](../apis/js-apis-webview.md#registerjavascriptproxy).
**Parameters**
@@ -4007,12 +4412,14 @@ Registers a JavaScript object and invokes the methods of the object in the windo
```
-### runJavaScript
+### runJavaScript(deprecated)
runJavaScript(options: { script: string, callback?: (result: string) => void })
Executes a JavaScript script. This API uses an asynchronous callback to return the script execution result. **runJavaScript** can be invoked only after **loadUrl** is executed. For example, it can be invoked in **onPageEnd**.
+This API is deprecated since API version 9. You are advised to use [runJavaScript9+](../apis/js-apis-webview.md#runjavascript).
+
**Parameters**
| Name | Type | Mandatory | Default Value | Description |
@@ -4066,12 +4473,14 @@ Executes a JavaScript script. This API uses an asynchronous callback to return t
```
-### stop
+### stop(deprecated)
stop()
Stops page loading.
+This API is deprecated since API version 9. You are advised to use [stop9+](../apis/js-apis-webview.md#stop).
+
**Example**
```ts
@@ -4093,12 +4502,14 @@ Stops page loading.
}
```
-### clearHistory
+### clearHistory(deprecated)
clearHistory(): void
Clears the browsing history.
+This API is deprecated since API version 9. You are advised to use [clearHistory9+](../apis/js-apis-webview.md#clearhistory).
+
**Example**
```ts
@@ -4626,7 +5037,7 @@ Obtains the cookie value corresponding to the specified URL.
Column() {
Button('getCookie')
.onClick(() => {
- let value = webview.WebCookieManager.getCookie('www.example.com')
+ let value = web_webview.WebCookieManager.getCookie('www.example.com')
console.log("value: " + value)
})
Web({ src: 'www.example.com', controller: this.controller })
@@ -4676,44 +5087,10 @@ Sets a cookie value for the specified URL.
}
```
-### saveCookieSync9+
-saveCookieSync(): boolean
-
-Saves the cookies in the memory to the drive. This API returns the result synchronously.
-
-**Return value**
-
-| Type | Description |
-| ------- | -------------------- |
-| boolean | Operation result.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
-
- build() {
- Column() {
- Button('saveCookieSync')
- .onClick(() => {
- let result = web_webview.WebCookieManager.saveCookieSync()
- console.log("result: " + result)
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
### saveCookieAsync9+
saveCookieAsync(): Promise\
-Saves cookies in the memory to the drive. This API uses a promise to return the value.
+Saves the cookies in the memory to the drive. This API uses a promise to return the value.
**Return value**
@@ -4752,7 +5129,7 @@ Saves cookies in the memory to the drive. This API uses a promise to return the
### saveCookieAsync9+
saveCookieAsync(callback: AsyncCallback\): void
-Saves cookies in the memory to the drive. This API uses an asynchronous callback to return the result.
+Saves the cookies in the memory to the drive. This API uses an asynchronous callback to return the result.
**Parameters**
@@ -4998,158 +5375,7 @@ Deletes all session cookies.
Column() {
Button('deleteSessionCookie')
.onClick(() => {
- webview.WebCookieManager.deleteSessionCookie()
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
-## WebDataBase9+
-Implements the **WebDataBase** object.
-
-### existHttpAuthCredentials9+
-
-static existHttpAuthCredentials(): boolean
-
-Checks whether any saved HTTP authentication credentials exist. This API returns the result synchronously.
-
-**Return value**
-
-| Type | Description |
-| ------- | ---------------------------------------- |
-| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
-
- build() {
- Column() {
- Button('existHttpAuthCredentials')
- .onClick(() => {
- let result = web_webview.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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
-
- build() {
- Column() {
- Button('deleteHttpAuthCredentials')
- .onClick(() => {
- web_webview.WebDataBase.deleteHttpAuthCredentials()
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
-### getHttpAuthCredentials9+
-
-static getHttpAuthCredentials(host: string, realm: string): Array\
-
-Retrieves 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. |
-
-**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_webview from '@ohos.web.webview'
- @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_webview.WebDataBase.getHttpAuthCredentials(this.host, this.realm)
- console.log('num: ' + this.username_password.length)
- ForEach(this.username_password, (item) => {
- console.log('username_password: ' + item)
- }, item => item)
- })
- 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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- host: string = "www.spincast.org"
- realm: string = "protected example"
- build() {
- Column() {
- Button('saveHttpAuthCredentials')
- .onClick(() => {
- web_webview.WebDataBase.saveHttpAuthCredentials(this.host, this.realm, "Stromgol", "Laroche")
+ web_webview.WebCookieManager.deleteSessionCookie()
})
Web({ src: 'www.example.com', controller: this.controller })
}
@@ -5157,783 +5383,88 @@ Saves HTTP authentication credentials for a given host and realm. This API retur
}
```
-## GeolocationPermissions9+
-
-Implements a **GeolocationPermissions** object.
-
-### allowGeolocation9+
-
-static allowGeolocation(origin: string): void
-
-Allows the specified origin to use the geolocation information.
-
-**Parameters**
-
-| Name | Type | Mandatory | Default Value | Description |
-| ------ | ------ | ---- | ---- | ---------- |
-| origin | string | Yes | - | Index of the origin.|
-
-**Example**
+## MessageLevel
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "file:///"
- build() {
- Column() {
- Button('allowGeolocation')
- .onClick(() => {
- web_webview.GeolocationPermissions.allowGeolocation(this.origin)
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
+| Name | Description |
+| ----- | :---- |
+| Debug | Debug level.|
+| Error | Error level.|
+| Info | Information level.|
+| Log | Log level.|
+| Warn | Warning level. |
-### deleteGeolocation9+
+## RenderExitReason
-static deleteGeolocation(origin: string): void
+Enumerates the reasons why the rendering process exits.
-Clears the geolocation permission status of a specified origin.
+| 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. |
-**Parameters**
+## MixedMode
-| Name | Type | Mandatory | Default Value | Description |
-| ------ | ------ | ---- | ---- | ---------- |
-| origin | string | Yes | - | Index of the origin.|
+| 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. |
-**Example**
+## 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. |
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "file:///"
- build() {
- Column() {
- Button('deleteGeolocation')
- .onClick(() => {
- web_webview.GeolocationPermissions.deleteGeolocation(this.origin)
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
+## 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. |
-### deleteAllGeolocation9+
+ ## HitTestType
-static deleteAllGeolocation(): void
+| 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. |
+| Phone | Phone number. |
+| Unknown | Unknown content. |
-Clears the geolocation permission status of all sources.
+## SslError9+
-**Example**
+Enumerates the error codes returned by **onSslErrorEventReceive** API.
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- build() {
- Column() {
- Button('deleteAllGeolocation')
- .onClick(() => {
- web_webview.GeolocationPermissions.deleteAllGeolocation()
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
+| Name | Description |
+| ------------ | ----------- |
+| Invalid | Minor error. |
+| HostMismatch | The host name does not match. |
+| DateInvalid | The certificate has an invalid date. |
+| Untrusted | The certificate issuer is not trusted.|
-### getAccessibleGeolocation9+
+## ProtectedResourceType9+
-static getAccessibleGeolocation(origin: string, callback: AsyncCallback\): void
+| Name | Description | Remarks |
+| --------- | ------------- | -------------------------- |
+| MidiSysex | MIDI SYSEX resource.| Currently, only permission events can be reported. MIDI devices are not yet supported.|
-Obtains the geolocation permission status of the specified source. This API uses an asynchronous callback to return the result.
-
-**Parameters**
-
-| Name | Type | Mandatory | Default Value | Description |
-| -------- | ------------------------ | ---- | ---- | ---------------------------------------- |
-| origin | string | Yes | - | Index of the origin. |
-| callback | AsyncCallback\ | Yes | - | Callback used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "file:///"
- build() {
- Column() {
- Button('getAccessibleGeolocationAsync')
- .onClick(() => {
- web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin, (error, result) => {
- if (error) {
- console.log('getAccessibleGeolocationAsync error: ' + JSON.stringify(error))
- return
- }
- console.log('getAccessibleGeolocationAsync result: ' + result)
- })
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
-### getAccessibleGeolocation9+
-
-static getAccessibleGeolocation(origin: string): Promise\
-
-Obtains the geolocation permission status of the specified source. This API uses a promise to return the result.
-
-**Parameters**
-
-| Name | Type | Mandatory | Default Value | Description |
-| ------ | ------ | ---- | ---- | ---------- |
-| origin | string | Yes | - | Index of the origin.|
-
-**Return value**
-
-| Type | Description |
-| ------------------ | ---------------------------------------- |
-| Promise\ | Promise used to return the geolocation permission status of the specified source. If the operation is successful, the value **true** means that the geolocation permission is granted, and **false** means the opposite. If the operation fails, the geolocation permission status of the specified source is not found.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "file:///"
- build() {
- Column() {
- Button('getAccessibleGeolocationPromise')
- .onClick(() => {
- web_webview.GeolocationPermissions.getAccessibleGeolocation(this.origin).then(result => {
- console.log('getAccessibleGeolocationPromise result: ' + result)
- }).catch(error => {
- console.log('getAccessibleGeolocationPromise error: ' + JSON.stringify(error))
- })
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
-### getStoredGeolocation9+
-
-static getStoredGeolocation(callback: AsyncCallback\\>): void
-
-Obtains the geolocation permission status of all sources. This API uses an asynchronous callback to return the result.
-
-**Parameters**
-
-| Name | Type | Mandatory | Default Value | Description |
-| -------- | -------------------------------- | ---- | ---- | -------------------- |
-| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- build() {
- Column() {
- Button('getStoredGeolocationAsync')
- .onClick(() => {
- web_webview.GeolocationPermissions.getStoredGeolocation((error, origins) => {
- if (error) {
- console.log('getStoredGeolocationAsync error: ' + JSON.stringify(error))
- return
- }
- let origins_str: string = origins.join()
- console.log('getStoredGeolocationAsync origins: ' + origins_str)
- })
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
-### getStoredGeolocation9+
-
-static getStoredGeolocation(): Promise\\>
-
-Obtains the geolocation permission status of all sources. This API uses a promise to return the result.
-
-**Parameters**
-
-| Name | Type | Mandatory | Default Value | Description |
-| -------- | -------------------------------- | ---- | ---- | -------------------- |
-| callback | AsyncCallback\\> | Yes | - | Callback used to return the geolocation permission status of all sources.|
-
-**Return value**
-
-| Type | Description |
-| -------------------------- | -------------------------------- |
-| Promise\\> | Promise used to return the geolocation permission status of all sources.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- build() {
- Column() {
- Button('getStoredGeolocationPromise')
- .onClick(() => {
- web_webview.GeolocationPermissions.getStoredGeolocation().then(origins => {
- let origins_str: string = origins.join()
- console.log('getStoredGeolocationPromise origins: ' + origins_str)
- }).catch(error => {
- console.log('getStoredGeolocationPromise error: ' + JSON.stringify(error))
- })
- })
- 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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- build() {
- Column() {
- Button('deleteAllData')
- .onClick(() => {
- web_webview.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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "origin"
- build() {
- Column() {
- Button('getHttpAuthCredentials')
- .onClick(() => {
- web_webview.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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "origin"
- build() {
- Column() {
- Button('getOrigins')
- .onClick(() => {
- web_webview.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)
- }
- }
- }
- ```
-
-### 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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "origin"
- build() {
- Column() {
- Button('getOrigins')
- .onClick(() => {
- web_webview.WebStorage.getOrigins()
- .then(origins => {
- for (let i = 0; i < origins.length; i++) {
- console.log('origin: ' + origins[i].origin)
- console.log('usage: ' + origins[i].usage)
- console.log('quota: ' + origins[i].quota)
- }
- })
- .catch(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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- origin: string = "origin"
- build() {
- Column() {
- Button('getOriginQuota')
- .onClick(() => {
- web_webview.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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController();
- origin: string = "origin"
- build() {
- Column() {
- Button('getOriginQuota')
- .onClick(() => {
- web_webview.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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController();
- origin: string = "origin"
- build() {
- Column() {
- Button('getOriginUsage')
- .onClick(() => {
- web_webview.WebStorage.getOriginUsage(this.origin, (error, usage) => {
- if (error) {
- console.log('error: ' + error)
- return
- }
- console.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_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController();
- origin: string = "origin"
- build() {
- Column() {
- Button('getOriginQuota')
- .onClick(() => {
- web_webview.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)
- }
- }
- }
- ```
-
-## 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
-
-| Name | Description |
-| ----- | :---- |
-| Debug | Debug level.|
-| Error | Error level.|
-| Info | Information level.|
-| Log | Log level.|
-| Warn | Warning level. |
-
-## RenderExitReason
-
-Enumerates the reasons 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
+## WebDarkMode9+
| 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. |
-| Phone | Phone number. |
-| Unknown | Unknown content. |
-
-## SslError9+
-
-Enumerates the error codes returned by **onSslErrorEventReceive** API.
-
-| Name | Description |
-| ------------ | ----------- |
-| Invalid | Minor error. |
-| HostMismatch | The host name does not match. |
-| DateInvalid | The certificate has an invalid date. |
-| Untrusted | The certificate issuer is not trusted.|
-
-## ProtectedResourceType9+
-
-| Name | Description | Remarks |
-| --------- | ------------- | -------------------------- |
-| MidiSysex | MIDI SYSEX resource.| 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
-
-```
-webController: WebController = new WebController();
-webAsyncController: WebAsyncController = new WebAsyncController(webController);
-```
-
-### storeWebArchive9+
-
-storeWebArchive(baseName: string, autoName: boolean, callback: AsyncCallback): void
-
-Stores this 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 **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
-| callback | AsyncCallback | Yes | Callback used to return the save path if the operation is successful and null otherwise.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController()
- build() {
- Column() {
- Button('saveWebArchive')
- .onClick(() => {
- let webAsyncController = new web_webview.WebAsyncController(this.controller)
- webAsyncController.storeWebArchive("/data/storage/el2/base/", true, (filename) => {
- if (filename != null) {
- console.info(`save web archive success: ${filename}`)
- }
- })
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
-
-### storeWebArchive9+
-
-storeWebArchive(baseName: string, autoName: boolean): Promise
-
-Stores this web page. This API uses a promise 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 **false** means not to automatically generate a file name.
The value **true** means to automatically generate a file name based on the URL of current page and the **baseName** value. In this case, **baseName** is regarded as a directory.
-
-**Return value**
-
-| Type | Description |
-| --------------- | -------------------------------- |
-| Promise | Promise used to return the save path if the operation is successful and null otherwise.|
-
-**Example**
-
- ```ts
- // xxx.ets
- import web_webview from '@ohos.web.webview'
- @Entry
- @Component
- struct WebComponent {
- controller: WebController = new WebController();
- build() {
- Column() {
- Button('saveWebArchive')
- .onClick(() => {
- let webAsyncController = new web_webview.WebAsyncController(this.controller);
- webAsyncController.storeWebArchive("/data/storage/el2/base/", true)
- .then(filename => {
- if (filename != null) {
- console.info(`save web archive success: ${filename}`)
- }
- })
- })
- Web({ src: 'www.example.com', controller: this.controller })
- }
- }
- }
- ```
+| Off | The web dark mode is disabled. |
+| On | The web dark mode is enabled. |
+| Auto | The web dark mode setting follows the system settings. |
## WebMessagePort9+
@@ -6158,7 +5689,7 @@ Sets the message port in this object. For the complete sample code, see [postMes
## DataResubmissionHandler9+
-Implements the **DataResubmissionHandler** for resubmitting or canceling the web form data.
+Implements the **DataResubmissionHandler** object for resubmitting or canceling the web form data.
### resend9+
diff --git a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md
index 8425cf29444183671c4fd8e3389bd0ffa28840f9..a603c54bc5f16e877420e80c1714ac16f70e2123 100644
--- a/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md
+++ b/en/application-dev/reference/arkui-ts/ts-universal-attributes-location.md
@@ -17,7 +17,7 @@ The location attributes set the alignment mode, layout direction, and position o
| position | [Position](ts-types.md#position8) | Offset of the component's upper left corner relative to the parent component's upper left corner. This offset is expressed using absolute values. When laying out components, this attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.|
| markAnchor | [Position](ts-types.md#position8) | Anchor point of the component for positioning. The upper left corner of the component is used as the reference point for offset. Generally, this attribute is used together with the **position** and **offset** attributes. When used independently, this attribute is similar to **offset**.
Default value:
{
x: 0,
y: 0
} |
| offset | [Position](ts-types.md#position8) | Offset of the component relative to itself. This offset is expressed using relative values. This attribute does not affect the layout of the parent component. It only adjusts the component position during drawing.
Default value:
{
x: 0,
y: 0
} |
-| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container.
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.|
+| alignRules9+ | {
left?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
right?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
middle?: { anchor: string, align: [HorizontalAlign](ts-appendix-enums.md#horizontalalign) };
top?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
bottom?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) };
center?: { anchor: string, align: [VerticalAlign](ts-appendix-enums.md#verticalalign) }
} | Alignment rules relative to the container. This attribute is valid only when the container is [\](ts-container-relativecontainer.md).
- **left**: left-aligned.
- **right**: right-aligned.
- **middle**: center-aligned.
- **top**: top-aligned.
- **bottom**: bottom-aligned.
- **center**: center-aligned.
**NOTE**
- **anchor**: ID of the component that functions as the anchor point.
- **align**: alignment mode relative to the anchor component.|
## Example
diff --git a/en/application-dev/reference/errorcodes/Readme-EN.md b/en/application-dev/reference/errorcodes/Readme-EN.md
index b286cbf232d6d334444b164117fa289b79f9a6c4..28669ef9f2e4955e785462d935468bd519fd2931 100644
--- a/en/application-dev/reference/errorcodes/Readme-EN.md
+++ b/en/application-dev/reference/errorcodes/Readme-EN.md
@@ -33,8 +33,11 @@
- Security
- [Ability Access Control Error Codes](errorcode-access-token.md)
- [HUKS Error Codes](errorcode-huks.md)
+ - [User Authentication Error Codes](errorcode-useriam.md)
- Data Management
- [RDB Error Codes](errorcode-data-rdb.md)
+ - [DataShare Error Codes](errorcode-datashare.md)
+ - [Distributed Data Object Error Codes](errorcode-distributed-dataObject.md)
- [Distributed KV Store Error Codes](errorcode-distributedKVStore.md)
- [Preferences Error Codes](errorcode-preferences.md)
- File Management
diff --git a/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md
new file mode 100644
index 0000000000000000000000000000000000000000..0ebad934ac37ea27b349fa9e2b0c0d4941f83ca3
--- /dev/null
+++ b/en/application-dev/reference/errorcodes/errorcode-distributed-dataObject.md
@@ -0,0 +1,19 @@
+# Distributed Data Object Error Codes
+
+## 15400001 Failed to Create the In-Memory Database
+
+**Error Message**
+
+Create table failed.
+
+**Description**
+
+The in-memory database fails to be created.
+
+**Possible Causes**
+
+An object with the same session ID already exists.
+
+**Solution**
+
+Check for the object has been added to the same session.
diff --git a/en/application-dev/reference/errorcodes/errorcode-useriam.md b/en/application-dev/reference/errorcodes/errorcode-useriam.md
new file mode 100644
index 0000000000000000000000000000000000000000..2e84641a549af91c9101e94da86b54cf0db9d712
--- /dev/null
+++ b/en/application-dev/reference/errorcodes/errorcode-useriam.md
@@ -0,0 +1,163 @@
+# User Authentication Error Codes
+
+## 201 Permission Verification Failed
+
+For details, see [Universal Error Codes](./errorcode-universal.md).
+
+## 202 Invoker Is Not a System Application
+
+For details, see [Universal Error Codes](./errorcode-universal.md).
+
+## 401 Parameter Check Failed.
+
+For details, see [Universal Error Codes](./errorcode-universal.md).
+
+## 12500001 Authentication Failed
+
+**Error Message**
+
+Authentication failed.
+
+**Possible Causes**
+
+The credential does not match the credential enrolled.
+
+**Solution**
+
+Initiate authentication again.
+
+## 12500002 General Operation Error
+
+**Error Message**
+
+General operation error.
+
+**Possible Causes**
+
+1. An error occurs when the NAPI layer parses parameters.
+2. The process of the user authentication service is not started.
+3. The proxy client fails to write data over IPC.
+4. The stub server fails to parse data over IPC.
+5. The driver service is not obtained.
+
+**Solution**
+
+Call the API again later or restart the device.
+
+## 12500003 Authentication Canceled
+
+**Error Message**
+
+Authentication canceled.
+
+**Possible Causes**
+
+The authentication operation has been canceled.
+
+**Solution**
+
+Initiate the authentication again.
+
+## 12500004 Authentication Timed Out
+
+**Error Message**
+
+Authentication timeout.
+
+**Possible Causes**
+
+The authentication is not complete within the specified time.
+
+**Solution**
+
+Initiate the authentication again.
+
+## 12500005 Unsupported Authentication Type
+
+**Error Message**
+
+The authentication type is not supported.
+
+**Possible Causes**
+
+1. The input authentication type parameter is not supported. For example, if the authentication type passed in **getAvailableStatus** of the **userAuth** module is not **FACE** or **FINGERPRINT**, error code 12500005 is returned.
+2. The device does not support the authentication type. For example, if fingerprint authentication is initiated on a device that has no fingerprint sensor, error code 12500005 is returned.
+
+**Solution**
+
+Check the authentication type parameter and call the API again.
+
+## 12500006 Unsupported Authentication Trust Level
+
+**Error Message**
+
+The authentication trust level is not supported.
+
+**Possible Causes**
+
+1. The **authTrustLevel** value in **getAvailableStatus** or **getAuthInstance** of the **userAuth** module is not in the range [ATL1, ATL2, ATL3, ATL4].
+2. The device does not support the authentication trust level. For example, if facial authentication for payment is initiated on a device that has only 2D cameras, error code 12500006 is returned.
+
+**Solution**
+
+Check that the **authTrustLevel** passed in is within the value range, and the device supports the specified authentication trust level.
+
+## 12500007 Authentication Service Unavailable
+
+**Error Message**
+
+Authentication service is busy.
+
+**Possible Causes**
+
+Another authentication is initiated when the current authentication has not been finished yet.
+
+**Solution**
+
+Initiate authentication again later.
+
+## 12500009 Authentication Locked
+
+**Error Message**
+
+Authentication is lockout.
+
+**Possible Causes**
+
+The number of authentication failures exceeds the limit.
+
+**Solution**
+
+Initiate authentication later.
+
+## 12500010 Credential Not Enrolled
+
+**Error Message**
+
+The type of credential has not been enrolled.
+
+**Possible Causes**
+
+The **authType** parameter set in **getAvailableStatus** of the **userAuth** module is **FACE**, but no facial credential is enrolled in the device.
+**start()** is called to initiate facial authentication, but no facial credential is enrolled in the device.
+
+**Solution**
+
+Check that the related type of credential has been enrolled in the device.
+
+## 12700001 Failed to Enroll Faces
+
+**Error Message**
+
+The operation is failed.
+
+**Possible Causes**
+
+1. The facial authentication service is not started when **setSurfaceId()** of the **userAuth** module is called.
+2. The proxy client fails to write data over IPC.
+3. The stub server fails to parse data over IPC.
+4. An error occurs when the facial authentication driver is invoked.
+
+**Solution**
+
+Call the API again later or restart the device.
diff --git a/en/application-dev/security/cryptoFramework-guidelines.md b/en/application-dev/security/cryptoFramework-guidelines.md
index 35784280547f6f5064fc13f15d651801ea0d0b02..1d61382eb57babf5a33a0768a2e0248307b223d5 100644
--- a/en/application-dev/security/cryptoFramework-guidelines.md
+++ b/en/application-dev/security/cryptoFramework-guidelines.md
@@ -32,8 +32,8 @@ The table below describes the APIs used in this guide.
|AsyKeyGenerator|generateKeyPair() : Promise\|Generates an asymmetric key pair randomly. This API uses a promise to return the result.|
|SymKeyGenerator|generateSymKey(callback : AsyncCallback\) : void|Generates a symmetric key randomly. This API uses an asynchronous callback to return the result.|
|SymKeyGenerator|generateSymKey() : Promise\|Generates a symmetric key randomly. This API uses a promise to return the result.|
-| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.) |
-| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary public key and private key data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.) |
+| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob, callback : AsyncCallback\) : void | Converts binary data into a key pair. This API uses an asynchronous callback to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the return **KeyPair** instance contains only the public or private key.)|
+| AsyKeyGenerator | convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\ | Converts the binary data into a key pair. This API uses a promise to return the result.
(**pubKey** or **priKey** can be **null**. That is, you can pass in only **pubKey** or **priKey**. As a result, the returned **KeyPair** instance contains only the public or private key.)|
| SymKeyGenerator | convertKey(key : DataBlob, callback : AsyncCallback\) : void| Converts binary data into a symmetric key. This API uses an asynchronous callback to return the result.|
| SymKeyGenerator |convertKey(pubKey : DataBlob, priKey : DataBlob) : Promise\| Converts binary data into a symmetric key. This API uses a promise to return the result.|
| Key | getEncoded() : DataBlob; | Obtains the binary data of a key. (The child class instances of **Key** include **SymKey**, **PubKey**, and **PriKey**.)|
@@ -264,14 +264,14 @@ function stringToUint8Array(str) {
return new Uint8Array(arr);
}
-// Convert byte streams into strings in plaintext.
+// Output the byte streams in hexadecimal format.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
-// Output the byte streams in hexadecimal format.
+// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
@@ -383,14 +383,14 @@ function stringToUint8Array(str) {
return new Uint8Array(arr);
}
-// Convert byte streams into strings in plaintext.
+// Output the byte streams in hexadecimal format.
function uint8ArrayToShowStr(uint8Array) {
return Array.prototype.map
.call(uint8Array, (x) => ('00' + x.toString(16)).slice(-2))
.join('');
}
-// Output the byte streams in hexadecimal format.
+// Convert byte streams into strings in plaintext.
function uint8ArrayToString(array) {
let arrayString = '';
for (let i = 0; i < array.length; i++) {
@@ -500,7 +500,7 @@ Example 2: Encrypt and decrypt data using an asymmetric key pair.
Call **createCipher()** to create a **Cipher** instance, and set the key and encryption/decryption mode.
-3. Perform encryption and decryption operations.
+3. Perform encryption and decryption operations.
Call **doFinal()** provided by the **Cipher** instance to encrypt data or decrypt data.
@@ -573,38 +573,24 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
|Sign|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Sign** instance. This API uses a promise to return the result.|
|Sign|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signing. This API uses an asynchronous callback to return the result.|
|Sign|update(data : DataBlob) : Promise\|Updates the data for signing. This API uses a promise to return the result.|
-|Sign|sign(data : DataBlob, callback : AsyncCallback) : void|Signs the data. This API uses an asynchronous callback to return the result.|
-|Sign|sign(data : DataBlob) : Promise|Signs the data. This API uses a promise to return the result.|
+|Sign|sign(data : DataBlob, callback : AsyncCallback\) : void|Signs the data. This API uses an asynchronous callback to return the result.|
+|Sign|sign(data : DataBlob) : Promise\|Signs the data. This API uses a promise to return the result.|
|cryptoFramework|function createVerify(algName : string) : Verify|Creates a **Verify** instance.|
|Verify|init(priKey : PriKey, callback : AsyncCallback\) : void|Sets a key and initializes the **Verify** instance. This API uses an asynchronous callback to return the result.|
|Verify|init(priKey : PriKey) : Promise\|Sets a key and initializes the **Verify** instance. This API uses a promise to return the result.|
|Verify|update(data : DataBlob, callback : AsyncCallback\) : void|Updates the data for signature verification. This API uses an asynchronous callback to return the result.|
|Verify|update(data : DataBlob) : Promise\|Updates the data for signature verification. This API uses a promise to return the result.|
-|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback) : void|Verifies the signature. This API uses an asynchronous callback to return the result.|
-|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise|Verifies the signature. This API uses a promise to return the result.|
+|Verify|verify(data : DataBlob, signatureData : DataBlob, callback : AsyncCallback\) : void|Verifies the signature. This API uses an asynchronous callback to return the result.|
+|Verify|verify(data : DataBlob, signatureData : DataBlob) : Promise\|Verifies the signature. This API uses a promise to return the result.|
**How to Develop**
Example 1: Use RSA to sign data and verify the signature.
-1. Generate an RSA key pair.
-
- Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair.
-
-2. Create a **Sign** instance.
-
- Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
-
-3. Generate a signature.
-
- Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature.
-
-4. Create a **Verify** instance.
-
- Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
-
-5. Verify the signature.
-
- Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature.
+1. Generate an RSA key pair.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an RSA asymmetric key pair.
+2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
+3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **sign()** to generate a signature.
+4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
+5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **verify()** to verify the signature.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
@@ -684,25 +670,11 @@ function verifyMessageCallback() {
```
Example 2: Using ECC to sign data and verify the signature.
-1. Generate an ECC key.
-
- Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
-
-2. Create a **Sign** instance.
-
- Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
-
-3. Generate a signature.
-
- Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature.
-
-4. Create a **Verify** instance.
-
- Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
-
-5. Verify the signature.
-
- Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature.
+1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
+2. Create a **Sign** instance.
Call **createSign()** to create a **Sign** instance, initialize the **Sign** instance, and set a private key for signing.
+3. Generate a signature.
Call **update()** provided by the **Sign** class to add the data for signing and call **doFinal()** to generate a signature.
+4. Create a **Verify** instance.
Call **createVerify()** to create a **Verify** instance, initialize the instance, and set a public key for signature verification.
+5. Verify the signature.
Call **update()** provided by the **Verify** class to add signature data and call **doFinal()** to verify the signature.
```javascript
import cryptoFramework from "@ohos.security.cryptoFramework"
@@ -792,7 +764,7 @@ Typical message digest operations involve the following:
1. Create an **Md** instance.
2. Add one or more segments of data for generating a digest.
-3. Compute a digest.
+3. Compute a digest.
4. Obtain the algorithm and length of a digest.
**Available APIs**
@@ -802,10 +774,10 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | -------------------------------------------------- |
| cryptoFramework | function createMd(algName : string) : Md; | Creates an **Md** instance. |
-| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.|
-| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. |
-| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. |
-| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. |
+| Md | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for a digest. This API uses an asynchronous callback to return the result.|
+| Md | update(input : DataBlob) : Promise\; | Updates the data for a digest. This API uses a promise to return the result. |
+| Md | digest(callback : AsyncCallback\) : void; | Generates the digest. This API uses an asynchronous callback to return the result. |
+| Md | digest() : Promise\; | Generates the digest. This API uses a promise to return the result. |
| Md | getMdLength() : number; | Obtains the digest length based on the specified digest algorithm. |
| Md | readonly algName : string; | Obtains the digest algorithm. |
@@ -907,10 +879,7 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
**How to Develop**
-1. Generate an ECC key.
-
- Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
-
+1. Generate an ECC key.
Call **createAsyKeyGenerator()** to create an **AsyKeyGenerator** instance and generate an ECC asymmetric key pair.
2. Generate a shared secret by using the private and public ECC keys.
```javascript
@@ -966,15 +935,15 @@ For details about the APIs, see [Crypto Framework](../reference/apis/js-apis-cry
| Instance | API | Description |
| --------------- | ------------------------------------------------------------ | --------------------------------------------------- |
-| cryptoFramework | function createMac(algName : string) : Md; | Creates a **Mac** instance. |
-| Mac | init(key : SymKey, callback : AsyncCallback\) : void; | Initializes the MAC operation. This API uses an asynchronous callback to return the result.|
-| Mac | init(key : SymKey) : Promise\; | Initializes the MAC operation. This API uses a promise to return the result. |
-| Mac | update(input : DataBlob, callback : AsyncCallback\) : void; | Updates the data for the MAC operation. This API uses an asynchronous callback to return the result. |
-| Mac | update(input : DataBlob) : Promise\; | Updates the data for the MAC operation. This API uses a promise to return the result. |
-| Mac | doFinal(callback : AsyncCallback\) : void; | Finalizes the MAC operation to generate a MAC. This API uses an asynchronous callback to return the result. |
-| Mac | doFinal() : Promise\; | Finalizes the MAC operation to generate a MAC. This API uses a promise to return the result. |
+| cryptoFramework | function createMac(algName : string) : Mac; | Creates a **Mac** instance. |
+| Mac | init(key : SymKey, callback : AsyncCallback\