• 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.
12
13If the web debugging function is not enabled, DevTools cannot detect the web page to be debugged.
14
151. Enable web frontend page debugging in the application code.
16
17   ```ts
18   // xxx.ets
19   import { webview } from '@kit.ArkWeb';
20
21   @Entry
22   @Component
23   struct WebComponent {
24     controller: webview.WebviewController = new webview.WebviewController();
25
26     aboutToAppear() {
27       // Enable web frontend page debugging.
28       webview.WebviewController.setWebDebuggingAccess(true);
29     }
30
31     build() {
32       Column() {
33         Web({ src: 'www.example.com', controller: this.controller })
34       }
35     }
36   }
37   ```
382. 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).
39
40   ```
41   "requestPermissions":[
42      {
43        "name" : "ohos.permission.INTERNET"
44      }
45    ]
46   ```
47
48### Connecting the Device to a PC
49
50Connect the device to a PC and enable Developer mode for subsequent port forwarding operations.
51
521. Enable Developer mode and USB debugging on your device.
53
54   (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.
55
56   (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**.
57
582. Run the hdc command to connect to the device.
59
60   Run the following command in the CLI to check whether hdc can discover the device.
61
62   ```shell
63   hdc list targets
64   ```
65
66   - If a device ID is returned, the device is connected.
67
68   ![hdc_list_targets_success](figures/devtools_resources_hdc_list_targets_success.png)
69   - If **[Empty]** is returned, the device is not found.
70
71   ![hdc_list_targets_empty](figures/devtools_resources_hdc_list_targets_empty.jpg)
72
733. Enter the hdc shell.
74
75   After hdc is connected to the device, run the following command to enter hdc shell.
76
77   ```shell
78   hdc shell
79   ```
80
81### Port Forwarding
82After 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.
83However, Chrome cannot directly access the domain socket on the device. Therefore, the domain socket on the device needs to be forwarded to the PC.
84
851. Run the following command in hdc shell to obtain the domain socket created by ArkWeb on the device.
86   ```shell
87   cat /proc/net/unix | grep devtools
88   ```
89   * If the preceding operations are correct, the domain socket port is displayed.
90
91   ![hdc_grep_devtools_38532](figures/devtools_resources_hdc_grep_devtools_38532.jpg)
92
93   * If it is not displayed, check the following items again.
94     (1) The web debugging function is enabled for the application.
95     (2) The application uses the **Web** component to load the web page.
96
972. Exit hdc shell, and run the following command to forward the obtained domain socket to TCP port 9222 of the PC.
98
99   Run the **exit** command to exit the hdc shell.
100
101   ```shell
102   exit
103   ```
104   Run the following command to forward the port:
105   ```shell
106   hdc fport tcp:9222 localabstract:webview_devtools_remote_38532
107   ```
108   > **NOTE**
109   >
110   > 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.
111   >
112   > If the process ID of the application changes (for example, the application is restarted), forward the port again.
113
114   The following figure shows a successful forwarding.
115
116   ![hdc_fport_38532_success](figures/devtools_resources_hdc_fport_38532_success.jpg)
117
1183. Run the following command to check whether the port is successfully forwarded.
119   ```shell
120   hdc fport ls
121   ```
122   * If a port forwarding task is returned, the operation is successful.
123
124   ![hdc_fport_ls_38532](figures/devtools_resources_hdc_fport_ls_38532.png)
125   * If **[Empty]** is returned, the operation fails.
126
127   ![hdc_fport_ls_empty](figures/devtools_resources_hdc_fport_ls_empty.jpg)
128
129### Opening the Debugging Tool Page in Chrome
130  1. Input **chrome://inspect/\#devices** in the address box of Chrome on the PC and open the page.
131
132  2. Configure the Chrome debugging tool.
133
134     The web page to be debugged needs to be discovered from the local TCP port 9222. Therefore, ensure that **Discovery network targets** is selected. Then, configure the network.
135
136     (1) Click the **Configure** button.
137
138     (2) Add **localhost:9222** to **Target discovery settings**.
139
140     ![chrome_configure](figures/devtools_resources_chrome_configure.jpg)
141
142  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.
143
144     ![debug-effect](figures/debug-domains.png)
145
146### Waiting for the Page to Be Debugged
147
148If the preceding steps are successful, the page to be debugged is displayed on the Chrome debugging page.
149
150![chrome_inspect](figures/devtools_resources_chrome_inspect.jpg)
151
152### Starting Web Page Debugging
153
154  ![debug-effect](figures/debug-effect.png)
155
156## Script
157### On Windows
158Copy the following information to create a .bat file, enable application debugging, and run the file.
159   ```
160   @echo off
161   setlocal enabledelayedexpansion
162
163   :: Initialize port number and PID list
164   set PORT=9222
165   set PID_LIST=
166
167   :: Get the list of all forwarded ports and PIDs
168   for /f "tokens=2,5 delims=:_" %%a in ('hdc fport ls') do (
169       if %%a gtr !PORT! (
170           set PORT=%%a
171       )
172       for /f "tokens=1 delims= " %%c in ("%%b") do (
173           set PID_LIST=!PID_LIST! %%c
174       )
175   )
176
177   :: Increment port number for next application
178   set temp_PORT=!PORT!
179   set /a temp_PORT+=1
180   set PORT=!temp_PORT!
181
182   :: Get the domain socket name of devtools
183   for /f "tokens=*" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do (
184       set SOCKET_NAME=%%a
185
186       :: Extract process ID
187       for /f "delims=_ tokens=4" %%b in ("!SOCKET_NAME!") do set PID=%%b
188
189       :: Check if PID already has a mapping
190       echo !PID_LIST! | findstr /C:" !PID! " >nul
191       if errorlevel 1 (
192           :: Add mapping
193           hdc fport tcp:!PORT! localabstract:webview_devtools_remote_!PID!
194           if errorlevel 1 (
195               echo Error: Failed to add mapping.
196               pause
197               exit /b
198           )
199
200           :: Add PID to list and increment port number for next application
201           set PID_LIST=!PID_LIST! !PID!
202           set temp_PORT=!PORT!
203           set /a temp_PORT+=1
204           set PORT=!temp_PORT!
205       )
206   )
207
208   :: If no process ID was found, prompt the user to open debugging in their application code and provide the documentation link
209   if "!SOCKET_NAME!"=="" (
210       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]
211       pause
212       exit /b
213   )
214
215   :: Check mapping
216   hdc fport ls
217
218   echo.
219   echo Script executed successfully. Press any key to exit...
220   pause >nul
221
222   :: Try to open the page in Edge
223   start msedge chrome://inspect/#devices.com
224
225   :: If Edge is not available, then open the page in Chrome
226   if errorlevel 1 (
227       start chrome chrome://inspect/#devices.com
228   )
229
230   endlocal
231   ```
232### On Linux or macOS
233Copy 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.
234   ```
235   #!/bin/bash
236
237   # Get current fport rule list
238   CURRENT_FPORT_LIST=$(hdc fport ls)
239
240   # Delete the existing fport rule one by one
241   while IFS= read -r line; do
242       # Extract the taskline
243       IFS=' ' read -ra parts <<< "$line"
244       taskline="${parts[1]} ${parts[2]}"
245
246       # Delete the corresponding fport rule
247       echo "Removing forward rule for $taskline"
248       hdc fport rm $taskline
249       result=$?
250
251       if [ $result -eq 0 ]; then
252           echo "Remove forward rule success, taskline:$taskline"
253       else
254           echo "Failed to remove forward rule, taskline:$taskline"
255       fi
256
257   done <<< "$CURRENT_FPORT_LIST"
258
259   # Initial port number
260   INITIAL_PORT=9222
261
262   # Get the current port number, use initial port number if not set previously
263   CURRENT_PORT=${PORT:-$INITIAL_PORT}
264
265   # Get the list of all PIDs that match the condition
266   PID_LIST=$(hdc shell cat /proc/net/unix | grep webview_devtools_remote_ | awk -F '_' '{print $NF}')
267
268   if [ -z "$PID_LIST" ]; then
269       echo "Failed to retrieve PID from the device"
270       exit 1
271   fi
272
273   # Increment the port number
274   PORT=$CURRENT_PORT
275
276   # Forward ports for each application one by one
277   for PID in $PID_LIST; do
278       # Increment the port number
279       PORT=$((PORT + 1))
280
281       # Execute the hdc fport command
282       hdc fport tcp:$PORT localabstract:webview_devtools_remote_$PID
283
284       # Check if the command executed successfully
285       if [ $? -ne 0 ]; then
286           echo "Failed to execute hdc fport command"
287           exit 1
288       fi
289   done
290
291   # List all forwarded ports
292   hdc fport ls
293   ```
294
295## FAQs
296
297### What should I do if hdc cannot discover devices?
298**Symptom**
299
300The device ID is not displayed after the following command is executed.
301   ```shell
302   hdc list targets
303   ```
304
305**Solution**
306
307  * Ensure that USB debugging is enabled on the device.
308  * Ensure that the device is connected to the PC.
309
310### What should I do if "unauthorized" is displayed in the hdc command output?
311**Symptom**
312
313When the hdc command is executed, the system displays a message indicating that the device is "unauthorized".
314
315**Possible Causes**
316
317The PC is not authorized to debug the device.
318
319**Solution**
320
321When 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**.
322
323### What should I do if the domain socket of DevTools cannot be found?
324**Symptom**
325
326No result is displayed after the following command is executed in hdc shell.
327   ```shell
328   cat /proc/net/unix | grep devtools
329   ```
330
331**Solution**
332
333  * Ensure that the step of [Enabling Web Debugging for Application Code](#enabling-web-debugging-for-application-code) is performed.
334  * Ensure that the application uses the **Web** component to load the web page.
335
336### What should I do if port forwarding fails
337**Symptom**
338
339The configured forwarding task is not displayed after the following command is executed.
340   ```shell
341   hdc fport ls
342   ```
343
344**Solution**
345
346  * Ensure that the domain socket exists on the device.
347
348  * Ensure that **tcp:9222** on the PC is not occupied.
349
350    If **tcp:9222** is occupied, forward the domain socket to another TCP port that is not occupied, for example, **tcp:9223**.
351
352    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.
353
354### What should I do if the web page to be debugged cannot be found in Chrome on the PC after port forwarding is successful?
355**Symptom**
356
357The web page to be debugged cannot be found in Chrome on the PC.
358
359**Possible Causes**
360
361The port forwarding may be invalid due to the following reasons:
362  * The device is disconnected from the PC. As a result, all forwarding tasks in hdc are cleared.
363  * The hdc service is restarted. As a result, all forwarding tasks in hdc are cleared.
364  * 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.
365  * Exceptions occur when multiple forwarding tasks are forwarded to the same port.
366
367**Solution**
368
369  * Ensure that the local **tcp:9222** (or other configured port) on the PC is not occupied.
370  * Ensure that the domain socket exists on the device.
371  * Ensure that the process ID in the domain socket name is the same as that of the application to be debugged.
372  * Delete unnecessary forwarding tasks from hdc.
373  * 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.
374
375    - 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).
376
377    ![chrome_localhost](figures/devtools_resources_chrome_localhost.jpg)
378- 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).
379
380    ![chrome_localhost_refused](figures/devtools_resources_chrome_localhost_refused.jpg)
381
382  * 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:
383    - Ensure that the port number in **Configure** on the Chrome debugging page is the same as the TCP port number specified for port forwarding.
384
385    - In this topic, the default TCP port number is **9222**.
386
387      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).
388
389 <!--no_check-->