提交 f527fee6 编写于 作者: E ester.zhou

Update docs (14175)

Signed-off-by: Nester.zhou <ester.zhou@huawei.com>
上级 74931a3c
...@@ -42,13 +42,13 @@ arkXtest is divided into two parts: unit test framework and UI test framework. ...@@ -42,13 +42,13 @@ arkXtest is divided into two parts: unit test framework and UI test framework.
- The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md). - The feature availability of the unit test framework varies by version. For details about the mappings between the features and versions, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md).
## Environment preparations ## Preparing the Environment
### Environment Requirements ### Environment Requirements
Software for writing test scripts: DevEco Studio 3.0 or later Software for writing test scripts: DevEco Studio 3.0 or later
Hardware for running test scripts: PC connected to a OpenHarmony device, such as the RK3568 development board Hardware for running test scripts: PC connected to an OpenHarmony device, such as the RK3568 development board
### Setting Up the Environment ### Setting Up the Environment
...@@ -63,8 +63,8 @@ Hardware for running test scripts: PC connected to a OpenHarmony device, such as ...@@ -63,8 +63,8 @@ Hardware for running test scripts: PC connected to a OpenHarmony device, such as
## Writing a Unit Test Script ## Writing a Unit Test Script
```TS ```TS
import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium';
import abilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import abilityDelegatorRegistry from '@ohos.app.ability.abilityDelegatorRegistry';
const delegator = abilityDelegatorRegistry.getAbilityDelegator() const delegator = abilityDelegatorRegistry.getAbilityDelegator()
export default function abilityTest() { export default function abilityTest() {
...@@ -72,7 +72,7 @@ export default function abilityTest() { ...@@ -72,7 +72,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) { it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin"); console.info("uitest: TestUiExample begin");
//start tested ability //start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
console.info('Uitest, start ability finished:' + result) console.info('Uitest, start ability finished:' + result)
}).catch(err => { }).catch(err => {
console.info('Uitest, start ability failed: ' + err) console.info('Uitest, start ability failed: ' + err)
...@@ -81,7 +81,7 @@ export default function abilityTest() { ...@@ -81,7 +81,7 @@ export default function abilityTest() {
//check top display ability //check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{ await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability"); console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
}) })
done(); done();
}) })
...@@ -119,7 +119,7 @@ export default function abilityTest() { ...@@ -119,7 +119,7 @@ export default function abilityTest() {
it('testUiExample',0, async function (done) { it('testUiExample',0, async function (done) {
console.info("uitest: TestUiExample begin"); console.info("uitest: TestUiExample begin");
//start tested ability //start tested ability
await delegator.executeShellCommand('aa start -b com.ohos.uitest -a MainAbility').then(result =>{ await delegator.executeShellCommand('aa start -b com.ohos.uitest -a EntryAbility').then(result =>{
console.info('Uitest, start ability finished:' + result) console.info('Uitest, start ability finished:' + result)
}).catch(err => { }).catch(err => {
console.info('Uitest, start ability failed: ' + err) console.info('Uitest, start ability failed: ' + err)
...@@ -128,7 +128,7 @@ export default function abilityTest() { ...@@ -128,7 +128,7 @@ export default function abilityTest() {
//check top display ability //check top display ability
await delegator.getCurrentTopAbility().then((Ability)=>{ await delegator.getCurrentTopAbility().then((Ability)=>{
console.info("get top ability"); console.info("get top ability");
expect(Ability.context.abilityInfo.name).assertEqual('MainAbility'); expect(Ability.context.abilityInfo.name).assertEqual('EntryAbility');
}) })
//ui test code //ui test code
//init uidriver //init uidriver
...@@ -154,20 +154,180 @@ export default function abilityTest() { ...@@ -154,20 +154,180 @@ export default function abilityTest() {
## Running the Test Script ## Running the Test Script
### In DevEco Studio
You can run a test script in DevEco Studio in any of the following modes: You can run a test script in DevEco Studio in any of the following modes:
- Test package level: All test cases in the test package are executed. 1. Test package level: All test cases in the test package are executed.
- Test suite level: All test cases defined in the **describe** method are executed.
- Test method level: The specified **it** method, that is, a single test case, is executed. 2. Test suite level: All test cases defined in the **describe** method are executed.
3. Test method level: The specified **it** method, that is, a single test case, is executed.
![](figures/Execute.PNG) ![](figures/Execute.PNG)
## Viewing the Test Result **Viewing the Test Result**
After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure. After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure.
![](figures/TestResult.PNG) ![](figures/TestResult.PNG)
### In the CLI
To run a test script in the CLI, execute **aa** commands with different execution control keywords.
Parameters in aa test commands
| Keyword | Abbreviation| Description | Example |
| ------------- | ------------ | -------------------------------------- | ---------------------------------- |
| --bundleName | -b | Application bundle name. | - b com.test.example |
| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry |
| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry |
| NA | -s | \<key, value> pair.| - s unittest OpenHarmonyTestRunner |
The framework supports multiple test case execution modes, which are triggered by the key-value pair following the **-s** keyword. The table below lists the available keys and values.
| Key | Description | Value | Parameter |
| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- |
| unittest | OpenHarmonyTestRunner object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner |
| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt |
| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt |
| itName | Test case to be executed. | {itName} | -s itName testAttributeIt |
| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value 5000 is used. | -s timeout 15000 |
| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion error or any other error occurs.| **true**/**false** (default value) | -s breakOnError true |
| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function |
| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 |
| size | Size of the test case to be executed. | small, medium, large | -s size small |
| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 |
**Running Commands**
> Configure hdc-related environment variables, and then perform the following:
- Open the CLI.
- Run the **aa test** commands.
Example 1: Execute all test cases.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner
```
Example 2: Execute cases in the specified test suites, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class s1,s2
```
Example 3: Execute specified cases in the specified test suites, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0
```
Example 4: Execute all test cases except the specified ones, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s notClass testStop
```
Example 5: Execute specified test cases, separated by commas (,).
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s itName stop_0
```
Example 6: Set the timeout interval for executing a test case.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s timeout 15000
```
Example 7: Enable break-on-error mode.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s breakOnError true
```
Example 8: Execute test cases of the specified type.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s testType function
```
Example 9: Execute test cases at the specified level.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s level 0
```
Example 10: Execute test cases with the specified size.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s size small
```
Example 11: Execute test cases for a specified number of times.
```shell
hdc shell aa test -b xxx -p xxx -s unittest OpenHarmonyTestRunner -s stress 1000
```
**Viewing the Test Result**
- During test execution in the CLI, the log information similar to the following is displayed:
```
OHOS_REPORT_STATUS: class=testStop
OHOS_REPORT_STATUS: current=1
OHOS_REPORT_STATUS: id=JS
OHOS_REPORT_STATUS: numtests=447
OHOS_REPORT_STATUS: stream=
OHOS_REPORT_STATUS: test=stop_0
OHOS_REPORT_STATUS_CODE: 1
OHOS_REPORT_STATUS: class=testStop
OHOS_REPORT_STATUS: current=1
OHOS_REPORT_STATUS: id=JS
OHOS_REPORT_STATUS: numtests=447
OHOS_REPORT_STATUS: stream=
OHOS_REPORT_STATUS: test=stop_0
OHOS_REPORT_STATUS_CODE: 0
OHOS_REPORT_STATUS: consuming=4
```
| Log Field | Description |
| ------- | -------------------------|
| OHOS_REPORT_SUM | Total number of test cases in the current test suite.|
| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.|
| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. |
| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.|
| OHOS_REPORT_STATUS: stream | Error information of the current test case.|
| OHOS_REPORT_STATUS: test| Name of the current test case.|
| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. The options are as follows:<br>**0**: pass<br>**1**: error<br>**2**: fail|
| OHOS_REPORT_STATUS: consuming | Execution duration of the current test case.|
- After the commands are executed, the log information similar to the following is displayed:
```
OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245
OHOS_REPORT_CODE: 0
OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error
OHOS_REPORT_STATUS: taskconsuming=16029
```
| Log Field | Description |
| ------------------| -------------------------|
| run | Total number of test cases in the current test package.|
| Failure | Number of failed test cases.|
| Error | Number of test cases whose execution encounters errors. |
| Pass | Number of passed test cases.|
| Ignore | Number of test cases not executed.|
| taskconsuming| Total time spent in executing the current test case.|
> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information.
## FAQs ## FAQs
### FAQs About Unit Test Cases ### FAQs About Unit Test Cases
...@@ -182,7 +342,7 @@ The logs added to the test case are displayed after the test case execution, rat ...@@ -182,7 +342,7 @@ The logs added to the test case are displayed after the test case execution, rat
More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete. More than one asynchronous interface is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete.
**Solution** **Solution**
If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode If more than one asynchronous interface is called, you are advised to encapsulate the interface invoking into the promise mode
...@@ -209,14 +369,18 @@ After the test case execution is complete, the console displays the error messag ...@@ -209,14 +369,18 @@ After the test case execution is complete, the console displays the error messag
**Possible Causes** **Possible Causes**
1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. 1. The test case is executed through an asynchronous interface, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out.
2. The time taken for API invocation is longer than the timeout interval set for test case execution. 2. The time taken for API invocation is longer than the timeout interval set for test case execution.
3. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until the timeout expires.
**Solution** **Solution**
1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails. 1. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails.
2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. 2. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio.
3. Check the code logic and assertion result of the test case and make sure that the assertion is passed.
### FAQs About UI Test Cases ### FAQs About UI Test Cases
#### The failure log contains "Get windows failed/GetRootByWindow failed" #### The failure log contains "Get windows failed/GetRootByWindow failed"
...@@ -237,11 +401,11 @@ Run the following command, restart the device, and execute the test case again: ...@@ -237,11 +401,11 @@ Run the following command, restart the device, and execute the test case again:
hdc shell param set persist.ace.testmode.enabled 1 hdc shell param set persist.ace.testmode.enabled 1
``` ```
#### The failure log contains "uitest-api dose not allow calling concurrently" #### The failure log contains "uitest-api does not allow calling concurrently"
**Problem** **Problem**
The UI test case fails to be executed. The HiLog file contains the error message "uitest-api dose not allow calling concurrently". The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently".
**Possible Causes** **Possible Causes**
...@@ -255,11 +419,11 @@ The UI test case fails to be executed. The HiLog file contains the error message ...@@ -255,11 +419,11 @@ The UI test case fails to be executed. The HiLog file contains the error message
2. Do not execute UI test cases in multiple processes. 2. Do not execute UI test cases in multiple processes.
#### The failure log contains "dose not exist on current UI! Check if the UI has changed after you got the widget object" #### The failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object"
**Problem** **Problem**
The UI test case fails to be executed. The HiLog file contains the error message "dose not exist on current UI! Check if the UI has changed after you got the widget object". The UI test case fails to be executed. The HiLog file contains the error message "does not exist on current UI! Check if the UI has changed after you got the widget object".
**Possible Causes** **Possible Causes**
......
...@@ -305,6 +305,7 @@ struct WebComponent { ...@@ -305,6 +305,7 @@ struct WebComponent {
Button('loadUrl') Button('loadUrl')
.onClick(() => { .onClick(() => {
try { try {
// The URL to be loaded is of the string type.
this.controller.loadUrl('www.example.com'); this.controller.loadUrl('www.example.com');
} catch (error) { } catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`); console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
...@@ -316,6 +317,69 @@ struct WebComponent { ...@@ -316,6 +317,69 @@ struct WebComponent {
} }
``` ```
```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('loadUrl')
.onClick(() => {
try {
// The headers parameter is carried.
this.controller.loadUrl('www.example.com', [{headerKey: "headerKey", headerValue: "headerValue"}]);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
.webDebuggingAccess(true)
}
}
}
```
```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('loadUrl')
.onClick(() => {
try {
// The URL to be loaded is of the Resource type.
this.controller.loadUrl($rawfile('xxx.html'));
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
})
Web({ src: 'www.example.com', controller: this.controller })
}
}
}
```
```html
<!-- xxx.html -->
<!DOCTYPE html>
<html>
<body>
<p>Hello World</p>
</body>
</html>
```
### loadData ### loadData
loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void loadData(data: string, mimeType: string, encoding: string, baseUrl?: string, historyUrl?: string): void
...@@ -987,7 +1051,7 @@ Executes a JavaScript script. This API uses a promise to return the script execu ...@@ -987,7 +1051,7 @@ Executes a JavaScript script. This API uses a promise to return the script execu
| Type | Description | | Type | Description |
| --------------- | --------------------------------------------------- | | --------------- | --------------------------------------------------- |
| Promise\<string> | Callback used to return the result. Returns **null** if the JavaScript script fails to be executed| | Promise\<string> | Promise used to return the result. Returns **null** if the JavaScript script fails to be executed|
**Error codes** **Error codes**
...@@ -4101,7 +4165,7 @@ Checks whether any saved HTTP authentication credentials exist. This API returns ...@@ -4101,7 +4165,7 @@ Checks whether any saved HTTP authentication credentials exist. This API returns
| Type | Description | | Type | Description |
| ------- | ------------------------------------------------------------ | | ------- | ------------------------------------------------------------ |
| boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist exists; returns **false** otherwise.| | boolean | Whether any saved HTTP authentication credentials exist. Returns **true** if any saved HTTP authentication credentials exist; returns **false** otherwise. |
**Example** **Example**
......
...@@ -21,6 +21,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController}) ...@@ -21,6 +21,7 @@ Web(options: { src: ResourceStr, controller: WebController | WebviewController})
> **NOTE** > **NOTE**
> >
> Transition animation is not supported. > Transition animation is not supported.
> Different **\<Web>** components on the same page must be bound to different **WebController**s.
**Parameters** **Parameters**
...@@ -526,7 +527,7 @@ Sets whether to enable the multi-window permission. ...@@ -526,7 +527,7 @@ Sets whether to enable the multi-window permission.
horizontalScrollBarAccess(horizontalScrollBar: boolean) horizontalScrollBarAccess(horizontalScrollBar: boolean)
Sets whether to display the horizontal scrollbar, including the system default scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed. Sets whether to display the horizontal scrollbar, including the default system scrollbar and custom scrollbar. By default, the horizontal scrollbar is displayed.
**Parameters** **Parameters**
...@@ -577,7 +578,7 @@ Sets whether to display the horizontal scrollbar, including the system default s ...@@ -577,7 +578,7 @@ Sets whether to display the horizontal scrollbar, including the system default s
verticalScrollBarAccess(verticalScrollBar: boolean) verticalScrollBarAccess(verticalScrollBar: boolean)
Sets whether to display the vertical scrollbar, including the system default scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed. Sets whether to display the vertical scrollbar, including the default system scrollbar and custom scrollbar. By default, the vertical scrollbar is displayed.
**Parameters** **Parameters**
...@@ -1539,7 +1540,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp ...@@ -1539,7 +1540,7 @@ onDownloadStart(callback: (event?: { url: string, userAgent: string, contentDisp
onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void) onErrorReceive(callback: (event?: { request: WebResourceRequest, error: WebResourceError }) => void)
Called when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. Called when an error occurs during web page loading. For better results, simplify the implementation logic in the callback. This API is called when there is no network connection.
**Parameters** **Parameters**
...@@ -1764,7 +1765,7 @@ Called when the document title of the web page is changed. ...@@ -1764,7 +1765,7 @@ Called when the document title of the web page is changed.
onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void) onRefreshAccessedHistory(callback: (event?: { url: string, isRefreshed: boolean }) => void)
Called when loading of the web page is complete. This API is used by an application to update the historical link it accessed.. Called when loading of the web page is complete. This API is used by an application to update the historical link it accessed.
**Parameters** **Parameters**
...@@ -1950,7 +1951,7 @@ Called when the display ratio of this page changes. ...@@ -1950,7 +1951,7 @@ Called when the display ratio of this page changes.
onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean) onUrlLoadIntercept(callback: (event?: { data:string | WebResourceRequest }) => boolean)
Called when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access. Called when the **\<Web>** component is about to access a URL. This API is used to determine whether to block the access, which is allowed by default.
**Parameters** **Parameters**
...@@ -2326,8 +2327,8 @@ Called when the scrollbar of the page scrolls. ...@@ -2326,8 +2327,8 @@ Called when the scrollbar of the page scrolls.
| Name | Type | Description | | Name | Type | Description |
| ------- | ------ | ------------ | | ------- | ------ | ------------ |
| xOffset | number | Position of the scrollbar on the x-axis.| | xOffset | number | Position of the scrollbar on the x-axis relative to the leftmost of the web page.|
| yOffset | number | Position of the scrollbar on the y-axis.| | yOffset | number | Position of the scrollbar on the y-axis relative to the top of the web page.|
**Example** **Example**
...@@ -2668,7 +2669,7 @@ Called when the old page is not displayed and the new page is about to be visibl ...@@ -2668,7 +2669,7 @@ Called when the old page is not displayed and the new page is about to be visibl
onInterceptKeyEvent(callback: (event: KeyEvent) => boolean) onInterceptKeyEvent(callback: (event: KeyEvent) => boolean)
Called when the key event is intercepted, before being consumed by the Webview. Called when the key event is intercepted and before it is consumed by the Webview.
**Parameters** **Parameters**
......
...@@ -8,10 +8,12 @@ Create a **\<Web>** component in the .ets file under **main/ets/MainAbility/page ...@@ -8,10 +8,12 @@ Create a **\<Web>** component in the .ets file under **main/ets/MainAbility/page
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Web({ src: 'https://www.example.com', controller: this.controller }) Web({ src: 'https://www.example.com', controller: this.controller })
...@@ -26,11 +28,13 @@ When using the **\<Web>** component, you must specify the styles and attributes. ...@@ -26,11 +28,13 @@ When using the **\<Web>** component, you must specify the styles and attributes.
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
fileAccess: boolean = true; fileAccess: boolean = true;
controller: WebController = new WebController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Text('Hello world!') Text('Hello world!')
...@@ -54,13 +58,15 @@ Add the **onProgressChange** event for the **\<Web>** component, which is trigge ...@@ -54,13 +58,15 @@ Add the **onProgressChange** event for the **\<Web>** component, which is trigge
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
@State progress: number = 0; @State progress: number = 0;
@State hideProgress: boolean = true; @State hideProgress: boolean = true;
fileAccess: boolean = true; fileAccess: boolean = true;
controller: WebController = new WebController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Text('Hello world!') Text('Hello world!')
...@@ -93,14 +99,17 @@ Add the **runJavaScript** method to the **onPageEnd** event. The **onPageEnd** e ...@@ -93,14 +99,17 @@ Add the **runJavaScript** method to the **onPageEnd** event. The **onPageEnd** e
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
@State progress: number = 0; @State progress: number = 0;
@State hideProgress: boolean = true; @State hideProgress: boolean = true;
@State webResult: string = ''
fileAccess: boolean = true; fileAccess: boolean = true;
// Define the controller for the \<Web> component. // Define the controller for the \<Web> component.
controller: WebController = new WebController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Text('Hello world!') Text('Hello world!')
...@@ -124,8 +133,23 @@ struct WebComponent { ...@@ -124,8 +133,23 @@ struct WebComponent {
}) })
.onPageEnd(e => { .onPageEnd(e => {
// test() is defined in index.html. // test() is defined in index.html.
this.controller.runJavaScript({ script: 'test()' }); try {
this.controller.runJavaScript(
'test()',
(error, result) => {
if (error) {
console.info(`run JavaScript error: ` + JSON.stringify(error))
return;
}
if (result) {
this.webResult = result
console.info(`The test() return value is: ${result}`)
}
});
console.info('url: ', e.url); console.info('url: ', e.url);
} catch (error) {
console.error(`ErrorCode: ${error.code}, Message: ${error.message}`);
}
}) })
Text('End') Text('End')
.fontSize(20) .fontSize(20)
...@@ -160,10 +184,12 @@ The configuration procedure is as follows: ...@@ -160,10 +184,12 @@ The configuration procedure is as follows:
1. Set the **webDebuggingAccess** attribute of the **\<Web>** component to **true**. 1. Set the **webDebuggingAccess** attribute of the **\<Web>** component to **true**.
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController() controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Web({ src: 'www.example.com', controller: this.controller }) Web({ src: 'www.example.com', controller: this.controller })
...@@ -189,20 +215,30 @@ In this example, you'll implement a **\<Web>** component where videos can be pla ...@@ -189,20 +215,30 @@ In this example, you'll implement a **\<Web>** component where videos can be pla
```ts ```ts
// xxx.ets // xxx.ets
import web_webview from '@ohos.web.webview';
@Entry @Entry
@Component @Component
struct WebComponent { struct WebComponent {
controller: WebController = new WebController(); controller: web_webview.WebviewController = new web_webview.WebviewController();
build() { build() {
Column() { Column() {
Row() { Row() {
Button('onActive').onClick(() => { Button('onActive').onClick(() => {
console.info("Web Component onActive"); console.info("Web Component onActive");
try {
this.controller.onActive(); this.controller.onActive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
}) })
Button('onInactive').onClick(() => { Button('onInactive').onClick(() => {
console.info("Web Component onInactive"); console.info("Web Component onInactive");
try {
this.controller.onInactive(); this.controller.onInactive();
} catch (error) {
console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
}
}) })
} }
Web({ src: $rawfile('index.html'), controller: this.controller }) Web({ src: $rawfile('index.html'), controller: this.controller })
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册