• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Web
2
3Web是提供网页显示能力的组件,具体用法请参考 [Web API](../reference/arkui-ts/ts-basic-components-web.md)。
4
5## 创建组件
6
7main/ets/MainAbility/pages目录下的ets文件中创建一个Web组件。在web组件中通过src指定引用的网页路径,controller为组件的控制器,通过controller绑定Web组件,用于调用Web组件的方法。
8
9  ```ts
10  // xxx.ets
11  import web_webview from '@ohos.web.webview';
12
13  @Entry
14  @Component
15  struct WebComponent {
16    controller: web_webview.WebviewController = new web_webview.WebviewController();
17    build() {
18      Column() {
19        Web({ src: 'https://www.example.com', controller: this.controller })
20      }
21    }
22  }
23  ```
24
25## 设置样式和属性
26
27Web组件的使用需要添加丰富的页面样式和功能属性。设置height、padding样式可为Web组件添加高和内边距,设置fileAccess属性可为Web组件添加文件访问权限,设置javaScriptAccess属性为true使Web组件具有执行JavaScript代码的能力。
28
29```ts
30// xxx.ets
31import web_webview from '@ohos.web.webview';
32
33@Entry
34@Component
35struct WebComponent {
36  fileAccess: boolean = true;
37  controller: web_webview.WebviewController = new web_webview.WebviewController();
38  build() {
39    Column() {
40      Text('Hello world!')
41        .fontSize(20)
42      Web({ src: 'https://www.example.com', controller: this.controller })
43        // 设置高和内边距
44        .height(500)
45        .padding(20)
46        // 设置文件访问权限和脚本执行权限
47        .fileAccess(this.fileAccess)
48        .javaScriptAccess(true)
49      Text('End')
50        .fontSize(20)
51    }
52  }
53}
54```
55## 添加事件和方法
56
57为Web组件添加onProgressChange事件,该事件回调Web引擎加载页面的进度值。将该进度值赋值给Progress组件的value,控制Progress组件的状态。当进度为100%时隐藏Progress组件,Web页面加载完成。
58
59```ts
60// xxx.ets
61import web_webview from '@ohos.web.webview';
62
63@Entry
64@Component
65struct WebComponent {
66  @State progress: number = 0;
67  @State hideProgress: boolean = true;
68  fileAccess: boolean = true;
69  controller: web_webview.WebviewController = new web_webview.WebviewController();
70  build() {
71    Column() {
72      Text('Hello world!')
73        .fontSize(20)
74      Progress({value: this.progress, total: 100})
75        .color('#0000ff')
76        .visibility(this.hideProgress ? Visibility.None : Visibility.Visible)
77      Web({ src: 'https://www.example.com', controller: this.controller })
78        .fileAccess(this.fileAccess)
79        .javaScriptAccess(true)
80        .height(500)
81        .padding(20)
82        // 添加onProgressChange事件
83        .onProgressChange(e => {
84          this.progress = e.newProgress;
85          // 当进度100%时,进度条消失
86          if (this.progress === 100) {
87            this.hideProgress = true;
88          } else {
89            this.hideProgress = false;
90          }
91        })
92      Text('End')
93        .fontSize(20)
94    }
95  }
96}
97```
98在onPageEnd事件中添加runJavaScript方法。onPageEnd事件是网页加载完成时的回调,runJavaScript方法可以执行HTML中的JavaScript脚本。当页面加载完成时,触发onPageEnd事件,调用HTML文件中的test方法,在控制台打印信息。
99
100```ts
101// xxx.ets
102import web_webview from '@ohos.web.webview';
103
104@Entry
105@Component
106struct WebComponent {
107  @State progress: number = 0;
108  @State hideProgress: boolean = true;
109  @State webResult: string = ''
110  fileAccess: boolean = true;
111  // 定义Web组件的控制器controller
112  controller: web_webview.WebviewController = new web_webview.WebviewController();
113  build() {
114    Column() {
115      Text('Hello world!')
116        .fontSize(20)
117      Progress({value: this.progress, total: 100})
118        .color('#0000ff')
119        .visibility(this.hideProgress ? Visibility.None : Visibility.Visible)
120      // 初始化Web组件,并绑定controller
121      Web({ src: $rawfile('index.html'), controller: this.controller })
122        .fileAccess(this.fileAccess)
123        .javaScriptAccess(true)
124        .height(500)
125        .padding(20)
126        .onProgressChange(e => {
127          this.progress = e.newProgress;
128          if (this.progress === 100) {
129            this.hideProgress = true;
130          } else {
131            this.hideProgress = false;
132          }
133        })
134        .onPageEnd(e => {
135          // test()在index.html中定义
136          try {
137            this.controller.runJavaScript(
138              'test()',
139              (error, result) => {
140                if (error) {
141                  console.info(`run JavaScript error: ` + JSON.stringify(error))
142                  return;
143                }
144                if (result) {
145                  this.webResult = result
146                  console.info(`The test() return value is: ${result}`)
147                }
148              });
149            console.info('url: ', e.url);
150          } catch (error) {
151            console.error(`ErrorCode: ${error.code},  Message: ${error.message}`);
152          }
153        })
154      Text('End')
155        .fontSize(20)
156    }
157  }
158}
159```
160
161main/resources/rawfile目录下创建一个HTML文件。
162
163```html
164<!-- index.html -->
165<!DOCTYPE html>
166<html>
167<meta charset="utf-8">
168<body>
169    Hello world!
170</body>
171<script type="text/javascript">
172  function test() {
173      console.info('Ark Web Component');
174  }
175</script>
176</html>
177```
178
179## 开启网页调试
180在PC上启用端口转发,以及设置Web组件属性webDebuggingAccess为true后,便可以在PC上调试通过USB连接的开发设备上的Web组件里的网页。
181
182设置步骤如下:
183
1841、首先设置Web组件属性webDebuggingAccess为true。
185  ```ts
186  // xxx.ets
187  import web_webview from '@ohos.web.webview';
188
189  @Entry
190  @Component
191  struct WebComponent {
192    controller: web_webview.WebviewController = new web_webview.WebviewController();
193    build() {
194      Column() {
195        Web({ src: 'www.example.com', controller: this.controller })
196          .webDebuggingAccess(true) // true表示启用调试功能
197      }
198    }
199  }
200  ```
201
2022、PC上启用端口转发功能,添加TCP端口9222映射。
203  ```ts
204  hdc fport tcp:9222 tcp:9222
205  ```
206  添加是否成功可以通过如下命令来查看已存在的映射关系表。
207  ```ts
208  hdc fport ls
209  ```
210如上设置完成后,首先打开应用Web组件、访问要调试的网页,然后在PC上使用chrome浏览器访问:http://localhost:9222, 就可以在PC上调试开发设备刚才访问的网页。
211
212## 场景示例
213
214该场景实现了Web组件中视频的动态播放。首先在HTML页面内嵌入视频资源,再使用Web组件的控制器调用onActive和onInactive方法激活和暂停页面渲染。点击onInactive按钮,Web页面停止渲染,视频暂停播放;点击onActive按钮,激活Web组件,视频继续播放。
215
216  ```ts
217  // xxx.ets
218import web_webview from '@ohos.web.webview';
219
220@Entry
221@Component
222struct WebComponent {
223  controller: web_webview.WebviewController = new web_webview.WebviewController();
224  build() {
225    Column() {
226      Row() {
227        Button('onActive').onClick(() => {
228          console.info("Web Component onActive");
229          try {
230            this.controller.onActive();
231          } catch (error) {
232            console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
233          }
234        })
235        Button('onInactive').onClick(() => {
236          console.info("Web Component onInactive");
237          try {
238            this.controller.onInactive();
239          } catch (error) {
240            console.error(`Errorcode: ${error.code}, Message: ${error.message}`);
241          }
242        })
243      }
244      Web({ src: $rawfile('index.html'), controller: this.controller })
245        .fileAccess(true)
246    }
247  }
248}
249  ```
250
251  ```html
252  <!-- index.html -->
253  <!DOCTYPE html>
254  <html>
255  <meta charset="utf-8">
256  <body>
257      <video width="320" height="240" controls="controls" muted="muted" autoplay="autoplay">
258          <!-- test.mp4视频文件放在main/resources/rawfile目录下 -->
259          <source src="test.mp4" type="video/mp4">
260      </video>
261  </body>
262  </html>
263  ```
264
265## 相关实例
266
267针对Web开发,有以下相关实例可供参考:
268
269- [`Web`:Web(ArkTS)(API8)](https://gitee.com/openharmony/applications_app_samples/tree/OpenHarmony-3.2-Release/ETSUI/Web)
270
271- [Web组件的使用(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebCookie)
272
273- [Web组件抽奖案例(ArkTS)(API9)](https://gitee.com/openharmony/codelabs/tree/master/ETSUI/WebComponent)