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

!17821 翻译已完成16490+17323+web精品

Merge pull request !17821 from shawn_he/17323-d
......@@ -23,7 +23,8 @@ When an asynchronous callback is used, the return value can be processed directl
| API | Description |
| ------------------------------ | ------------------------------------------------------------ |
| onUnhandledException(errMsg: string): void | Called when an application generates an uncaught exception after being registered.|
| onUnhandledException(errMsg: string): void | Called when an uncaught exception is reported after the application is registered.|
| onException?(errObject: Error): void | Called when an application exception is reported to the JavaScript layer after the application is registered.|
### Result Codes for Unregistering an Observer
......@@ -43,6 +44,13 @@ let registerId = -1;
let callback = {
onUnhandledException: function (errMsg) {
console.log(errMsg);
},
onException: function (errorObj) {
console.log('onException, name: ', errorObj.name);
console.log('onException, message: ', errorObj.message);
if (typeof(errorObj.stack) === 'string') {
console.log('onException, stack: ', errorObj.stack);
}
}
}
......
# 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 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** frontend 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 [allowWindowOpenMethod()](../reference/arkui-ts/ts-basic-components-web.md#allowwindowopenmethod10) is set to **true**, you can open a new window in the frontend page by invoking its JavaScript functions.
>
> - 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#setwebcontroller9) 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 its setting not to follow the frontend page or system. 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)
}
}
}
```
......@@ -8,6 +8,7 @@ By default, OpenHarmony provides the battery level based on the current battery
### Constraints
The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy.
## How to Develop
......@@ -36,7 +37,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
├── battery_config.json
```
3. Write the custom `battery_config.json` file by referring to the `battery_config.json` file in the default folder of battery level configuration. For example:
3. Write the custom `battery_config.json` file by referring to the [battery_config.json](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json) file in the default folder of battery level configuration. For example:
```json
{
......@@ -54,7 +55,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
**Table 1** Battery level configuration
| Battery Bevel| Battery Volume| Description|
| Battery Level| Battery Volume| Description|
| -------- | -------- | -------- |
| shutdown | 5 | Power-off battery level|
| critical | 10 | Extremely low battery level|
......@@ -65,7 +66,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
| full | 100 | Full battery level|
4. Write the `BUILD.gn` file by referring to the `BUILD.gn` in the default folder of battery level configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/BUILD.gn) file in the default folder of battery level configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
```shell
import("//build/ohos.gni") # Reference build/ohos.gni.
......@@ -292,6 +293,8 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
## Reference
During development, you can refer to the [default battery level configuration](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json), as shown below:
```json
{
"soc": {
......@@ -306,4 +309,4 @@ During development, you can refer to the [default battery level configuration](h
}
```
Packing path: `/system/etc/battery`
Packing path: /system/etc/battery
......@@ -8,6 +8,7 @@ OpenHarmony provides the battery level and LED color mapping by default. Some pr
### Constraints
The configuration path for battery level customization is subject to the [configuration policy](https://gitee.com/openharmony/customization_config_policy). In this development guide, `/vendor` is used as an example of the configuration path. During actual development, you need to modify the customization path based on the product configuration policy.
## How to Develop
......@@ -36,7 +37,7 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
├── battery_config.json
```
3. Write the custom `battery_config.json` file by referring to the `battery_config.json` file in the default folder of battery level and LED color mapping configuration. For example:
3. Write the custom `battery_config.json` file by referring to the [battery_config.json](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json) file in the default folder of battery level and LED color mapping configuration. For example:
```json
{
......@@ -57,18 +58,23 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
}
```
**Table 1** Description of the battery level and LED color mapping configuration
**Table 1** Description of battery levels
| Item| Description|
| Battery Level| Description|
| -------- | -------- |
| low | Low battery level|
| normal | Normal battery level|
| high | High battery level|
**Table 2** Configuration items for the battery level range and LED color
| Configuration Item| Description|
| -------- | -------- |
| soc | Battery level range|
| rgb | LED RGB combination|
4. Write the `BUILD.gn` file by referring to the `BUILD.gn` in the default folder of battery level and LED color mapping configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
4. Write the `BUILD.gn` file by referring to the [BUILD.gn](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/BUILD.gn) file in the default folder of battery level and LED color mapping configuration to pack the `battery_config.json` file to the `//vendor/etc/battery` directory. The configuration is as follows:
```shell
import("//build/ohos.gni") # Reference build/ohos.gni.
......@@ -207,6 +213,8 @@ The following uses [DAYU200](https://gitee.com/openharmony/vendor_hihope/tree/ma
## Reference
During development, you can refer to the [default battery level and LED color mapping configuration](https://gitee.com/openharmony/powermgr_battery_manager/blob/master/services/native/profile/battery_config.json), as shown below:
```json
{
"light": {
......@@ -226,4 +234,4 @@ During development, you can refer to the [default battery level and LED color ma
}
```
Packing path: `/system/etc/battery`
Packing path: /system/etc/battery
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册