• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# 使用DevTools工具调试前端页面
2<!--Kit: ArkWeb-->
3<!--Subsystem: Web-->
4<!--Owner: @aohui-->
5<!--Designer: @yaomingliu-->
6<!--Tester: @ghiker-->
7<!--Adviser: @HelloCrease-->
8
9
10Web组件支持使用DevTools工具调试前端页面。DevTools是Web前端开发调试工具,支持在电脑上调试移动设备前端页面。开发者通过[setWebDebuggingAccess()](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess)接口开启Web组件前端页面调试能力,使用DevTools在电脑上调试移动前端网页,设备需为4.1.0及以上版本。
11
12## 无线调试
13从API version 20开始,可使用无线调试接口[setWebDebuggingAccess<sup>20+</sup>](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess20),来简化调试流程。
14
15### 应用代码开启Web调试开关
16
17调试网页前,需要应用侧代码调用setWebDebuggingAccess()接口开启Web调试开关。
18如果没有开启Web调试开关,则DevTools无法发现被调试的网页。
19
20   1. 在应用代码中开启Web调试开关,应用需要调用[setWebDebuggingAccess<sup>20+</sup>](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess20)接口,设置TCP Socket端口号并启用Web调试功能。
21   ```ts
22   // xxx.ets
23   import { webview } from '@kit.ArkWeb';
24   import { BusinessError } from '@kit.BasicServicesKit';
25
26   @Entry
27   @Component
28   struct WebComponent {
29     controller: webview.WebviewController = new webview.WebviewController();
30
31     aboutToAppear(): void {
32       try {
33         // 配置Web开启无线调试模式,指定TCP Socket的端口。
34         webview.WebviewController.setWebDebuggingAccess(true, 8888);
35       } catch (error) {
36         console.error(`ErrorCode: ${(error as BusinessError).code},  Message: ${(error as BusinessError).message}`);
37       }
38     }
39
40     build() {
41       Column() {
42         Web({ src: 'www.example.com', controller: this.controller })
43       }
44     }
45   }
46   ```
47   > **说明:**
48   >
49   >  代码中使用的8888端口仅作为示例展示,开发者使用过程中,应保证端口号可以被应用使用。如果因为端口被占用或者应用无权限使用等因素导致端口无法被应用使用,会导致接口抛出异常或者ArkWeb无法开启调试模式。
50   2. 开启调试功能需要在DevEco Studio应用工程hap模块的module.json5文件中增加如下权限,添加方法请参考[在配置文件中声明权限](../security/AccessToken/declare-permissions.md#在配置文件中声明权限)。
51
52   ```
53   "requestPermissions":[
54      {
55        "name" : "ohos.permission.INTERNET"
56      }
57    ]
58   ```
59
60### 在Chrome浏览器上打开调试工具页面
61
62   1. 在电脑端Chrome浏览器地址栏中输入调试工具地址 chrome://inspect/\#devices 并打开该页面。
63   2. 修改Chrome调试工具的配置。
64     确保已勾选 "Discover network targets",以便从指定的IP地址和端口号发现被调试网页。
65     (1) 点击 "Configure" 按钮。
66     (2) 在 "Target discovery settings" 中添加被调试设备的IP地址和[setWebDebuggingAccess<sup>20+</sup>](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess20)接口中指定的port端口,比如:192.168.0.3:8888。
67
68   > **说明:**
69   >
70   >  调试工具和被调试设备要在同一局域网下,并且能够相互访问。如果被调试设备有多个IP地址,要使用与调试工具同一个网段的IP地址。
71
72### 等待发现被调试页面
73
74  如果前面的步骤执行成功,Chrome的调试页面将显示待调试的网页。
75  ![chrome_inspect](figures/devtools_resources_chrome_inspect.jpg)
76
77### 开始网页调试
78
79  ![debug-effect](figures/debug-effect.png)
80
81## USB连接调试
82
83### 应用代码开启Web调试开关
84
85调试网页前,需要应用侧代码调用[setWebDebuggingAccess()](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess)接口开启Web调试开关。
86如果没有开启Web调试开关,则DevTools无法发现被调试的网页。
87
881. 在应用代码中开启Web调试开关,具体如下:
89
90   ```ts
91   // xxx.ets
92   import { webview } from '@kit.ArkWeb';
93
94   @Entry
95   @Component
96   struct WebComponent {
97     controller: webview.WebviewController = new webview.WebviewController();
98
99     aboutToAppear() {
100       // 配置Web开启调试模式
101       webview.WebviewController.setWebDebuggingAccess(true);
102     }
103
104     build() {
105       Column() {
106         Web({ src: 'www.example.com', controller: this.controller })
107       }
108     }
109   }
110   ```
1112. 开启调试功能需要在DevEco Studio应用工程hap模块的module.json5文件中增加如下权限,添加方法请参考[在配置文件中声明权限](../security/AccessToken/declare-permissions.md#在配置文件中声明权限)。
112
113   ```
114   "requestPermissions":[
115      {
116        "name" : "ohos.permission.INTERNET"
117      }
118    ]
119   ```
120
121### 将设备连接至电脑
122
123请将设备连接至电脑,随后开启开发者模式,为后续的端口转发操作做好准备。
124
1251. 请开启设备上的开发者模式,并启用USB调试功能。
126
127   (1) 终端系统查看“设置 > 系统”中是否有“开发者选项”,如果不存在,可在“设置 > 关于本机”连续七次单击“版本号”,直到提示“开启开发者模式”,点击“确认开启”后输入PIN码(如果已设置),设备将自动重启。
128
129   (2) USB数据线连接终端和电脑,在“设置 > 系统 > 开发者选项”中,打开“USB调试”开关,弹出的“允许USB调试”的弹框,点击“允许”。
130
1312. 使用hdc命令连接上设备。
132   打开命令行执行如下命令,查看hdc能否发现设备。
133   ```shell
134   hdc list targets
135   ```
136   - 如果命令返回设备的ID,表示hdc已连接上设备。
137   ![hdc_list_targets_success](figures/devtools_resources_hdc_list_targets_success.png)
138   - 如果命令返回 `[Empty]`,则说明hdc还没有发现设备。
139   ![hdc_list_targets_empty](figures/devtools_resources_hdc_list_targets_empty.jpg)
140
1413. 进入hdc shell。
142   连接设备后,执行以下命令进入hdc shell。
143   ```shell
144   hdc shell
145   ```
146
147### 端口转发
148当应用代码调用setWebDebuggingAccess接口开启Web调试开关后,ArkWeb内核将启动一个domain socket的监听,以此实现DevTools对网页的调试功能。也可以参考[自动映射WebView调试链接](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/ide-run-debug-configurations#section48387420516)149Chrome浏览器无法直接访问到设备上的domain socket, 因此需要将设备上的domain socket转发到电脑上。
150
1511. 先在hdc shell里执行如下命令,查询ArkWeb在设备里创建的domain socket。
152   ```shell
153   cat /proc/net/unix | grep devtools
154   ```
155   * 如果前几步操作无误,该命令的执行结果将显示用于查询的domain socket端口。
156   ![hdc_grep_devtools_38532](figures/devtools_resources_hdc_grep_devtools_38532.jpg)
157
158   * 如果没有查询到结果, 请再次确认。
159     (1) 应用开启了Web调试开关。
160     (2) 应用使用Web组件加载了网页。
161
1622. 将查询到的domain socket转发至电脑的TCP 9222端口。
163   执行exit退出hdc shell。
164   ```shell
165   exit
166   ```
167   在命令行里执行如下命令转发端口。
168   ```shell
169   hdc fport tcp:9222 localabstract:webview_devtools_remote_38532
170   ```
171   > **说明:**
172   >
173   > "webview_devtools_remote_" 后面的数字,代表ArkWeb所在应用的进程号, 该数字不是固定的。请将”webview_devtools_remote_“后面的数字改为自己查询到的值。
174   > 如果应用的进程号发生变化,例如,应用重新启动,则需要重新配置端口转发。
175
176   命令执行成功示意图:
177   ![hdc_fport_38532_success](figures/devtools_resources_hdc_fport_38532_success.jpg)
178
1793. 在命令行里执行如下命令,检查端口是否转发成功。
180   ```shell
181   hdc fport ls
182   ```
183   * 如果有返回端口转发的任务,则说明端口转发成功。
184   ![hdc_fport_ls_38532](figures/devtools_resources_hdc_fport_ls_38532.png)
185   * 如果返回 `[Empty]`, 则说明端口转发失败。
186   ![hdc_fport_ls_empty](figures/devtools_resources_hdc_fport_ls_empty.jpg)
187
188### 便捷脚本
189#### Windows平台
190请复制以下信息建立bat文件,开启调试应用后执行。
191   ```
192   @echo off
193   setlocal enabledelayedexpansion
194
195   :: Initialize port number and PID list
196   set PORT=9222
197   set PID_LIST=
198
199   :: Get the list of all forwarded ports and PIDs
200   for /f "tokens=2,5 delims=:_" %%a in ('hdc fport ls') do (
201       if %%a gtr !PORT! (
202           set PORT=%%a
203       )
204       for /f "tokens=1 delims= " %%c in ("%%b") do (
205           set PID_LIST=!PID_LIST! %%c
206       )
207   )
208
209   :: Increment port number for next application
210   set temp_PORT=!PORT!
211   set /a temp_PORT+=1
212   set PORT=!temp_PORT!
213
214   :: Get the domain socket name of devtools
215   for /f "tokens=*" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do (
216       set SOCKET_NAME=%%a
217
218       :: Extract process ID
219       for /f "delims=_ tokens=4" %%b in ("!SOCKET_NAME!") do set PID=%%b
220
221       :: Check if PID already has a mapping
222       echo !PID_LIST! | findstr /C:" !PID! " >nul
223       if errorlevel 1 (
224           :: Add mapping
225           hdc fport tcp:!PORT! localabstract:webview_devtools_remote_!PID!
226           if errorlevel 1 (
227               echo Error: Failed to add mapping.
228               pause
229               exit /b
230           )
231
232           :: Add PID to list and increment port number for next application
233           set PID_LIST=!PID_LIST! !PID!
234           set temp_PORT=!PORT!
235           set /a temp_PORT+=1
236           set PORT=!temp_PORT!
237       )
238   )
239
240   :: If no process ID was found, prompt the user to open debugging in their application code and provide the documentation link
241   if "!SOCKET_NAME!"=="" (
242       echo No process ID was found. Please open debugging in your application code using the corresponding interface. You can find the relevant documentation at this link: [https://gitcode.com/openharmony/docs/blob/master/zh-cn/application-dev/web/web-debugging-with-devtools.md]
243       pause
244       exit /b
245   )
246
247   :: Check mapping
248   hdc fport ls
249
250   echo.
251   echo Script executed successfully. Press any key to exit...
252   pause >nul
253
254   :: Try to open the page in Edge
255   start msedge chrome://inspect/#devices
256
257   :: If Edge is not available, then open the page in Chrome
258   if errorlevel 1 (
259       start chrome chrome://inspect/#devices
260   )
261
262   endlocal
263   ```
264#### Linux或Mac平台
265请复制以下信息建立sh文件,注意chmod以及格式转换,开启调试应用后执行。
266本脚本会先删除所有的端口转发,如果有其他的工具(如:DevEco Studio)也在使用端口转发功能,会受到影响。
267   ```
268   #!/bin/bash
269
270   # Get current fport rule list
271   CURRENT_FPORT_LIST=$(hdc fport ls)
272
273   # Delete the existing fport rule one by one
274   while IFS= read -r line; do
275       # Extract the taskline
276       IFS=' ' read -ra parts <<< "$line"
277       taskline="${parts[1]} ${parts[2]}"
278
279       # Delete the corresponding fport rule
280       echo "Removing forward rule for $taskline"
281       hdc fport rm $taskline
282       result=$?
283
284       if [ $result -eq 0 ]; then
285           echo "Remove forward rule success, taskline:$taskline"
286       else
287           echo "Failed to remove forward rule, taskline:$taskline"
288       fi
289
290   done <<< "$CURRENT_FPORT_LIST"
291
292   # Initial port number
293   INITIAL_PORT=9222
294
295   # Get the current port number, use initial port number if not set previously
296   CURRENT_PORT=${PORT:-$INITIAL_PORT}
297
298   # Get the list of all PIDs that match the condition
299   PID_LIST=$(hdc shell cat /proc/net/unix | grep webview_devtools_remote_ | awk -F '_' '{print $NF}')
300
301   if [ -z "$PID_LIST" ]; then
302       echo "Failed to retrieve PID from the device"
303       exit 1
304   fi
305
306   # Increment the port number
307   PORT=$CURRENT_PORT
308
309   # Forward ports for each application one by one
310   for PID in $PID_LIST; do
311       # Increment the port number
312       PORT=$((PORT + 1))
313
314       # Execute the hdc fport command
315       hdc fport tcp:$PORT localabstract:webview_devtools_remote_$PID
316
317       # Check if the command executed successfully
318       if [ $? -ne 0 ]; then
319           echo "Failed to execute hdc fport command"
320           exit 1
321       fi
322   done
323
324   # List all forwarded ports
325   hdc fport ls
326   ```
327
328### 在Chrome浏览器上打开调试工具页面
329  1. 在电脑端Chrome浏览器地址栏中输入调试工具地址 chrome://inspect/\#devices 并打开该页面。
330  2. 修改Chrome调试工具的配置。
331     需要从本地的TCP 9222端口发现被调试网页,所以请确保已勾选 "Discover network targets"。然后再进行网络配置。
332     (1) 点击 "Configure" 按钮。
333     (2) 在 "Target discovery settings" 中添加要监听的本地端口localhost:9222。
334
335     ![chrome_configure](figures/devtools_resources_chrome_configure.jpg)
336
337  3. 为了同时调试多个应用,请在Chrome浏览器的调试工具网页内,于“Devices”选项中的“configure”部分添加多个端口号。
338
339     ![debug-effect](figures/debug-domains.png)
340
341### 等待发现被调试页面
342
343  如果前面的步骤执行成功,Chrome的调试页面将显示待调试的网页。
344  ![chrome_inspect](figures/devtools_resources_chrome_inspect.jpg)
345
346### 开始网页调试
347
348  ![debug-effect](figures/debug-effect.png)
349
350## 常见问题与解决方法
351
352### 可以调试系统浏览器打开的网页吗?
353
354能否调试系统浏览器打开的网页,取决于系统浏览器是否开启Web调试开关。
355* 当前系统浏览器已启用Web调试开关,可继续执行[USB连接调试](#usb连接调试)中的后续步骤。
356
357### hdc无法发现设备
358**问题现象**
359
360   在命令行里执行如下命令后,没有列出设备ID。
361   ```shell
362   hdc list targets
363   ```
364
365**解决方法**
366
367  * 请确保设备上的USB调试开关已开启。
368  * 请确保设备与电脑相连。
369
370### hdc的命令显示设备"未授权"或"unauthorized"
371**问题现象**
372
373   执行hdc命令时,提示设备"未授权"或"unauthorized"。
374
375**问题原因**
376
377   设备没有授权该台电脑进行调试。
378
379**解决方法**
380
381  开启USB调试开关的设备连接没有授权的电脑后,会弹框提示"是否允许USB调试?",请选择允许。
382
383### 找不到DevTools的domain socket
384**问题现象**
385
386   在hdc shell里执行如下命令后,没有结果。
387   ```shell
388   cat /proc/net/unix | grep devtools
389   ```
390
391**解决方法**
392
393  * 请确保应用[开启了Web调试开关](#应用代码开启web调试开关)。
394  * 请确保应用使用Web组件加载了网页。
395
396### 端口转发不成功
397**问题现象**
398
399   在命令行里执行如下命令后,没有列出之前设置过转发任务。
400   ```shell
401   hdc fport ls
402   ```
403
404**解决方法**
405
406  * 请确保设备里的domain socket存在。
407  * 请确保电脑端的tcp:9222没有被占用。
408    如果tcp:9222被占用,可以将domain socket转发到其他未被占用的TCP端口, 比如9223等。
409    如果转发到了新的TCP端口, 需要同步修改电脑端Chrome浏览器"Target discovery settings"中的端口号。
410
411### 端口转发成功后,电脑端Chrome无法发现被调试网页
412**问题现象**
413
414  电脑端Chrome浏览器无法发现被调试网页。
415
416**问题原因**
417
418端口转发失效可能是以下原因:
419  * 设备与电脑断连,会导致hdc里的所有转发任务被清空。
420  * hdc服务重启,也会导致hdc里的所有转发任务被清空。
421  * 设备里应用的进程号发生了变更(应用重新启动等),会导致hdc里旧的转发任务失效。
422  * 多个转发任务转发到了同一个端口等异常配置,会导致转发异常。
423
424**解决方法**
425
426  * 请确保电脑端的本地tcp:9222(其他TCP端口同理)没有被占用。
427  * 请确保设备端的domain socket还存在。
428  * 请确保domain socket名称里的进程号与被调试的应用的进程号相同。
429  * 请删除hdc里其他不必要的转发任务。
430  * 转发成功后,请用电脑端的Chrome浏览器打开网址 http://localhost:9222/json ,URL里的9222需要改为自己实际配置的TCP端口。
431
432    - 如果网页有内容, 说明端口转发成功,请在Chrome的调试页面[等待被调试页面的出现](#等待发现被调试页面)。
433    ![chrome_localhost](figures/devtools_resources_chrome_localhost.jpg)
434
435    - 如果展示的是错误网页, 说明端口转发失败, 请参阅[端口转发不成功](#端口转发不成功)中的解决方法。
436    ![chrome_localhost_refused](figures/devtools_resources_chrome_localhost_refused.jpg)
437
438  * 电脑端Chrome浏览器打开 http://localhost:9222/json 页面有内容,但是Chrome的调试工具界面还是无法发现调试目标。
439    - 请确保Chrome调试工具界面的 "Configure" 中配置的端口号,与端口转发指定的TCP端口号一致。
440    - 在本文档中,默认使用的TCP端口号为9222。
441      如果开发者使用了其他的TCP端口号(比如9223),请同时修改[端口转发](#端口转发)中的TCP端口号和[Chrome调试工具界面"Configure"配置](#在chrome浏览器上打开调试工具页面)中的端口号。
442
443### 开启了无线调试模式后,电脑端Chrome无法发现被调试网页
444**问题现象**
445
446  ArkWeb开启了无线调试模式后,电脑端Chrome浏览器无法发现被调试网页。
447
448**问题原因**
449
450* 无线调试模式没有成功开启。
451* 调试工具和被调试设备之间网络不通。
452
453**解决方法**
454
455* 请确保使用的端口可以被应用使用。
456* 请确保调试工具和被调试设备在同一个局域网内,且它们之间网络通畅。
457
458### Web组件无法使用DevTools工具进行调试
459**问题现象**
460
461  电脑端Chrome浏览器无法发现被调试网页。
462
463**问题原因**
464
465* 当同时使用HDC和ADB时,ADB会干扰DevTools与设备之间的WebSocket连接
466
467**解决方法**
468* 如果同时使用HDC和ADB,先关闭ADB进程,确保DevTools与设备建立WebSocket连接