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

!17719 翻译已完成17378+17239+17370+17348+17292+17237+16743

Merge pull request !17719 from shawn_he/17378-d
......@@ -23,7 +23,7 @@ The following table provides only a simple description of the related APIs. For
| off(type: 'headersReceive') | Unregisters the observer for HTTP Response Header events.|
| once\('headersReceive'\)<sup>8+</sup> | Registers a one-time observer for HTTP Response Header events.|
## How to Develop
## How to Develop request APIs
1. Import the **http** namespace from **@ohos.net.http.d.ts**.
2. Call **createHttp()** to create an **HttpRequest** object.
......@@ -46,7 +46,6 @@ httpRequest.on('headersReceive', (header) => {
});
httpRequest.request(
// Customize EXAMPLE_URL in extraData on your own. It is up to you whether to add parameters to the URL.
"EXAMPLE_URL",
{
method: http.RequestMethod.POST, // Optional. The default value is http.RequestMethod.GET.
// You can add header fields based on service requirements.
......@@ -81,3 +80,4 @@ httpRequest.request(
}
);
```
# Network Sharing
## Introduction
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.
import sharing from '@ohos.net.sharing'
import sharing from '@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.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
});
```
## Disabling network sharing
......@@ -79,18 +86,18 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
import sharing from '@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 stopSharing to stop network sharing of the specified type.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
// Call stopSharing to stop network sharing of the specified type.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
});
```
## Obtaining the data traffic of the shared network
......@@ -104,27 +111,27 @@ For the complete list of APIs and example code, see [Network Sharing](../referen
```js
// Import the sharing namespace from @ohos.net.sharing.
import sharing from '@ohos.net.sharing'
import sharing from '@ohos.net.sharing'
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
// Call startSharing to start network sharing of the specified type.
sharing.startSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
});
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
// Call getStatsTotalBytes to obtain the data traffic generated during data sharing.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
});
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
// Call stopSharing to stop network sharing of the specified type and clear the data volume of network sharing.
sharing.stopSharing(sharing.SharingIfaceType.SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
});
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
// Call getStatsTotalBytes again. The data volume of network sharing has been cleared.
sharing.getStatsTotalBytes((error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
});
});
```
......@@ -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 TLS Socket 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/UDP Socket connections
- Implementing encrypted data transmission over TLS Socket 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:&nbsp;'close') | Unsubscribes from **close** events of the Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDP Socket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDP Socket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCP Socket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCP Socket connection.|
| on(type:&nbsp;'listening') | Subscribes to **listening** events of the UDPSocket connection. |
| off(type:&nbsp;'listening') | Unsubscribes from **listening** events of the UDPSocket connection. |
| on(type:&nbsp;'connect') | Subscribes to **connect** events of the TCPSocket connection. |
| off(type:&nbsp;'connect') | Unsubscribes from **connect** events of the TCPSocket connection.|
TLS Socket 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 TLS Socket 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 TLS Socket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLS Socket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLS Socket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLS Socket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLS Socket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLS Socket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLS Socket connection.|
| getState() | Obtains the TLSSocket connection status.|
| off(type:&nbsp;'close') | Unsubscribes from **close** events of the TLSSocket connection.|
| off(type:&nbsp;'error') | Unsubscribes from **error** events of the TLSSocket connection.|
| off(type:&nbsp;'message') | Unsubscribes from **message** events of the TLSSocket connection.|
| on(type:&nbsp;'close') | Subscribes to **close** events of the TLSSocket connection.|
| on(type:&nbsp;'error') | Subscribes to **error** events of the TLSSocket connection.|
| on(type:&nbsp;'message') | Subscribes to **message** events of the TLSSocket connection.|
| send() | Sends data.|
| setExtraOptions() | Sets other properties of the TLS Socket connection.|
| setExtraOptions() | Sets other properties of the TLSSocket connection.|
## Transmitting Data over TCP/UDP Socket 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 TCP Socket 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 TCP Socket connection to be automatically closed after use.
7. Enable the TCPSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
......@@ -93,7 +93,7 @@ The implementation is similar for UDP Socket and TCP Socket connections. The fol
// Create a TCPSocket object.
let tcp = socket.constructTCPSocketInstance();
// Subscribe to TCP Socket connection events.
// Subscribe to TCPSocket connection events.
tcp.on('message', value => {
console.log("on message")
let buffer = 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
TLS Socket 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 TLS Socket connection events.
5. (Optional) Subscribe to TLSSocket connection events.
6. Send data.
7. Enable the TLS Socket connection to be automatically closed after use.
7. Enable the TLSSocket connection to be automatically closed after use.
```js
import socket from '@ohos.net.socket'
// Create a TLS Socket connection (for two-way authentication).
let tlsTwoWay = socket.constructTLSSocketInstance();
// Create a TLSSocket connection (for two-way authentication).
let tlsTwoWay = 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")
let buffer = value.message
let dataView = new DataView(buffer)
......@@ -199,25 +197,25 @@ TLS Socket connection process on the client:
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
});
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
// Bind the local IP address and port number.
tlsTwoWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
});
// Set the communication parameters.
let options = {
// Set the communication parameters.
let options = {
ALPNProtocols: ["spdy/1", "http/1.1"],
// Set up a connection to the specified IP address and port number.
......@@ -238,16 +236,16 @@ TLS Socket connection process on the client:
signatureAlgorithms: "rsa_pss_rsae_sha256:ECDSA+SHA256", // Signature algorithm
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
};
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
// Set up a connection.
tlsTwoWay.connect(options, (err, data) => {
console.error(err);
console.log(data);
});
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
......@@ -256,40 +254,40 @@ TLS Socket connection process on the client:
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
});
// Create a TLS Socket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Create a TLSSocket connection (for one-way authentication).
let tlsOneWay = socket.constructTLSSocketInstance(); // One way authentication
// Subscribe to TLS Socket connection events.
tlsTwoWay.on('message', value => {
// Subscribe to TLSSocket connection events.
tlsTwoWay.on('message', value => {
console.log("on message")
let buffer = value.message
let dataView = new DataView(buffer)
let str = ""
for (let i = 0;i < dataView.byteLength; ++i) {
for (let i = 0; i < dataView.byteLength; ++i) {
str += String.fromCharCode(dataView.getUint8(i))
}
console.log("on connect received:" + str)
});
tlsTwoWay.on('connect', () => {
});
tlsTwoWay.on('connect', () => {
console.log("on connect")
});
tlsTwoWay.on('close', () => {
});
tlsTwoWay.on('close', () => {
console.log("on close")
});
});
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
// Bind the local IP address and port number.
tlsOneWay.bind({address: '192.168.xxx.xxx', port: xxxx, family: 1}, err => {
if (err) {
console.log('bind fail');
return;
}
console.log('bind success');
});
});
// Set the communication parameters.
let oneWayOptions = {
// Set the communication parameters.
let oneWayOptions = {
address: {
address: "192.168.xxx.xxx",
port: xxxx,
......@@ -299,16 +297,16 @@ TLS Socket connection process on the client:
ca: ["xxxx","xxxx"], // CA certificate
cipherSuite: "AES256-SHA256", // Cipher suite
},
};
};
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
// Set up a connection.
tlsOneWay.connect(oneWayOptions, (err, data) => {
console.error(err);
console.log(data);
});
});
// Enable the TCP Socket connection to be automatically closed after use. Then, disable listening for TCP Socket connection events.
tlsTwoWay.close((err) => {
// Enable the TCPSocket connection to be automatically closed after use. Then, disable listening for TCPSocket connection events.
tlsTwoWay.close((err) => {
if (err) {
console.log("close callback error = " + err);
} else {
......@@ -317,5 +315,5 @@ TLS Socket connection process on the client:
tlsTwoWay.off('message');
tlsTwoWay.off('connect');
tlsTwoWay.off('close');
});
});
```
# WebSocket Connection
## When to Use
## Use Cases
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.
```js
import webSocket from '@ohos.net.webSocket';
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
var defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
console.log("on open, status:" + JSON.stringify(value));
// When receiving the on('open') event, the client can use the send() API to communicate with the server.
ws.send("Hello, server!", (err, value) => {
......@@ -55,8 +54,8 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
console.log("Failed to send the message. Err:" + JSON.stringify(err));
}
});
});
ws.on('message', (err, value) => {
});
ws.on('message', (err, value) => {
console.log("on message, message:" + value);
// When receiving the `bye` message (the actual message name may differ) from the server, the client proactively disconnects from the server.
if (value === 'bye') {
......@@ -68,18 +67,18 @@ The WebSocket connection function is mainly implemented by the WebSocket module.
}
});
}
});
ws.on('close', (err, value) => {
});
ws.on('close', (err, value) => {
console.log("on close, code is " + value.code + ", reason is " + value.reason);
});
ws.on('error', (err) => {
});
ws.on('error', (err) => {
console.log("on error, error:" + JSON.stringify(err));
});
ws.connect(defaultIpAddress, (err, value) => {
});
ws.connect(defaultIpAddress, (err, value) => {
if (!err) {
console.log("Connected successfully");
} else {
console.log("Connection failed. Err:" + JSON.stringify(err));
}
});
```
});
```
......@@ -199,8 +199,8 @@ The development process consists of the following main steps:
2. Run the CMake tool.
- Use hdc_std to connect to the RK3568 development board and put **demo** and **mobilenetv2.ms** to the same directory on the board.
- Run the hdc_std shell command to access the development board, go to the directory where **demo** is located, and run the following command:
- Use hdc_std to connect to the device and put **demo** and **mobilenetv2.ms** to the same directory on the board.
- Run the hdc_std shell command to access the device, go to the directory where **demo** is located, and run the following command:
```shell
./demo mobilenetv2.ms
......
# Geolocation
# @ohos.geolocation (Geolocation)
The **geolocation** module provides a wide array of location services, including GNSS positioning, network positioning, geocoding, reverse geocoding, and geofencing.
......
# @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.
> **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.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -42,8 +40,6 @@ getNativeHeapAllocatedSize(): bigint
Obtains the allocated heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -65,8 +61,6 @@ getNativeHeapFreeSize(): bigint
Obtains the free heap memory size of this application.
This API is defined but not implemented in OpenHarmony 3.1 Release.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Return value**
......@@ -163,76 +157,6 @@ For example, if the CPU usage is **50%**, **0.5** is returned.
let cpuUsage = 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**<br>This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9) instead.
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
## hidebug.getServiceDump<sup>9+<sup>
getServiceDump(serviceid : number, fd : number, args : Array\<string>) : void
......@@ -251,11 +175,10 @@ Obtains system service information.
| fd | number | Yes | File descriptor to which data is written by the API.|
| args | Array\<string> | Yes | Parameter list corresponding to the **Dump** API of the system service.|
**Example**
```js
import fileio from '@ohos.fileio'
import fs from '@ohos.file.fs'
import hidebug from '@ohos.hidebug'
import featureAbility from '@ohos.ability.featureAbility'
......@@ -263,7 +186,7 @@ let context = featureAbility.getContext();
context.getFilesDir().then((data) => {
var path = data + "/serviceInfo.txt"
console.info("output path: " + path)
let fd = fileio.openSync(path, 0o102, 0o666)
let fd = fs.openSync(path, 0o102, 0o666)
var serviceId = 10
var args = new Array("allInfo")
try {
......@@ -272,7 +195,7 @@ context.getFilesDir().then((data) => {
console.info(error.code)
console.info(error.message)
}
fileio.closeSync(fd);
fs.closeSync(fd);
})
```
......@@ -360,3 +283,79 @@ try {
console.info(error.message)
}
```
## hidebug.startProfiling<sup>(deprecated)</sup>
startProfiling(filename : string) : void
> **NOTE**
>
> 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Example**
```js
hidebug.startProfiling("cpuprofiler-20220216");
// code block
// ...
// code block
hidebug.stopProfiling();
```
## hidebug.dumpHeapData<sup>(deprecated)</sup>
dumpHeapData(filename : string) : void
> **NOTE**
>
> This API is deprecated since API version 9. You are advised to use [hidebug.dumpJsHeapData](#hidebugdumpjsheapdata9).
Exports the heap data.
**System capability**: SystemCapability.HiviewDFX.HiProfiler.HiDebug
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | ------ | ---- | ------------------------------------------------------------ |
| 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`.|
**Example**
```js
hidebug.dumpHeapData("heap-20220216");
```
......@@ -2,7 +2,7 @@
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
```js
import http from '@ohos.net.http';
let httpRequest = http.createHttp();
```
......@@ -95,8 +96,8 @@ request(url: string, callback: AsyncCallback\<HttpResponse\>):void
Initiates an HTTP request to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -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).
......@@ -146,8 +147,8 @@ request(url: string, options: HttpRequestOptions, callback: AsyncCallback\<HttpR
Initiates an HTTP request containing specified options to a given URL. This API uses an asynchronous callback to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -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
```js
httpRequest.request("EXAMPLE_URL",
{
{
method: http.RequestMethod.GET,
header: {
'Content-Type': 'application/json'
},
readTimeout: 60000,
connectTimeout: 60000
}, (err, data) => {
}, (err, data) => {
if (!err) {
console.info('Result:' + data.result);
console.info('code:' + data.responseCode);
......@@ -223,7 +224,7 @@ httpRequest.request("EXAMPLE_URL",
} else {
console.info('error:' + JSON.stringify(err));
}
});
});
```
### request
......@@ -232,8 +233,8 @@ request(url: string, options? : HttpRequestOptions): Promise\<HttpResponse\>
Initiates an HTTP request containing specified options to a given URL. This API uses a promise to return the result.
>**NOTE**
>This API supports only transfer of data not greater than 5 MB.
> **NOTE**
> This API supports only transfer of data not greater than 5 MB.
**Required permissions**: ohos.permission.INTERNET
......@@ -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).
......@@ -335,8 +336,8 @@ on(type: 'headerReceive', callback: AsyncCallback\<Object\>): void
Registers an observer for HTTP Response Header events.
>**NOTE**
>This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
> **NOTE**
> This API has been deprecated. You are advised to use [on('headersReceive')<sup>8+</sup>](#onheadersreceive8).
**System capability**: SystemCapability.Communication.NetStack
......@@ -361,7 +362,7 @@ off(type: 'headerReceive', callback?: AsyncCallback\<Object\>): void
Unregisters the observer for HTTP Response Header events.
>**NOTE**
> **NOTE**
>
>1. This API has been deprecated. You are advised to use [off('headersReceive')<sup>8+</sup>](#offheadersreceive8).
>
......@@ -411,8 +412,8 @@ off(type: 'headersReceive', callback?: Callback\<Object\>): void
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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -460,11 +461,11 @@ Specifies the type and value range of the optional parameters in the HTTP reques
| Name | Type | Mandatory| Description |
| -------------- | --------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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.
| Name | Type | Mandatory| Description |
| -------------------- | -------------------------------------------- | ---- | ------------------------------------------------------------ |
| 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.
```js
import http from '@ohos.net.http';
let httpResponseCache = http.createHttpResponseCache();
```
......@@ -651,6 +653,7 @@ httpResponseCache.delete(err => {
console.info('delete success');
});
```
### delete<sup>9+</sup>
delete(): Promise\<void\>
......
......@@ -10,6 +10,7 @@ The network connection management module provides basic network management capab
```js
import connection from '@ohos.net.connection'
```
## connection.createNetConnection
createNetConnection(netSpecifier?: NetSpecifier, timeout?: number): NetConnection
......@@ -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.
let netConnection = 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.
let netConnectionCellular = connection.createNetConnection({
netCapabilities: {
bearerTypes: [connection.NetBearType.BEARER_CELLULAR]
......@@ -164,7 +165,7 @@ Obtains information about the network bound to an application. This API uses an
**Example**
```js
connection.getAppNet(function(error, data) {
connection.getAppNet(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -774,8 +775,7 @@ connection.disableAirplaneMode().then(function (error) {
reportNetConnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
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
......@@ -812,8 +812,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetConnected(netHandle: NetHandle): Promise&lt;void&gt;
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
......@@ -854,8 +853,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle, callback: AsyncCallback&lt;void&gt;): void
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
......@@ -892,8 +890,7 @@ connection.getDefaultNet().then(function (netHandle) {
reportNetDisconnected(netHandle: NetHandle): Promise&lt;void&gt;
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. |
**Example**
```js
......@@ -1196,7 +1192,8 @@ netCon.unregister(function (error) {
### on('netConnectionPropertiesChange')
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties: ConnectionProperties }>): void
on(type: 'netConnectionPropertiesChange', callback: Callback<{ netHandle: NetHandle, connectionProperties:
ConnectionProperties }>): void
Registers a listener for **netConnectionPropertiesChange** events.
......@@ -1209,7 +1206,7 @@ Registers a listener for **netConnectionPropertiesChange** events.
| Name | Type | Mandatory| Description |
| -------- | ------------------------------------------------------------ | ---- | ------------------------------------------------------------ |
| 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
```js
import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance();
......@@ -1363,6 +1361,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => {
if (error) {
console.log('bind fail');
return;
}
netHandle.bindSocket(tcp, (error, data) => {
if (error) {
......@@ -1382,6 +1381,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => {
if (error) {
console.log('bind fail');
return;
}
udp.on('message', (data) => {
console.log(JSON.stringify(data))
......@@ -1431,6 +1431,7 @@ Binds a **TCPSocket** or **UDPSocket** object to the data network. This API uses
```js
import socket from "@ohos.net.socket";
connection.getDefaultNet().then((netHandle) => {
var tcp = socket.constructTCPSocketInstance();
var udp = socket.constructUDPSocketInstance();
......@@ -1441,6 +1442,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => {
if (error) {
console.log('bind fail');
return;
}
netHandle.bindSocket(tcp).then((data) => {
console.log(JSON.stringify(data));
......@@ -1458,6 +1460,7 @@ connection.getDefaultNet().then((netHandle) => {
}, error => {
if (error) {
console.log('bind fail');
return;
}
udp.on('message', (data) => {
console.log(JSON.stringify(data));
......@@ -1732,8 +1735,8 @@ Defines a network address.
**System capability**: SystemCapability.Communication.NetManager.Core
| Name | Type | Mandatory| Description |
| Name| Type| Mandatory| Description|
| ------- | ------ | -- |------------------------------ |
| address | string | Yes|Network address. |
| address | string | Yes|Network address.|
| family | number | No|Address family identifier. The value is **1** for IPv4 and **2** for IPv6. The default value is **1**.|
| port | number | No|Port number. The value ranges from **0** to **65535**. |
| port | number | No|Port number. The value ranges from **0** to **65535**.|
......@@ -386,6 +386,74 @@ ethernet.getAllActiveIfaces().then((data) => {
});
```
## ethernet.on('interfaceStateChange')<sup>10+</sup>
on(type: 'interfaceStateChange', callback: Callback\<{ iface: string, active: boolean }\>): void
Registers an observer for NIC hot swap events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| 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.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**Example**
```js
ethernet.on('interfaceStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
});
```
## ethernet.off('interfaceStateChange')<sup>10+</sup>
off(type: 'interfaceStateChange', callback?: Callback\<{ iface: string, active: boolean }\>): void
Unregisters the observer for NIC hot swap events. This API uses an asynchronous callback to return the result.
**System API**: This is a system API.
**Required permission**: ohos.permission.GET_NETWORK_INFO
**System capability**: SystemCapability.Communication.NetManager.Ethernet
**Parameters**
| Name | Type | Mandatory| Description |
| -------- | --------------------------------------- | ---- | ---------- |
| 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.|
**Error codes**
| ID| Error Message |
| ------- | -------------------------------------------- |
| 201 | Permission denied. |
| 202 | Applicable only to system applications. |
| 401 | Parameter error. |
**Example**
```js
ethernet.off('interfaceStateChange');
```
## InterfaceConfiguration
Defines the network configuration for the Ethernet connection.
......
......@@ -46,7 +46,9 @@ policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))), (error, da
this.callBack(error, data);
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
});
}
)
;
```
## policy.setBackgroundPolicy
......@@ -84,7 +86,7 @@ Sets a background network policy. This API uses a promise to return the result.
**Example**
```js
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
policy.setBackgroundPolicy(Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -151,7 +153,7 @@ Obtains the background network policy. This API uses a promise to return the res
**Example**
```js
policy.isBackgroundAllowed().then(function(error, data) {
policy.isBackgroundAllowed().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -236,7 +238,7 @@ Sets an application-specific network policy. This API uses a promise to return t
let param = {
uid: Number.parseInt(this.firstParam), policy: Number.parseInt(this.currentNetUidPolicy)
}
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function(error, data) {
policy.setPolicyByUid(Number.parseInt(this.firstParam), Number.parseInt(this.currentNetUidPolicy)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -313,7 +315,7 @@ Obtains an application-specific network policy by **uid**. This API uses a promi
**Example**
```js
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
policy.getPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -390,7 +392,7 @@ Obtains the UID array of applications configured with a certain application-spec
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -456,7 +458,7 @@ Obtains the network quota policies. This API uses a promise to return the result
**Example**
```js
policy.getNetQuotaPolicies().then(function(error, data) {
policy.getNetQuotaPolicies().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -493,8 +495,18 @@ Sets an array of network quota policies. This API uses an asynchronous callback
**Example**
```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes),
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction};
let param = {
netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList, (error, data) => {
......@@ -537,11 +549,21 @@ Sets an array of network quota policies. This API uses a promise to return the r
**Example**
```js
let param = {netType:Number.parseInt(this.netType), iccid:this.iccid, ident:this.ident, periodDuration:this.periodDuration, warningBytes:Number.parseInt(this.warningBytes),
limitBytes:Number.parseInt(this.limitBytes), lastWarningRemind:this.lastWarningRemind, lastLimitRemind:this.lastLimitRemind, metered:Boolean(Number.parseInt(this.metered)), limitAction:this.limitAction};
let param = {
netType: Number.parseInt(this.netType),
iccid: this.iccid,
ident: this.ident,
periodDuration: this.periodDuration,
warningBytes: Number.parseInt(this.warningBytes),
limitBytes: Number.parseInt(this.limitBytes),
lastWarningRemind: this.lastWarningRemind,
lastLimitRemind: this.lastLimitRemind,
metered: Boolean(Number.parseInt(this.metered)),
limitAction: this.limitAction
};
this.netQuotaPolicyList.push(param);
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function(error, data) {
policy.setNetQuotaPolicies(this.netQuotaPolicyList).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -619,7 +641,7 @@ Restores all the policies (cellular network, background network, firewall, and a
```js
this.firstParam = iccid;
policy.restoreAllPolicies(this.firstParam).then(function(error, data){
policy.restoreAllPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -706,7 +728,7 @@ Checks whether an application is allowed to access metered networks. This API us
let param = {
uid: Number.parseInt(this.firstParam), isMetered: Boolean(Number.parseInt(this.isBoolean))
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
policy.isUidNetAllowed(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -792,7 +814,7 @@ Checks whether an application is allowed to access the given network. This API u
let param = {
uid: Number.parseInt(this.firstParam), iface: this.secondParam
}
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function(error, data) {
policy.isUidNetAllowed(Number.parseInt(this.firstParam), this.secondParam).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -877,7 +899,7 @@ Sets whether to add an application to the device idle allowlist. This API uses a
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
policy.setDeviceIdleAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -943,7 +965,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example**
```js
policy.getDeviceIdleAllowList().then(function(error, data) {
policy.getDeviceIdleAllowList().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -1021,7 +1043,7 @@ Obtains the background network policies configured for the given application. Th
```js
this.firstParam = uid
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function(error, data) {
policy.getBackgroundPolicyByUid(Number.parseInt(this.firstParam)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -1098,11 +1120,11 @@ Restores all the policies (cellular network, background network, firewall, and a
**Example**
```js
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function(error, data) {
policy.getUidsByPolicy(Number.parseInt(this.firstParam)).then(function (error, data) {
})
this.firstParam = iccid
policy.resetPolicies(this.firstParam).then(function(error, data) {
policy.resetPolicies(this.firstParam).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -1189,7 +1211,7 @@ Updates a reminder policy. This API uses a promise to return the result.
let param = {
netType: Number.parseInt(this.netType), iccid: this.firstParam, remindType: this.currentRemindType
}
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function(error, data) {
policy.updateRemindPolicy(Number.parseInt(this.netType), this.firstParam, Number.parseInt(this.currentRemindType)).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -1274,7 +1296,7 @@ Sets whether to add an application to the power-saving allowlist. This API uses
let param = {
uid: Number.parseInt(this.firstParam), isAllowed: Boolean(Number.parseInt(this.isBoolean))
}
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function(error, data) {
policy.setPowerSaveAllowList(Number.parseInt(this.firstParam), Boolean(Number.parseInt(this.isBoolean))).then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......@@ -1340,7 +1362,7 @@ Obtains the UID array of applications that are on the device idle allowlist. Thi
**Example**
```js
policy.getPowerSaveAllowList().then(function(error, data) {
policy.getPowerSaveAllowList().then(function (error, data) {
console.log(JSON.stringify(error))
console.log(JSON.stringify(data))
})
......
......@@ -194,7 +194,8 @@ Starts network sharing of a specified type. This API uses an asynchronous callba
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
......@@ -243,7 +244,8 @@ Starts network sharing of a specified type. This API uses a promise to return th
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.startSharing(SHARING_WIFI).then(() => {
console.log("start wifi sharing successful");
}).catch(error => {
......@@ -287,7 +289,8 @@ Stops network sharing of a specified type. This API uses an asynchronous callbac
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI, (error) => {
console.log(JSON.stringify(error));
});
......@@ -334,7 +337,8 @@ Stops network sharing of a specified type. This API uses a promise to return the
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.stopSharing(SHARING_WIFI).then(() => {
console.log("stop wifi sharing successful");
}).catch(error => {
......@@ -588,7 +592,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js
import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
......@@ -633,7 +638,8 @@ Obtains the names of NICs in the specified network sharing state. This API uses
```js
import SharingIfaceState from '@ohos.net.sharing'
let SHARING_BLUETOOTH=2;
let SHARING_BLUETOOTH = 2;
sharing.getSharingIfaces(SHARING_BLUETOOTH).then(data => {
console.log(JSON.stringify(data));
}).catch(error => {
......@@ -674,7 +680,8 @@ Obtains the network sharing state of the specified type. This API uses an asynch
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
......@@ -719,7 +726,8 @@ Obtains the network sharing state of the specified type. This API uses a promise
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharingState(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data));
}).catch(error => {
......@@ -760,7 +768,8 @@ Obtains regular expressions of NICs of a specified type. This API uses an asynch
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI, (error, data) => {
console.log(JSON.stringify(error));
console.log(JSON.stringify(data));
......@@ -805,7 +814,8 @@ Obtains regular expressions of NICs of a specified type. This API uses a promise
```js
import SharingIfaceType from '@ohos.net.sharing'
let SHARING_WIFI=0;
let SHARING_WIFI = 0;
sharing.getSharableRegexes(SHARING_WIFI).then(data => {
console.log(JSON.stringify(data));
}).catch(error => {
......@@ -842,7 +852,7 @@ Subscribes to network sharing state changes. This API uses an asynchronous callb
**Example**
```js
sharing.on('sharingStateChange', (data) => {
sharing.on('sharingStateChange', (data) => {
console.log('on sharingStateChange: ' + JSON.stringify(data));
});
```
......@@ -910,8 +920,8 @@ Subscribes to network sharing state changes of a specified NIC. This API uses an
**Example**
```js
sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange: ' + JSON.stringify(data));
sharing.on('interfaceSharingStateChange', (data) => {
console.log('on interfaceSharingStateChange:' + JSON.stringify(data));
});
```
......@@ -978,8 +988,8 @@ Subscribes to upstream network changes. This API uses an asynchronous callback t
**Example**
```js
sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange: ' + JSON.stringify(data));
sharing.on('sharingUpstreamChange', (data) => {
console.log('on sharingUpstreamChange:' + JSON.stringify(data));
});
```
......
# UI Appearance
# @ohos.uiAppearance (UI Appearance)
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.
......
......@@ -5,11 +5,12 @@
> 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';
```js
import webSocket from '@ohos.net.webSocket';
var defaultIpAddress = "ws://";
let defaultIpAddress = "ws://";
let ws = webSocket.createWebSocket();
ws.on('open', (err, value) => {
if (err != undefined) {
console.log(JSON.stringify(err))
return
}
console.log("on open, status:" + value['status'] + ", message:" + value['message']);
// 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
let ws = webSocket.createWebSocket();
```
## WebSocket
Defines a **WebSocket** object. Before invoking WebSocket APIs, you need to call [webSocket.createWebSocket](#websocketcreatewebsocket) to create a **WebSocket** object.
......@@ -93,6 +97,9 @@ connect(url: string, callback: AsyncCallback\<boolean\>): void
Initiates a WebSocket request 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.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -125,13 +132,15 @@ ws.connect(url, (err, value) => {
});
```
### connect
connect(url: string, options: WebSocketRequestOptions, callback: AsyncCallback\<boolean\>): void
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.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -170,13 +179,15 @@ ws.connect(url, {
});
```
### connect
connect(url: string, options?: WebSocketRequestOptions): Promise\<boolean\>
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.
**Required permissions**: ohos.permission.INTERNET
**System capability**: SystemCapability.Communication.NetStack
......@@ -214,7 +225,6 @@ promise.then((value) => {
});
```
### send
send(data: string | ArrayBuffer, callback: AsyncCallback\<boolean\>): void
......@@ -255,7 +265,6 @@ ws.connect(url, (err, value) => {
});
```
### send
send(data: string | ArrayBuffer): Promise\<boolean\>
......@@ -300,7 +309,6 @@ ws.connect(url, (err, value) => {
});
```
### close
close(callback: AsyncCallback\<boolean\>): void
......@@ -328,7 +336,6 @@ Closes a WebSocket connection. This API uses an asynchronous callback to return
```js
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close((err, value) => {
if (!err) {
console.log("close success")
......@@ -338,7 +345,6 @@ ws.close((err, value) => {
});
```
### close
close(options: WebSocketCloseOptions, callback: AsyncCallback\<boolean\>): void
......@@ -367,7 +373,6 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js
let ws = webSocket.createWebSocket();
let url = "ws://"
ws.close({
code: 1000,
reason: "your reason"
......@@ -380,7 +385,6 @@ ws.close({
});
```
### close
close(options?: WebSocketCloseOptions): Promise\<boolean\>
......@@ -414,7 +418,6 @@ Closes a WebSocket connection carrying specified options such as **code** and **
```js
let ws = webSocket.createWebSocket();
let url = "ws://"
let promise = ws.close({
code: 1000,
reason: "your reason"
......@@ -426,7 +429,6 @@ promise.then((value) => {
});
```
### on('open')
on(type: 'open', callback: AsyncCallback\<Object\>): void
......@@ -442,7 +444,6 @@ Enables listening for the **open** events of a WebSocket connection. This API us
| type | string | Yes | Event type. <br />**open**: event indicating that a WebSocket connection has been opened.|
| callback | AsyncCallback\<Object\> | Yes | Callback used to return the result. |
**Example**
```js
......@@ -452,15 +453,14 @@ ws.on('open', (err, value) => {
});
```
### off('open')
off(type: 'open', callback?: AsyncCallback\<Object\>): void
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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -483,15 +483,14 @@ ws.on('open', callback1);
ws.off('open', callback1);
```
### on('message')
on(type: 'message', callback: AsyncCallback\<string | ArrayBuffer\>): void
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).
**System capability**: SystemCapability.Communication.NetStack
......@@ -511,16 +510,15 @@ ws.on('message', (err, value) => {
});
```
### off('message')
off(type: 'message', callback?: AsyncCallback\<string | ArrayBuffer\>): void
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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -538,7 +536,6 @@ let ws = webSocket.createWebSocket();
ws.off('message');
```
### on('close')
on(type: 'close', callback: AsyncCallback\<{ code: number, reason: string }\>): void
......@@ -563,15 +560,14 @@ ws.on('close', (err, value) => {
});
```
### off('close')
off(type: 'close', callback?: AsyncCallback\<{ code: number, reason: string }\>): void
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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -589,7 +585,6 @@ let ws = webSocket.createWebSocket();
ws.off('close');
```
### on('error')
on(type: 'error', callback: ErrorCallback): void
......@@ -603,7 +598,7 @@ Enables listening for the **error** events of a WebSocket connection. This API u
| Name | Type | Mandatory| Description |
| -------- | ------------- | ---- | ------------------------------- |
| type | string | Yes | Event type.<br />**error**: event indicating the WebSocket connection has encountered an error.|
| callback | ErrorCallback | Yes | Callback used to return the result. |
| callback | ErrorCallback | Yes | Callback used to return the result.<br>Common error code: 200|
**Example**
......@@ -614,15 +609,14 @@ ws.on('error', (err) => {
});
```
### off('error')
off(type: 'error', callback?: ErrorCallback): void
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.
**System capability**: SystemCapability.Communication.NetStack
......@@ -640,7 +634,6 @@ let ws = webSocket.createWebSocket();
ws.off('error');
```
## WebSocketRequestOptions
Defines the optional parameters carried in the request for establishing a WebSocket connection.
......@@ -651,7 +644,6 @@ Defines the optional parameters carried in the request for establishing a WebSoc
| ------ | ------ | ---- | ------------------------------------------------------------ |
| 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.
......
# Web
- [Web Component Overview](web-component-overview.md)
- [Loading Pages by Using the Web Component](web-page-loading-with-web-components.md)
- Setting Basic Attributes and Events
- [Setting the Dark Mode](web-set-dark-mode.md)
- [Uploading Files](web-file-upload.md)
- [Opening Pages in a New Window](web-open-in-new-window.md)
- [Managing Location Permissions](web-geolocation-permission.md)
- Using Frontend Page JavaScript Code on the Application
- [Invoking Frontend Page Functions on the Application](web-in-app-frontend-page-function-invoking.md)
- [Invoking Application Functions on the Frontend Page](web-in-page-app-function-invoking.md)
- [Establishing a Data Channel Between the Application and the Frontend Page](web-app-page-data-channel.md)
- [Managing Page Redirection and Browsing History Navigation](web-redirection-and-browsing-history-mgmt.md)
- [Managing Cookies and Data Storage](web-cookie-and-data-storage-mgmt.md)
- [Customizing Page Request Responses](web-resource-interception-request-mgmt.md)
- [Debugging Frontend Pages by Using DevTools](web-debugging-with-devtools.md)
# 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.
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
ports: web_webview.WebMessagePort[];
@State sendFromEts: string = 'Send this message from ets to HTML';
@State receivedFromHtml: string = 'Display received message send from HTML';
build() {
Column() {
// Display the content received from the HTML side.
Text(this.receivedFromHtml)
// Send the content in the text box to the HTML side.
TextInput({placeholder: 'Send this message from ets to HTML'})
.onChange((value: string) => {
this.sendFromEts = value;
})
Button('postMessage')
.onClick(() => {
try {
// 1. Create two message ports.
this.ports = this.controller.createWebMessagePorts();
// 2. Register a callback for the message port (for example, port 1) on the application.
this.ports[1].onMessageEvent((result: web_webview.WebMessage) => {
let msg = 'Got msg from HTML:';
if (typeof(result) === 'string') {
console.info(`received string message from html5, string is: ${result}`);
msg = msg + result;
} else if (typeof(result) === 'object') {
if (result instanceof ArrayBuffer) {
console.info(`received arraybuffer from html5, length is: ${result.byteLength}`);
msg = msg + 'lenght is ' + result.byteLength;
} else {
console.info('not support');
}
} else {
console.info('not support');
}
this.receivedFromHtml = msg;
})
// 3. Send the other message port (for example, port 0) to the HTML side, which then saves the message port.
this.controller.postMessage('__init_port__', [this.ports[0]], '*');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// 4. Use the message port on the application to send messages to the message port that has been sent to the HTML side.
Button('SendDataToHTML')
.onClick(() => {
try {
if (this.ports && this.ports[1]) {
this.ports[1].postMessageEvent(this.sendFromEts);
} else {
console.error(`ports is null, Please initialize first`);
}
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: $rawfile('xxx.html'), controller: this.controller })
}
}
}
```
- Frontend page code:
```html
<!--xxx.html-->
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>WebView Message Port Demo</title>
</head>
<script>
var h5Port;
var output = document.querySelector('.output');
window.addEventListener('message', function (event) {
if (event.data === '__init_port__') {
if (event.ports[0] !== null) {
h5Port = event.ports[0]; // 1. Save the port sent from the eTS side.
h5Port.onmessage = function (event) {
// 2. Receive messages sent from the eTS side.
var msg = 'Got message from ets:';
var result = event.data;
if (typeof(result) === 'string') {
console.info(`received string message from html5, string is: ${result}`);
msg = msg + result;
} else if (typeof(result) === 'object') {
if (result instanceof ArrayBuffer) {
console.info(`received arraybuffer from html5, length is:` ${result.byteLength}`);
msg = msg + 'lenght is ' + result.byteLength;
} else {
console.info('not support');
}
} else {
console.info('not support');
}
output.innerHTML = msg;
}
}
}
})
// 3. Use H5Port to send messages to the eTS side.
function PostMsgToEts(data) {
if (h5Port) {
h5Port.postMessage(data);
} else {
console.error('h5Port is null, Please initialize first');
}
}
</script>
<body>
<h1>WebView Message Port Demo</h1>
<div>
<input type="button" value="SendToEts" onclick="PostMsgToEts(msgFromJS.value);"/><br/>
<input id="msgFromJS" type="text" value="send this message from HTML to ets"/><br/>
</div>
<p class="output">display received message send from ets</p>
</body>
</html>
```
# Web Component Overview
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.
# Managing Cookies and Data Storage
## Cookie Management
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).
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('setCookie')
.onClick(() => {
try {
web_webview.WebCookieManager.setCookie('https://www.example.com', 'value=test');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
## Cache and Storage Management
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**.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State mode: CacheMode = CacheMode.None;
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.cacheMode(this.mode)
}
}
}
```
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:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
@State mode: CacheMode = CacheMode.None;
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('removeCache')
.onClick(() => {
try {
// 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.
this.controller.removeCache(true);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.cacheMode(this.mode)
}
}
}
```
### Dom Storage
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:
```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 })
.domStorageAccess(true)
}
}
}
```
# Debugging Frontend Pages by Using DevTools
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.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
aboutToAppear() {
// Enable web frontend page debugging.
web_webview.WebviewController.setWebDebuggingAccess(true);
}
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
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:
**Figure 1** Page debugging effect
![debug-effect](figures/debug-effect.png)
# Uploading Files
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.
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: WebController = new WebController()
build() {
Column() {
// Load the local.html page.
Web({ src: $rawfile('local.html'), controller: this.controller })
.onShowFileSelector((event) => {
// Set the path of the local file to be uploaded.
let fileList: Array<string> = [
'xxx/test.png',
]
event.result.handleFileList(fileList)
return true;
})
}
}
}
```
- Code of the **local.html** page:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Document</title>
</head>
<body>
<!-- Click the Upload button -->
<input type="file" value="file"></br>
</body>
</html>
```
# Managing Location Permissions
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.
- Frontend page code:
```html
<!DOCTYPE html>
<html>
<body>
<p id="locationInfo">Location information</p>
<button onclick="getLocation()">Get Location</button>
<script>
var locationInfo=document.getElementById("locationInfo");
function getLocation(){
if (navigator.geolocation) {
<!-- Access to the device location by the frontend page -->
navigator.geolocation.getCurrentPosition(showPosition);
}
}
function showPosition(position){
locationInfo.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude;
}
</script>
</body>
</html>
```
- Application code:
```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:$rawfile('getLocation.html'), controller:this.controller })
.geolocationAccess(true)
.onGeolocationShow((event) => { // Notification of the location permission request
AlertDialog.show({
title: 'Location Permission',
message:'Grant access to the device location?',
primaryButton: {
value: 'cancel',
action: () => {
event.geolocation.invoke(event.origin, false, false); // Deny access to the device location.
}
},
secondaryButton: {
value: 'ok',
action: () => {
event.geolocation.invoke(event.origin, true, false); // Allow access to the device location.
}
},
cancel: () => {
event.geolocation.invoke(event.origin, false, false); // Deny access to the device location.
}
})
})
}
}
}
```
# 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.
- Frontend page code:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<script>
function htmlTest() {
console.info('JavaScript Hello World! ');
}
</script>
</body>
</html>
```
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('index.html'), controller: this.webviewController})
Button('runJavaScript')
.onClick(() => {
this.webviewController.runJavaScript('htmlTest()');
})
}
}
}
```
# 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):
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
// Declare the object to be registered.
testObj = {
test: () => {
return 'ArkTS Hello World!';
}
}
build() {
Column() {
// Load the local index.html page.
Web({ src: $rawfile('index.html'), controller: this.webviewController})
// Inject the object to the web client.
.javaScriptProxy({
object: this.testObj,
name: "testObjName",
methodList: ["test"],
controller: this.webviewController
})
}
}
}
```
- Sample code for using [registerJavaScriptProxy()](../reference/apis/js-apis-webview.md#registerjavascriptproxy):
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct Index {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
testObj = {
test: (data) => {
return "ArkUI Web Component";
},
toString: () => {
console.info('Web Component toString');
}
}
build() {
Column() {
Button('refresh')
.onClick(() => {
try {
this.webviewController.refresh();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Button('Register JavaScript To Window')
.onClick(() => {
try {
this.webviewController.registerJavaScriptProxy(this.testObj, "objName", ["test", "toString"]);
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: $rawfile('index.html'), controller: this.webviewController })
}
}
}
```
> **NOTE**
>
> 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:
```html
<!-- index.html -->
<!DOCTYPE html>
<html>
<body>
<button type="button" onclick="callArkTS()">Click Me!</button>
<p id="demo"></p>
<script>
function callArkTS() {
let str = testObjName.test();
document.getElementById("demo").innerHTML = str;
console.info('ArkTS Hello World! :' + str);
}
</script>
</body>
</html>
```
# Opening Pages in a New Window
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).
```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:$rawfile("window.html"), controller: this.controller })
.multiWindowAccess(true)
.onWindowNew((event) => {
console.info("onWindowNew...");
var popController: web_webview.WebviewController = new web_webview.WebviewController();
// 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>
<meta charset="utf-8">
<title>WindowEvent</title>
</head>
<body>
<input type="button" value="Open Page in New Window" onclick="OpenNewWindow()">
<script type="text/javascript">
function OpenNewWindow()
{
let openedWindow = window.open("about:blank", "", "location=no,status=no,scrollvars=no");
if (openedWindow) {
openedWindow.document.body.write("<p>This is my window</p>");
} else {
log.innerHTML = "window.open failed";
}
}
</script>
</body>
</html>
```
# Loading Pages by Using the Web Component
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**.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Upon button clicking, call loadUrl to redirect to www.example1.com.
this.webviewController.loadUrl('www.example1.com');
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// When creating a Web component, set the default network page to be loaded to www.example.com.
Web({ src: 'www.example.com', controller: this.webviewController})
}
}
}
```
## Loading Local Pages
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:
**Figure 1** Path of local page files
![resource-path](figures/resource-path.png)
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadUrl')
.onClick(() => {
try {
// Upon button clicking, call loadUrl to redirect to local1.html.
this.webviewController.loadUrl($rawfile("local1.html"));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// When creating a Web component, load the local.html file through $rawfile.
Web({ src: $rawfile("local.html"), controller: this.webviewController })
}
}
}
```
- Code of the **local.html** page:
```html
<!-- local.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
## Loading HTML Rich Text Data
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.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadData')
.onClick(() => {
try {
// Upon button clicking, call loadData to load HTML rich text data.
this.controller.loadData(
'<html><body bgcolor=\"white\">Source:<pre>source</pre></body></html>',
'text/html',
'UTF-8'
);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
// When creating a Web component, set the default network page to be loaded to www.example.com.
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
# 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.
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Button('loadData')
.onClick(() => {
if (this.webviewController.accessBackward()) {
this.webviewController.backward();
return true;
}
})
Web({ src: 'https://www.example.com/cn/', controller: this.webviewController})
}
}
}
```
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.
- Code of the **index.ets** page:
```ts
// index.ets
import web_webview from '@ohos.web.webview';
import router from '@ohos.router';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('route.html'), controller: this.webviewController })
.onUrlLoadIntercept((event) => {
let url: string = event.data as string;
if (url.indexOf('native://') === 0) {
// Redirect to another page.
router.pushUrl({ url:url.substring(9) })
return true;
}
return false;
})
}
}
}
```
- Code of the **route.html** page:
```html
<!-- route.html -->
<!DOCTYPE html>
<html>
<body>
<div>
<a href="native://pages/ProfilePage">My Profile</a>
</div>
</body>
</html>
```
- Code of the **ProfilePage.ets** page:
```ts
@Entry
@Component
struct ProfilePage {
@State message: string = 'Hello World';
build() {
Column() {
Text(this.message)
.fontSize(20)
}
}
}
```
## Cross-Application Redirection
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.
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
import call from '@ohos.telephony.call';
@Entry
@Component
struct WebComponent {
webviewController: web_webview.WebviewController = new web_webview.WebviewController();
build() {
Column() {
Web({ src: $rawfile('xxx.html'), controller: this.webviewController})
.onUrlLoadIntercept((event) => {
let url: string = event.data as string;
// Check whether the link is redirecting to the dial screen of the phone app.
if (url.indexOf('tel://') === 0) {
// Redirect to the dial screen.
call.makeCall(url.substring(6), (err) => {
if (!err) {
console.info('make call succeeded.');
} else {
console.info('make call fail, err is:' + JSON.stringify(err));
}
});
return true;
}
return false;
})
}
}
}
```
- Code of the **call.html** page:
```html
<!-- call.html -->
<!DOCTYPE html>
<html>
<body>
<div>
<a href="tel://xxx xxxx xxx">Dial number</a>
</div>
</body>
</html>
```
# Customizing Page Request Responses
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.
- Code of the **example.html** page:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
</head>
<body>
<!-- Page resource request ->
<a href="https://www.intercept.com/test.html">intercept test!</a>
</body>
</html>
```
- Application code:
```ts
// xxx.ets
import web_webview from '@ohos.web.webview';
@Entry
@Component
struct WebComponent {
controller: web_webview.WebviewController = new web_webview.WebviewController()
responseResource: WebResourceResponse = new WebResourceResponse()
// Customize a response.
@State webData: string = '<!DOCTYPE html>\n' +
'<html>\n'+
'<head>\n'+
'<title>intercept test</title>\n'+
'</head>\n'+
'<body>\n'+
'<h1>intercept ok</h1>\n'+
'</body>\n'+
'</html>'
build() {
Column() {
Web({ src: $rawfile('example.html'), controller: this.controller })
.onInterceptRequest((event) => {
console.info('url:' + event.request.getRequestUrl());
// Intercept the web page request.
if (event.request.getRequestUrl() !== 'https://www.intercept.com/test.html') {
return null;
}
// Construct a custom response.
this.responseResource.setResponseData(this.webData);
this.responseResource.setResponseEncoding('utf-8');
this.responseResource.setResponseMimeType('text/html');
this.responseResource.setResponseCode(200);
this.responseResource.setReasonMessage('OK');
return this.responseResource;
})
}
}
}
```
# Setting the Dark Mode
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();
@State mode: WebDarkMode = WebDarkMode.Auto;
build() {
Column() {
Web({ src: 'www.example.com', controller: this.controller })
.darkMode(this.mode)
}
}
}
```
- 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();
@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)
}
}
}
```
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册