The Network 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.
> **NOTE**
> **Note:**
> To maximize the application running efficiency, most API calls are called asynchronously in callback or promise mode. The following code examples use the callback mode. For details about the APIs, see [sms API Reference](../reference/apis/js-apis-net-sharing.md).
## Basic Concepts
- Wi-Fi sharing: Shares the network through a Wi-Fi hotspot.
- Bluetooth sharing: Shares the network through Bluetooth.
- USB tethering: Shares the network using a USB flash drive.
## **Constraints**
- Programming language: C++ and JS
- System: Linux kernel
- 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.
## When to Use
Typical network sharing scenarios are as follows:
- Enabling network sharing
- Enabling Network Sharing
- Disabling network sharing
- Obtaining the data traffic of the shared network
The following describes the development procedure specific to each application scenario.
## Available APIs
For the complete list of APIs and example code, see [Network Sharing](../reference/apis/js-apis-net-sharing.md).
| Type| API| Description|
...
...
@@ -54,18 +61,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js
// Import the sharing namespace from @ohos.net.sharing.
importsharingfrom'@ohos.net.sharing'
importsharingfrom'@ohos.net.sharing'
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange',(error,data)=>{
// Subscribe to network sharing state changes.
sharing.on('sharingStateChange',(error,data)=>{
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
});
// Call startSharing to start network sharing of the specified type.
@@ -13,10 +13,10 @@ The Socket Connection module allows an application to transmit data over a Socke
## When to Use
Applications transmit data over TCP, UDP, or TLSSocket connections. The main application scenarios are as follows:
Applications transmit data over TCP, UDP, or TLSSocket connections. The main application scenarios are as follows:
- Implementing data transmission over TCP/UDPSocket connections
- Implementing encrypted data transmission over TLSSocket connections
- Implementing data transmission over TCP/UDPSocket connections
- Implementing encrypted data transmission over TLSSocket connections
## Available APIs
...
...
@@ -40,12 +40,12 @@ Socket connection functions are mainly implemented by the **socket** module. The
| off(type: 'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type: 'error') | Subscribes to **error** events of the Socket connection.|
| off(type: 'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type: 'listening') | Subscribes to **listening** events of the UDPSocket connection. |
| off(type: 'listening') | Unsubscribes from **listening** events of the UDPSocket connection. |
| on(type: 'connect') | Subscribes to **connect** events of the TCPSocket connection. |
| off(type: 'connect') | Unsubscribes from **connect** events of the TCPSocket connection.|
| on(type: 'listening') | Subscribes to **listening** events of the UDPSocket connection. |
| off(type: 'listening') | Unsubscribes from **listening** events of the UDPSocket connection. |
| on(type: 'connect') | Subscribes to **connect** events of the TCPSocket connection. |
| off(type: 'connect') | Unsubscribes from **connect** events of the TCPSocket connection.|
TLSSocket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
TLSSocket connection functions are mainly provided by the **tls_socket** module. The following table describes the related APIs.
| API| Description|
| -------- | -------- |
...
...
@@ -56,28 +56,28 @@ TLS Socket connection functions are mainly provided by the **tls_socket** module
| getCertificate() | Obtains an object representing the local certificate.|
| getCipherSuite() | Obtains a list containing information about the negotiated cipher suite.|
| getProtocol() | Obtains a string containing the SSL/TLS protocol version negotiated for the current connection.|
| getRemoteAddress() | Obtains the peer address of the TLSSocket connection.|
| getRemoteAddress() | Obtains the peer address of the TLSSocket connection.|
| getRemoteCertificate() | Obtains an object representing a peer certificate.|
| getSignatureAlgorithms() | Obtains a list containing signature algorithms shared between the server and client, in descending order of priority.|
| getState() | Obtains the TLSSocket connection status.|
| off(type: 'close') | Unsubscribes from **close** events of the TLSSocket connection.|
| off(type: 'error') | Unsubscribes from **error** events of the TLSSocket connection.|
| off(type: 'message') | Unsubscribes from **message** events of the TLSSocket connection.|
| on(type: 'close') | Subscribes to **close** events of the TLSSocket connection.|
| on(type: 'error') | Subscribes to **error** events of the TLSSocket connection.|
| on(type: 'message') | Subscribes to **message** events of the TLSSocket connection.|
| getState() | Obtains the TLSSocket connection status.|
| off(type: 'close') | Unsubscribes from **close** events of the TLSSocket connection.|
| off(type: 'error') | Unsubscribes from **error** events of the TLSSocket connection.|
| off(type: 'message') | Unsubscribes from **message** events of the TLSSocket connection.|
| on(type: 'close') | Subscribes to **close** events of the TLSSocket connection.|
| on(type: 'error') | Subscribes to **error** events of the TLSSocket connection.|
| on(type: 'message') | Subscribes to **message** events of the TLSSocket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLSSocket connection.|
| setExtraOptions() | Sets other properties of the TLSSocket connection.|
## Transmitting Data over TCP/UDPSocket Connections
## Transmitting Data over TCP/UDPSocket Connections
The implementation is similar for UDP Socket and TCP Socket connections. The following uses data transmission over a TCP Socket connection as an example.
The implementation is similar for UDPSocket and TCPSocket connections. The following uses data transmission over a TCPSocket connection as an example.
1. Import the required **socket** module.
2. Create a **TCPSocket** object.
3. (Optional) Subscribe to TCPSocket connection events.
3. (Optional) Subscribe to TCPSocket connection events.
4. Bind the IP address and port number. The port number can be specified or randomly allocated by the system.
...
...
@@ -85,7 +85,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
6. Send data.
7. Enable the TCPSocket connection to be automatically closed after use.
7. Enable the TCPSocket connection to be automatically closed after use.
```js
importsocketfrom'@ohos.net.socket'
...
...
@@ -93,7 +93,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
// Create a TCPSocket object.
lettcp=socket.constructTCPSocketInstance();
// Subscribe to TCPSocket connection events.
// Subscribe to TCPSocket connection events.
tcp.on('message',value=>{
console.log("on message")
letbuffer=value.message
...
...
@@ -152,7 +152,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
});
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
setTimeout(()=>{
tcp.close((err)=>{
console.log('close socket.')
...
...
@@ -163,11 +163,11 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
},30*1000);
```
## Implementing Encrypted Data Transmission over TLS Socket Connections
## Implementing encrypted data transmission over TLSSocket connections
### How to Develop
TLSSocket connection process on the client:
TLSSocket connection process on the client:
1. Import the required **socket** module.
...
...
@@ -177,20 +177,18 @@ TLS Socket connection process on the client:
4. Create a **TLSSocket** object.
5. (Optional) Subscribe to TLSSocket connection events.
5. (Optional) Subscribe to TLSSocket connection events.
6. Send data.
7. Enable the TLSSocket connection to be automatically closed after use.
7. Enable the TLSSocket connection to be automatically closed after use.
```js
importsocketfrom'@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
lettlsTwoWay=socket.constructTLSSocketInstance();
// Create a TLSSocket connection (for two-way authentication).
lettlsTwoWay=socket.constructTLSSocketInstance();
// Subscribe to TLS Socket connection events.
tlsTwoWay.on('message',value=>{
// Subscribe to TLSSocket connection events.
tlsTwoWay.on('message',value=>{
console.log("on message")
letbuffer=value.message
letdataView=newDataView(buffer)
...
...
@@ -199,25 +197,25 @@ TLS Socket connection process on the client:
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server. If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API. When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the **createWebSocket()** API to create a **WebSocket** object and then use the **connect()** API to connect to the server.
If the connection is successful, the client will receive a callback of the **open** event. Then, the client can communicate with the server using the **send()** API.
When the server sends a message to the client, the client will receive a callback of the **message** event. If the client no longer needs this connection, it can call the **close()** API to disconnect from the server. Then, the client will receive a callback of the **close** event.
If an error occurs in any of the preceding processes, the client will receive a callback of the **error** event.
## Available APIs
The WebSocket connection function is mainly implemented by the WebSocket module. To use related APIs, you must declare the **ohos.permission.INTERNET** permission. The following table describes the related APIs.
| API | Description |
| API| Description|
| -------- | -------- |
| createWebSocket() | Creates a WebSocket connection. |
| connect() | Establishes a WebSocket connection to a given URL. |
| send() | Sends data through the WebSocket connection. |
| close() | Closes a WebSocket connection. |
| on(type: 'open') | Enables listening for **open** events of a WebSocket connection. |
| off(type: 'open') | Disables listening for **open** events of a WebSocket connection. |
| on(type: 'message') | Enables listening for **message** events of a WebSocket connection. |
| off(type: 'message') | Disables listening for **message** events of a WebSocket connection. |
| on(type: 'close') | Enables listening for **close** events of a WebSocket connection. |
| off(type: 'close') | Disables listening for **close** events of a WebSocket connection. |
| on(type: 'error') | Enables listening for **error** events of a WebSocket connection. |
| off(type: 'error') | Disables listening for **error** events of a WebSocket connection. |
| createWebSocket() | Creates a WebSocket connection.|
| connect() | Establishes a WebSocket connection to a given URL.|
| send() | Sends data through the WebSocket connection.|
| close() | Closes a WebSocket connection.|
| on(type: 'open') | Enables listening for **open** events of a WebSocket connection.|
| off(type: 'open') | Disables listening for **open** events of a WebSocket connection.|
| on(type: 'message') | Enables listening for **message** events of a WebSocket connection.|
| off(type: 'message') | Disables listening for **message** events of a WebSocket connection.|
| on(type: 'close') | Enables listening for **close** events of a WebSocket connection.|
| off(type: 'close') | Disables listening for **close** events of a WebSocket connection.|
| on(type: 'error') | Enables listening for **error** events of a WebSocket connection.|
| off(type: 'error') | Disables listening for **error** events of a WebSocket connection.|
## How to Develop
1. Import the required WebSocket module.
1. Import the required webSocket module.
2. Create a **WebSocket** object.
3. (Optional) Subscribe to WebSocket open, message, close, and error events.
3. (Optional) Subscribe to WebSocket **open**, **message**, **close**, and **error** events.
4. Establish a WebSocket connection to a given URL.
5. Close the WebSocket connection if it is no longer needed.
The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
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.
> **NOTE**<br>
> **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.
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.
## Modules to Import
...
...
@@ -19,8 +19,6 @@ getNativeHeapSize(): bigint
Obtains the total heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
@@ -163,76 +157,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
letcpuUsage=hidebug.getCpuUsage();
```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9) instead.
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9) instead.
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
> This API is deprecated since API version 9. You are advised to use [hidebug.startJsCpuProfiling](#hidebugstartjscpuprofiling9).
Starts the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined profile name. The `filename.json` file is generated in the `files` directory of the application based on the specified `filename`.|
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.stopProfiling<sup>(deprecated)</sup>
stopProfiling() : void
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hidebug.stopJsCpuProfiling](#hidebugstopjscpuprofiling9).
Stops the profiling method. `startProfiling()` and `stopProfiling()` are called in pairs. `startProfiling()` always occurs before `stopProfiling()`; that is, calling the functions in the sequence similar to the following is prohibited: `start->start->stop`, `start->stop->stop`, and `start->start->stop->stop`.
| filename | string | Yes | User-defined heap file name. The `filename.heapsnapshot` file is generated in the `files` directory of the application based on the specified `filename`.|
The **http** module provides the HTTP data request capability. An application can initiate a data request over HTTP. Common HTTP methods include **GET**, **POST**, **OPTIONS**, **HEAD**, **PUT**, **DELETE**, **TRACE**, and **CONNECT**.
>**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.
>
...
...
@@ -35,11 +35,11 @@ httpRequest.request(
header:{
'Content-Type':'application/json'
},
// This field is used to transfer data when the POST request is used.
// This parameter is used to transfer data when the POST request is used.
extraData:{
"data":"data to send",
},
expectDataType:http.HttpDataType.STRING,// Optional. This field specifies the type of the return data.
expectDataType:http.HttpDataType.STRING,// Optional. This parameter specifies the type of the return data.
usingCache:true,// Optional. The default value is true.
priority:1,// Optional. The default value is 1.
connectTimeout:60000// Optional. The default value is 60000, in ms.
...
...
@@ -82,6 +82,7 @@ Creates an HTTP request. You can use this API to initiate or destroy an HTTP req
@@ -121,7 +122,7 @@ Initiates an HTTP request to a given URL. This API uses an asynchronous callback
| 2300052 | Server returned nothing (no headers, no data). |
| 2300999 | Unknown Other Error. |
>**NOTE**
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
@@ -197,7 +198,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
...
...
@@ -205,14 +206,14 @@ Initiates an HTTP request containing specified options to a given URL. This API
@@ -288,7 +289,7 @@ Initiates an HTTP request containing specified options to a given URL. This API
| 2300094 | An authentication function returned an error. |
| 2300999 | Unknown Other Error. |
>**NOTE**
>**NOTE**
> For details about the error codes, see [HTTP Error Codes](../errorcodes/errorcode-net-http.md).
> The HTTP error code mapping is in the format of 2300000 + Curl error code. For more common error codes, see [Curl Error Codes](https://curl.se/libcurl/c/libcurl-errors.html).
Unregisters the observer for HTTP Response Header events.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
| method | [RequestMethod](#requestmethod) | No | Request method. |
| extraData | string\| Object \| ArrayBuffer<sup>6+</sup> | No | Additional data of the request.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request.<br>- If the HTTP request uses a GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter is a supplement to the HTTP request parameters and will be added to the URL when the request is sent.<sup>6+</sup><br>- To pass in a string object, you first need to encode the object on your own.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the return data. If this parameter is set, the system returns the specified type of data preferentially.|
| method | [RequestMethod](#requestmethod) | No | Request method. The default value is **GET**. |
| extraData | string<sup>6+</sup>\| Object<sup>6+</sup>\| ArrayBuffer<sup>8+</sup> | No | Additional data for sending a request. This parameter is not used by default.<br>- If the HTTP request uses a POST or PUT method, this parameter serves as the content of the HTTP request and is encoded in UTF-8 format.<sup>6+</sup><br>- If the HTTP request uses the GET, OPTIONS, DELETE, TRACE, or CONNECT method, this parameter serves as a supplement to HTTP request parameters. Parameters of the string type need to be encoded before being passed to the HTTP request. Parameters of the object type do not need to be precoded and will be directly concatenated to the URL. Parameters of the ArrayBuffer type will not be concatenated to the URL.<sup>6+</sup> |
| expectDataType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | No | Type of the returned data. This parameter is not used by default. If this parameter is set, the system returns the specified type of data preferentially.|
| usingCache<sup>9+</sup> | boolean | No | Whether to use the cache. The default value is **true**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[1,1000]. The default value is **1**. |
| priority<sup>9+</sup> | number | No | Priority. The value range is \[0, 1000]. The default value is **0**. |
| header | Object | No | HTTP request header. The default value is **{'Content-Type': 'application/json'}**. |
| readTimeout | number | No | Read timeout duration. The default value is **60000**, in ms. |
| connectTimeout | number | No | Connection timeout interval. The default value is **60000**, in ms. |
...
...
@@ -539,10 +540,10 @@ Defines the response to an HTTP request.
| result | string\| Object \| ArrayBuffer<sup>6+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| result | string<sup>6+</sup>\| Object<sup>deprecated 8+</sup>\| ArrayBuffer<sup>8+</sup> | Yes | Response content returned based on **Content-type** in the response header:<br>- application/json: a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content.<br>- application/octet-stream: ArrayBuffer<br>- Others: string|
| resultType<sup>9+</sup> | [HttpDataType](#httpdatatype9) | Yes | Type of the return value. |
| responseCode | [ResponseCode](#responsecode)\| number | Yes | Result code for an HTTP request. If the callback function is successfully executed, a result code defined in [ResponseCode](#responsecode) will be returned. Otherwise, an error code will be returned in the **err** field in **AsyncCallback**.|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- Content-Type: header['Content-Type'];<br>- Status-Line: header['Status-Line'];<br>- Date: header.Date/header['Date'];<br>- Server: header.Server/header['Server'];|
| header | Object | Yes | Response header. The return value is a string in JSON format. If you want to use specific content in the response, you need to implement parsing of that content. Common fields and parsing methods are as follows:<br>- content-type: header['content-type'];<br>- status-line: header['status-line'];<br>- date: header.date/header['date'];<br>- server: header.server/header['server'];|
| cookies<sup>8+</sup> | string | Yes | Cookies returned by the server. |
## http.createHttpResponseCache<sup>9+</sup>
...
...
@@ -569,6 +570,7 @@ Creates a default object to store responses to HTTP access requests.
@@ -34,10 +35,10 @@ Creates a **NetConnection** object. **netSpecifier** specifies the network, and
**Example**
```js
// Default network
// For the default network, you do not need to pass in parameters.
letnetConnection=connection.createNetConnection()
// Cellular network
// For the cellular network, you need to pass in related network parameters. If the timeout parameter is not specified, the timeout value is 0 by default.
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
Reports connection of the data network to the network management module. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
Reports connection of the data network to the network management module. This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses an asynchronous callback to return the result.
Reports disconnection of the data network to the network management module. This API uses an asynchronous callback to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
Reports a **netAavailable** event to NetManager. If this API is called, the application considers that its network status (ohos.net.connection.NetCap.NET_CAPABILITY_VAILDATED) is inconsistent with that of NetManager.
This API uses a promise to return the result.
Reports disconnection of the data network to the network management module. This API uses a promise to return the result.
**Permission required**: ohos.permission.GET_NETWORK_INFO and ohos.permission.INTERNET
...
...
@@ -1038,7 +1035,6 @@ Registers a listener for network status changes.
| 2101008 | The callback is not exists. |
| 2101022 | The number of requests exceeded the maximum. |
| type | string | Yes | Event type. The value is fixed to **netConnectionPropertiesChange**.<br>**netConnectionPropertiesChange**: event indicating that network connection properties have changed.|
| callback | Callback<{netHandle:[NetHandle](#nethandle),connectionProperties:[ConnectionProperties](#connectionproperties)}> | Yes | Callback used to return the network handle (**netHandle**) and capability information (**netCap**).|
| callback | Callback<{netHandle:[NetHandle](#nethandle),connectionProperties:[ConnectionProperties](#connectionproperties)}> | Yes | Callback used to return the network handle (**netHandle**) and conection information (**connectionProperties**).|
**Example**
...
...
@@ -1353,6 +1350,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
| type | string | Yes | Event type. The value is **interfaceStateChange**.|
| callback | AsyncCallback\<{ iface: string, active: boolean }\> | Yes | Callback used to return the result.<br>**iface**: NIC name.<br>**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.|
| type | string | Yes | Event type. The value is **interfaceStateChange**.|
| callback | AsyncCallback\<{ iface: string, active: boolean }> | No | Callback used to return the result.<br>**iface**: NIC name.<br>**active**: whether the NIC is active. The value **true** indicates that the NIC is active, and the value **false** indicates the opposite.|
The **uiAppearance** module provides basic capabilities for managing the system appearance. It allows for color mode configuration currently, and will introduce more features over time.
> 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.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server. If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API. When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
You can use WebSocket to establish a bidirectional connection between a server and a client. Before doing this, you need to use the [createWebSocket](#websocketcreatewebsocket) API to create a [WebSocket](#websocket) object and then use the [connect](#connect) API to connect to the server.
If the connection is successful, the client will receive a callback of the [open](#onopen) event. Then, the client can communicate with the server using the [send](#send) API.
When the server sends a message to the client, the client will receive a callback of the [message](#onmessage) event. If the client no longer needs this connection, it can call the [close](#close) API to disconnect from the server. Then, the client will receive a callback of the [close](#onclose) event.
If an error occurs in any of the preceding processes, the client will receive a callback of the [error](#onerror) event.
## Modules to Import
```js
...
...
@@ -21,9 +22,13 @@ import webSocket from '@ohos.net.webSocket';
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!",(err,value)=>{
...
...
@@ -82,7 +87,6 @@ Creates a WebSocket connection. You can use this API to create or close a WebSoc
letws=webSocket.createWebSocket();
```
## WebSocket
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses an asynchronous callback to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
Initiates a WebSocket request carrying specified options to establish a WebSocket connection to a given URL. This API uses a promise to return the result.
> **NOTE**
> You can listen to **error** events to obtain the operation result. If an error occurs, the error code 200 will be returned.
Disables listening for the **open** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
Enables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>**NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
Disables listening for the **message** events of a WebSocket connection. This API uses an asynchronous callback to return the result. The maximum length of each message is 4 KB. If the length exceeds 4 KB, the message is automatically fragmented.
>**NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>**NOTE**
>The data in **AsyncCallback** can be in the format of string (API version 6) or ArrayBuffer (API version 8).
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
Disables listening for the **close** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
Disables listening for the **error** events of a WebSocket connection. This API uses an asynchronous callback to return the result.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
>**NOTE**
>You can pass the callback of the **on** function if you want to cancel listening for a certain type of event. If you do not pass the callback, you will cancel listening for all events.
| header | Object | No | Header carrying optional parameters in the request for establishing a WebSocket connection. You can customize the parameter or leave it unspecified.|
## WebSocketCloseOptions
Defines the optional parameters carried in the request for closing a WebSocket connection.
# Establishing a Data Channel Between the Application and the Frontend Page
The [createWebMessagePorts()](../reference/apis/js-apis-webview.md#createwebmessageports) API allows you to create message ports to implement communication between the application and frontend page.
In the following example, **createWebMessagePorts** is used to create message ports on the application and [postMessage()](../reference/apis/js-apis-webview.md#postmessage) is used to forward one of the message ports to the frontend page so that the application and frontend page can exchange messages with each other over the port.
In addition to displaying web page content on applications, the **Web** component provides you with some other helpful functions, including:
-**Page loading**: provides a full set of basic frontend page loading capabilities, which allow you to load network pages, local pages, and HTML text data.
-**Page interaction**: supports a wide range of page interaction modes, which allow you to set the dark mode for frontend pages, load pages in a new window, manage location permissions and cookies, and use frontend page JavaScript code on the application.
-**Page debugging**: uses DevTools to debug frontend pages.
To help you better understand the features of the **Web** component, the following sections will exemplify use of the **Web** component in common application scenarios.
A cookie is a segment of data sent from the server to the client to uniquely identify a user during network access. The client may hold the data and provide it to the server at later interactions so that the server can quickly identify the client identity and status.
The **Web** component provides the **WebCookieManager** class for you to manage cookie information, which is stored in the **/proc/{pid}/root/data/storage/el2/base/cache/web/Cookiesd** file in the application sandbox path.
The following uses [setCookie()](../reference/apis/js-apis-webview.md#setcookie) as an example to describe how to set a cookie's value to **test** for **www.example.com**. For details about functions and usage of other APIs, see [WebCookieManager()](../reference/apis/js-apis-webview.md#webcookiemanager).
Network resource requests are relatively time-consuming during website access. You can use store resources locally by means of cache and Dom Storage to fasten the access to the same website.
### Cache
Use [cacheMode()](../reference/arkui-ts/ts-basic-components-web.md#cachemode) to configure the cache mode for page resources. Four cache modes are supported:
-**Default**: Page resources in a cache that has not expired are preferentially used. If the cache does not exist, page resources are obtained from the network.
-**None**: Page resources are loaded from the cache. If the cache does not exist, page resources are obtained from the network.
-**Online**: Page resources are not loaded from the cache. All resources are obtained from the network.
-**Only**: Page resources are only loaded from the cache.
In the following example, the cache mode is set to **None**.
To obtain up-to-date resources, you can use [removeCache()](../reference/apis/js-apis-webview.md#removecache) to clear cached resources. The sample code is as follows:
// If this parameter is set to true, the cache in both the ROM and RAM is cleared. If this parameter is set to false, only the cache in the RAM is cleared.
Dom Storage falls into Session Storage and Local Storage. Wherein, Session Storage applies to the temporary data, and its data storage and release follow the session lifecycle; Local Storage applies to the persistent data, which is flushed to the application directory. In both storage modes, data is stored in a form of key-value pair, and is usually used when a page that needs to be stored on the client is accessed. You can use [domStorageAccess()](../reference/arkui-ts/ts-basic-components-web.md#domstorageaccess) to enable Dom Storage. The following is the sample code:
The **Web** component supports debugging of web frontend pages by using DevTools, a web frontend development and debugging tool that allows you to debug an application's frontend pages on a PC. Before you do this, use [setWebDebuggingAccess()](../reference/apis/js-apis-webview.md#setwebdebuggingaccess) to enable frontend page debugging for the **Web** component.
To use DevTools for frontend page debugging, perform the following steps:
1. Enable web frontend page debugging in the application code.
2. Connect your device to a PC, and configure port mapping on the PC as follows:
```
// Configure port mapping.
hdc fport tcp:9222 tcp:9222
// View port mapping.
hdc fport ls
```
3. Enter **chrome://inspect/\#devices** in the address box of the Chrome browser on the PC. Once the device is identified, you can get started with page debugging. The debugging effect is as follows:
The **Web** component supports file uploading on a frontend page. You can use [onShowFileSelector()](../reference/arkui-ts/ts-basic-components-web.md#onshowfileselector9) to process file upload requests sent from a frontend page.
In the following example, when a user clicks the **Upload** button on the frontend page, the application receives a file upload request through [onShowFileSelector()](../reference/arkui-ts/ts-basic-components-web.md#onshowfileselector9), which carries the path of the local file to be uploaded.
The **Web** component provides the location permission management capability. You can use [onGeolocationShow()](../reference/arkui-ts/ts-basic-components-web.md#ongeolocationshow) to manage the location permission specific to a website. Based on the API response, the **Web** component determines whether to grant the location permission to the frontend page. To obtain the device location, you need to declare the [ohos.permission.LOCATION](../security/accesstoken-guidelines.md) permission.
In the following example, when a user clicks the **Get Location** button on the frontend page, the **Web** component notifies the application of the location permission request in a pop-up window.
# Invoking Frontend Page Functions on the Application
You can call [runJavaScript()](../reference/apis/js-apis-webview.md#runjavascript) on an application to call JavaScript functions of frontend pages.
In the following example, when a user clicks the **runJavaScript** button on the application, the **htmlTest()** API of the frontend page will be triggered.
# Invoking Application Functions on the Frontend Page
You can use the **Web** component to register application code with frontend pages. After the registration is done, frontend pages can use the registered object names to call application functions.
Two methods are available for registering the application code:<br>Call [javaScriptProxy()](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy) during **Web** component initialization.<br> Call [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy) after **Web** component initialization.
The following example registers the **test()** function with the frontend page. This way, the **test()** function can be triggered and run on the frontend page.
- Sample code for using [javaScriptProxy()](../reference/arkui-ts/ts-basic-components-web.md#javascriptproxy):
> If you use [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy) to register a function, call **[refresh()]**(../reference/apis/js-apis-webview.md#refresh) for the function to take effect.
- Sample code for invoking application functions on the **index.htm** page:
The **Web** component provides the capability of opening pages in a new window. You can call [multiWindowAccess()](../reference/arkui-ts/ts-basic-components-web.md#multiwindowaccess9) to specify whether to allow a web page to be opened in a new window. When a new window is opened in the **Web** component, the application will receive a window opening event through [onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9). You need to add the code for processing the window opening request in the event callback.
> **NOTE**
>
> If you do not want to open a new window in [onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9), set the return value of [ControllerHandler.setWebController()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9) to **null**.
In the following example, when a user clicks the **Open Page in New Window** button, the application receives a window opening event in the [onWindowNew()](../reference/arkui-ts/ts-basic-components-web.md#onwindownew9) callback.
- Application code:
For details about how to create a window, see [Web Development Examples] (https://gitee.com/openharmony/applications_app_samples/tree/master/code/BasicFeature/Web/Browser).
// Create a window, associate it with popController, and have popController returned to the Web component. If you do not need to open a new window, set the return value to event.handler.setWebController(null).
event.handler.setWebController(popController);
})
}
}
}
```
- Code of the **window.html** page:
```html
<!DOCTYPE html>
<html>
<head>
<metacharset="utf-8">
<title>WindowEvent</title>
</head>
<body>
<inputtype="button"value="Open Page in New Window"onclick="OpenNewWindow()">
Page loading is a basic function of the **Web** component. Depending on the data source, page loading falls into three types: loading of network pages, loading of local pages, and loading of HTML rich text data.
If acquisition of network resources is involved in page loading, you need to declare the [ohos.permission.INTERNET](../security/accesstoken-guidelines.md) permission.
## Loading Network Pages
You can specify the default network page to be loaded when creating a **Web** component. After the default network page is loaded, call [loadUrl()](../reference/apis/js-apis-webview.md#loadurl) if you want to change the network page displayed by the **Web** component.
In the following example, after the **www.example.com** page is loaded by the **Web** component, **loadUrl** is called to change the displayed page to **www.example1.com**.
Local page files are stored in the application's **rawfile** directory. You can specify the local page to be loaded by default when creating a **Web** component. After page loading is complete, you can call [loadUrl()](../reference/apis/js-apis-webview.md#loadurl) to change the displayed page of the **Web** component.
The following example shows how to load a local page file.
- Local page file in the application's resources/rawfile directory:
The **Web** component provides the [loadData()](../reference/apis/js-apis-webview.md#loaddata) API for you to load HTML rich text data. This API is applicable if you want to display some page sections instead of the entire page.
# Managing Page Redirection and Browsing History Navigation
## History Navigation
When a user clicks a web page link on the frontend page, the **Web** component automatically opens and loads the target website by default. When the current page is assigned a new loading link, the address of the accessed web page is automatically recorded. You can call [forward()](../reference/apis/js-apis-webview.md#forward) or [backward()](../reference/apis/js-apis-webview.md#backward) to browse the previous or next history record.
In the following example, when a user clicks the button, **backward()** is called to go back to the previous page.
If a previous record exists, [accessBackward()](../reference/apis/js-apis-webview.md#accessbackward) will return **true**. Similarly, you can call [accessForward()](../reference/apis/js-apis-webview.md#accessforward) to check whether a next record exists. If you skip the check, [forward()](../reference/apis/js-apis-webview.md#forward) and [backward()](../reference/apis/js-apis-webview.md#backward) will not trigger any action if the user has navigated to the end of history records.
## Page Redirection
The **Web** component provides the [onUrlLoadIntercept()](../reference/arkui-ts/ts-basic-components-web.md#onurlloadintercept) API to redirect you from one page to another.
In the following example, the frontend page **route.html** is loaded on to the application home page **Index.ets**, and the user is redirected to the application page **ProfilePage.ets** when clicking the link on the **route.html** page.
The **Web** component supports redirection from one application to another.
In the following example, when a user clicks the link on the frontend page **call.html**, the user will be redirected to the dial screen of the phone app.
The **Web** component supports customization of the response to intercepted page requests. You can call [onInterceptRequest()](../reference/arkui-ts/ts-basic-components-web.md#oninterceptrequest9) to customize web page responses, file resource responses, etc.
When a resource loading request is initiated on a web page, the application layer will receive the request. The application layer then constructs a local resource response and sends it to the web kernel. On receiving the response, the web kernel parses the response and loads page resources accordingly.
In the following example, the **Web** component intercepts the web page request **https://www.intercept.com/test.html** and constructs a custom response in the application code.
The **Web** component allows you to set the dark mode for frontend pages.
- Call [darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9) to configure an expected dark mode.
[WebDarkMode.Off](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9) indicates that the dark mode is disabled. [WebDarkMode.On](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9) indicates that the dark mode is enabled and its setting follows the frontend page. [WebDarkMode.Auto](../reference/arkui-ts/ts-basic-components-web.md#webdarkmode9) indicates that the dark mode is enabled and its setting follows the system.
In the following example, the dark mode setting is configured to follow the system by using [darkMode()](../reference/arkui-ts/ts-basic-components-web.md#darkmode9).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
- Call [forceDarkAccess()](../reference/arkui-ts/ts-basic-components-web.md#forcedarkaccess9) to forcibly set the dark mode for the frontend page and configure the dark mode not to follow the frontend page or system setting.
In this mode, you need to specify **WebDarkMode.On** when calling **darkMode()**.
In the following example, [forceDarkAccess()](../reference/arkui-ts/ts-basic-components-web.md#forcedarkaccess9) is used to forcibly set the dark mode for the frontend page.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();