• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Debugging Frontend Pages by Using DevTools
2
3
4The **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-arkweb/js-apis-webview.md#setwebdebuggingaccess) to enable frontend page debugging for the **Web** component and make sure the test device connected to the PC runs 4.1.0 or a later version.
5
6
7## Procedure
8
9### Enabling Web Debugging for Application Code
10
11Before debugging a web page, call the [setWebDebuggingAccess()](../reference/apis-arkweb/js-apis-webview.md#setwebdebuggingaccess) API to enable the web debugging function.
12If the web debugging function is not enabled, DevTools cannot detect the web page to be debugged.
13
141. Enable web frontend page debugging in the application code.
15
16   ```ts
17   // xxx.ets
18   import { webview } from '@kit.ArkWeb';
19
20   @Entry
21   @Component
22   struct WebComponent {
23     controller: webview.WebviewController = new webview.WebviewController();
24
25     aboutToAppear() {
26       // Enable web frontend page debugging.
27       webview.WebviewController.setWebDebuggingAccess(true);
28     }
29
30     build() {
31       Column() {
32         Web({ src: 'www.example.com', controller: this.controller })
33       }
34     }
35   }
36   ```
372. Declare the required permission in the **module.json5** file of the HAP module in the application project in DevEco Studio. For details, see [Declaring Permissions in the Configuration File](../security/AccessToken/declare-permissions.md).
38
39   ```
40   "requestPermissions":[
41      {
42        "name" : "ohos.permission.INTERNET"
43      }
44    ]
45   ```
46
47### Connecting the Device to a PC
48
49Connect the device to a PC and enable Developer mode for subsequent port forwarding operations.
50
511. Enable Developer mode and USB debugging on your device.
52
53   (1) Choose **Settings** > **System** and check whether **Developer options** is available. If not, go to **Settings** > **About** and touch the version number for seven consecutive times until the message "Enable developer mode?" is displayed. Touch **OK** and enter the PIN (if set). Then the device will automatically restart.
54
55   (2) Connect the device to the PC using a USB cable. Choose **Settings** > **System** > **Developer options** and enable USB debugging. In the displayed dialog box, touch **Allow**.
56
572. Run the hdc command to connect to the device.
58   Run the following command in the CLI to check whether hdc can discover the device.
59   ```shell
60   hdc list targets
61   ```
62   - If a device ID is returned, the device is connected.
63   ![hdc_list_targets_success](figures/devtools_resources_hdc_list_targets_success.png)
64   - If **[Empty]** is returned, the device is not found.
65   ![hdc_list_targets_empty](figures/devtools_resources_hdc_list_targets_empty.jpg)
66
673. Enter the hdc shell.
68   After hdc is connected to the device, run the following command to enter hdc shell.
69   ```shell
70   hdc shell
71   ```
72
73### Port Forwarding
74After the application code calls the **setWebDebuggingAccess** API to enable web debugging, the ArkWeb kernel starts a domain socket listener to enable DevTools to debug web pages.
75However, Chrome cannot directly access the domain socket on the device. Therefore, the domain socket on the device needs to be forwarded to the PC.
76
771. Run the following command in hdc shell to obtain the domain socket created by ArkWeb on the device.
78   ```shell
79   cat /proc/net/unix | grep devtools
80   ```
81   * If the preceding operations are correct, the domain socket port is displayed.
82   ![hdc_grep_devtools_38532](figures/devtools_resources_hdc_grep_devtools_38532.jpg)
83
84   * If it is not displayed, check the following items again.
85     (1) The web debugging function is enabled for the application.
86     (2) The application uses the **Web** component to load the web page.
87
882. Exit hdc shell, and run the following command to forward the obtained domain socket to TCP port 9222 of the PC.
89   Run the **exit** command to exit the hdc shell.
90   ```shell
91   exit
92   ```
93   Run the following command to forward the port:
94   ```shell
95   hdc fport tcp:9222 localabstract:webview_devtools_remote_38532
96   ```
97   > **NOTE**
98   >
99   > The number following **webview_devtools_remote_** indicates the process ID of the application where the **Web** component is located. The number is not fixed. Change the number to the obtained value.
100   > If the process ID of the application changes (for example, the application is restarted), forward the port again.
101
102   The following figure shows a successful forwarding.
103   ![hdc_fport_38532_success](figures/devtools_resources_hdc_fport_38532_success.jpg)
104
1053. Run the following command to check whether the port is successfully forwarded.
106   ```shell
107   hdc fport ls
108   ```
109   * If a port forwarding task is returned, the operation is successful.
110   ![hdc_fport_ls_38532](figures/devtools_resources_hdc_fport_ls_38532.png)
111   * If **[Empty]** is returned, the operation fails.
112   ![hdc_fport_ls_empty](figures/devtools_resources_hdc_fport_ls_empty.jpg)
113
114### Opening the Debugging Tool Page in Chrome
115  1. Input **chrome://inspect/\#devices** in the address box of Chrome on the PC and open the page.
116  2. Configure the Chrome debugging tool.
117     The web page to be debugged needs to be discovered from the local TCP port 9222. Therefore, ensure that **Discover network targets** is selected. Then, configure the network.
118     (1) Click the **Configure** button.
119     (2) Add **localhost:9222** to **Target discovery settings**.
120
121     ![chrome_configure](figures/devtools_resources_chrome_configure.jpg)
122
123  3. To debug multiple applications at the same time, add multiple port numbers in **Configure** of the **Devices** option on the Chrome debugging tool page.
124
125     ![debug-effect](figures/debug-domains.png)
126
127### Waiting for the Page to Be Debugged
128
129  If the preceding steps are successful, the page to be debugged is displayed on the Chrome debugging page.
130  ![chrome_inspect](figures/devtools_resources_chrome_inspect.jpg)
131
132### Starting Web Page Debugging
133
134  ![debug-effect](figures/debug-effect.png)
135
136## Script
137### On Windows
138Copy the following information to create a .bat file, enable application debugging, and run the file.
139   ```
140   @echo off
141   setlocal enabledelayedexpansion
142
143   :: Initialize port number and PID list
144   set PORT=9222
145   set PID_LIST=
146
147   :: Get the list of all forwarded ports and PIDs
148   for /f "tokens=2,5 delims=:_" %%a in ('hdc fport ls') do (
149       if %%a gtr !PORT! (
150           set PORT=%%a
151       )
152       for /f "tokens=1 delims= " %%c in ("%%b") do (
153           set PID_LIST=!PID_LIST! %%c
154       )
155   )
156
157   :: Increment port number for next application
158   set temp_PORT=!PORT!
159   set /a temp_PORT+=1
160   set PORT=!temp_PORT!
161
162   :: Get the domain socket name of devtools
163   for /f "tokens=*" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do (
164       set SOCKET_NAME=%%a
165
166       :: Extract process ID
167       for /f "delims=_ tokens=4" %%b in ("!SOCKET_NAME!") do set PID=%%b
168
169       :: Check if PID already has a mapping
170       echo !PID_LIST! | findstr /C:" !PID! " >nul
171       if errorlevel 1 (
172           :: Add mapping
173           hdc fport tcp:!PORT! localabstract:webview_devtools_remote_!PID!
174           if errorlevel 1 (
175               echo Error: Failed to add mapping.
176               pause
177               exit /b
178           )
179
180           :: Add PID to list and increment port number for next application
181           set PID_LIST=!PID_LIST! !PID!
182           set temp_PORT=!PORT!
183           set /a temp_PORT+=1
184           set PORT=!temp_PORT!
185       )
186   )
187
188   :: If no process ID was found, prompt the user to open debugging in their application code and provide the documentation link
189   if "!SOCKET_NAME!"=="" (
190       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://gitee.com/openharmony/docs/blob/master/zh-cn/application-dev/web/web-debugging-with-devtools.md]
191       pause
192       exit /b
193   )
194
195   :: Check mapping
196   hdc fport ls
197
198   echo.
199   echo Script executed successfully. Press any key to exit...
200   pause >nul
201
202   :: Try to open the page in Edge
203   start msedge chrome://inspect/#devices.com
204
205   :: If Edge is not available, then open the page in Chrome
206   if errorlevel 1 (
207       start chrome chrome://inspect/#devices.com
208   )
209
210   endlocal
211   ```
212### On Linux or macOS
213Copy the following information to create an .sh file. Note that you need to run the **chmod** command and convert the file format. Enable the application debugging and run the file.
214This script will delete all port forwarding. If other tools (such as DevEco Studio) are using port forwarding, they will be affected.
215   ```
216   #!/bin/bash
217
218   # Get current fport rule list
219   CURRENT_FPORT_LIST=$(hdc fport ls)
220
221   # Delete the existing fport rule one by one
222   while IFS= read -r line; do
223       # Extract the taskline
224       IFS=' ' read -ra parts <<< "$line"
225       taskline="${parts[1]} ${parts[2]}"
226
227       # Delete the corresponding fport rule
228       echo "Removing forward rule for $taskline"
229       hdc fport rm $taskline
230       result=$?
231
232       if [ $result -eq 0 ]; then
233           echo "Remove forward rule success, taskline:$taskline"
234       else
235           echo "Failed to remove forward rule, taskline:$taskline"
236       fi
237
238   done <<< "$CURRENT_FPORT_LIST"
239
240   # Initial port number
241   INITIAL_PORT=9222
242
243   # Get the current port number, use initial port number if not set previously
244   CURRENT_PORT=${PORT:-$INITIAL_PORT}
245
246   # Get the list of all PIDs that match the condition
247   PID_LIST=$(hdc shell cat /proc/net/unix | grep webview_devtools_remote_ | awk -F '_' '{print $NF}')
248
249   if [ -z "$PID_LIST" ]; then
250       echo "Failed to retrieve PID from the device"
251       exit 1
252   fi
253
254   # Increment the port number
255   PORT=$CURRENT_PORT
256
257   # Forward ports for each application one by one
258   for PID in $PID_LIST; do
259       # Increment the port number
260       PORT=$((PORT + 1))
261
262       # Execute the hdc fport command
263       hdc fport tcp:$PORT localabstract:webview_devtools_remote_$PID
264
265       # Check if the command executed successfully
266       if [ $? -ne 0 ]; then
267           echo "Failed to execute hdc fport command"
268           exit 1
269       fi
270   done
271
272   # List all forwarded ports
273   hdc fport ls
274   ```
275
276## FAQs
277
278### What should I do if hdc cannot discover devices?
279**Symptom**
280
281   The device ID is not displayed after the following command is executed.
282   ```shell
283   hdc list targets
284   ```
285
286**Solution**
287
288  * Ensure that USB debugging is enabled on the device.
289  * Ensure that the device is connected to the PC.
290
291### What should I do if "unauthorized" is displayed in the hdc command output?
292**Symptom**
293
294   When the hdc command is executed, the system displays a message indicating that the device is "unauthorized".
295
296**Possible Causes**
297
298   The PC is not authorized to debug the device.
299
300**Solution**
301
302  When a device with USB debugging enabled is connected to an unauthorized PC, a dialog box is displayed, asking you whether to allow USB debugging. In this case, select **Allow**.
303
304### What should I do if the domain socket of DevTools cannot be found?
305**Symptom**
306
307   No result is displayed after the following command is executed in hdc shell.
308   ```shell
309   cat /proc/net/unix | grep devtools
310   ```
311
312**Solution**
313
314  * Ensure that the step of [Enabling Web Debugging for Application Code](#enabling-web-debugging-for-application-code) is performed.
315  * Ensure that the application uses the **Web** component to load the web page.
316
317### What should I do if port forwarding fails
318**Symptom**
319
320   The configured forwarding task is not displayed after the following command is executed.
321   ```shell
322   hdc fport ls
323   ```
324
325**Solution**
326
327  * Ensure that the domain socket exists on the device.
328  * Ensure that **tcp:9222** on the PC is not occupied.
329    If **tcp:9222** is occupied, forward the domain socket to another TCP port that is not occupied, for example, **tcp:9223**.
330    If the domain socket is forwarded to a new TCP port, you need to change the port number in **Target discovery settings** of Chrome on the PC.
331
332### What should I do if the web page to be debugged cannot be found in Chrome on the PC after port forwarding is successful?
333**Symptom**
334
335  The web page to be debugged cannot be found in Chrome on the PC.
336
337**Possible Causes**
338
339The port forwarding may be invalid due to the following reasons:
340  * The device is disconnected from the PC. As a result, all forwarding tasks in hdc are cleared.
341  * The hdc service is restarted. As a result, all forwarding tasks in hdc are cleared.
342  * The process ID of the application on the device is changed (for example, the application is restarted). As a result, the previous forwarding tasks in hdc become invalid.
343  * Exceptions occur when multiple forwarding tasks are forwarded to the same port.
344
345**Solution**
346
347  * Ensure that the local **tcp:9222** (or other configured port) on the PC is not occupied.
348  * Ensure that the domain socket exists on the device.
349  * Ensure that the process ID in the domain socket name is the same as that of the application to be debugged.
350  * Delete unnecessary forwarding tasks from hdc.
351  * After the domain socket is successfully forwarded, open **http://localhost:9222/json** using the Chrome on the PC. Change **9222** in the URL to the actual TCP port number.
352
353    - If the web page is normally displayed, the port forwarding is successful. On the Chrome debugging page, perform the operation of [Waiting for the Page to Be Debugged](#waiting-for-the-page-to-be-debugged).
354    ![chrome_localhost](figures/devtools_resources_chrome_localhost.jpg)
355
356    - If an error page is displayed, port forwarding fails. For details about the solution, see [What should I do if port forwarding fails](#what-should-i-do-if-port-forwarding-fails).
357    ![chrome_localhost_refused](figures/devtools_resources_chrome_localhost_refused.jpg)
358
359  * If the **http://localhost:9222/json** page is normally displayed on Chrome, but the debugging target cannot be found on the Chrome debugging page, perform the following operations:
360    - Ensure that the port number in **Configure** on the Chrome debugging page is the same as the TCP port number specified for port forwarding.
361    - In this topic, the default TCP port number is **9222**.
362      If you use another TCP port number (for example, **9223**), change the TCP port number in [Port Forwarding](#port-forwarding) and [Opening the Debugging Tool Page in Chrome](#opening-the-debugging-tool-page-in-chrome).
363
364<!--no_check-->