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/arkts-apis-webview-WebviewController.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/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess) API to enable the web debugging feature. 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  64 - If **[Empty]** is returned, the device is not found. 65  66 673. Enter the hdc shell. 68 After the device is connected, 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. For details, see [Automatically Mapping the WebView Debugging Link](https://developer.huawei.com/consumer/en/doc/harmonyos-guides/ide-run-debug-configurations#section2773943154118). 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  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 following **webview_devtools_remote_** to the obtained value. 100 > If the process ID of the application changes (for example, the application is restarted), configure port forwarding again. 101 102 The following figure shows a successful forwarding. 103  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  111 * If **[Empty]** is returned, the operation fails. 112  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  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  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  131 132### Starting Web Page Debugging 133 134  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/en/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## Wireless Debugging 277In [debugging procedure](#procedure), domain sockets need to be frequently queried and ports need to be forwarded in [port forwarding](#port forwarding), which is inconvenient for page debugging. Therefore, since API version 20, the wireless debugging API [setWebDebuggingAccess<sup>20+</sup>](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess20) can be used to simplify the debugging process. 278 2791. Enable web debugging for application code. 280 281 In the application, call the [setWebDebuggingAccess<sup>20+</sup>](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess20) API to set the TCP Socket port number and enable web debugging. 282 ```ts 283 // xxx.ets 284 import { webview } from '@kit.ArkWeb'; 285 import { BusinessError } from '@kit.BasicServicesKit'; 286 287 @Entry 288 @Component 289 struct WebComponent { 290 controller: webview.WebviewController = new webview.WebviewController(); 291 292 aboutToAppear(): void { 293 try { 294 // Enable wireless web debugging and specify the TCP socket port. 295 webview.WebviewController.setWebDebuggingAccess(true, 8888); 296 } catch (error) { 297 console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`); 298 } 299 } 300 301 build() { 302 Column() { 303 Web({ src: 'www.example.com', controller: this.controller }) 304 } 305 } 306 } 307 ``` 308 > **NOTE** 309 > 310 > Port 8888 used in the sample code is for reference only. You must ensure that the port number can be used by applications in practice. If the port cannot be used because the port is occupied or the application does not have the permission to use the port, the API throws an exception or the ArkWeb cannot enable the debugging mode. 311 3122. Connect the device to a PC. 313 314 If wireless debugging is successfully enabled, skip this step. 315 3163. Forward the port. 317 318 If wireless debugging is successfully enabled, skip this step. 319 3204. Open the debugging tool page in Chrome. 321 322 In step 2 "Configure the Chrome debugging tool" of [Opening the Debugging Tool Page in Chrome](#opening-the-debugging-tool-page-in-chrome), change (2) to the following: 323 In **Target discovery settings**, add the IP address of the device to be debugged and the port specified in the [setWebDebuggingAccess<sup>20+</sup>](../reference/apis-arkweb/arkts-apis-webview-WebviewController.md#setwebdebuggingaccess20) API, for example, **192.168.0.3:8888**. 324 325 > **NOTE** 326 > 327 > The debugging tool and the device to be debugged must be in the same LAN and can access each other. If the device to be debugged has multiple IP addresses, use the IP address that is in the same network segment as the IP address of the debugging tool. 328 3295. Wait for the page to be debugged. 330 331 This step does not change. 332 3336. Start web page debugging. 334 335 This step does not change. 336 337## FAQs 338 339### What should I do if hdc cannot discover devices? 340**Symptom** 341 342 The device ID is not displayed after the following command is executed. 343 ```shell 344 hdc list targets 345 ``` 346 347**Solution** 348 349 * Ensure that USB debugging is enabled on the device. 350 * Ensure that the device is connected to the PC. 351 352### What should I do if "unauthorized" is displayed in the hdc command output? 353**Symptom** 354 355 When the hdc command is executed, the system displays a message indicating that the device is "unauthorized". 356 357**Possible Causes** 358 359 The PC is not authorized to debug the device. 360 361**Solution** 362 363 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**. 364 365### What should I do if the domain socket of DevTools cannot be found? 366**Symptom** 367 368 No result is displayed after the following command is executed in hdc shell. 369 ```shell 370 cat /proc/net/unix | grep devtools 371 ``` 372 373**Solution** 374 375 * Ensure that the step of [Enabling Web Debugging for Application Code](#enabling-web-debugging-for-application-code) is performed. 376 * Ensure that the application uses the **Web** component to load the web page. 377 378### What should I do if port forwarding fails 379**Symptom** 380 381 The configured forwarding task is not displayed after the following command is executed. 382 ```shell 383 hdc fport ls 384 ``` 385 386**Solution** 387 388 * Ensure that the domain socket exists on the device. 389 * Ensure that **tcp:9222** on the PC is not occupied. 390 If **tcp:9222** is occupied, forward the domain socket to another TCP port that is not occupied, for example, **tcp:9223**. 391 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. 392 393### What should I do if the web page to be debugged cannot be found in Chrome on the PC after port forwarding is successful? 394**Symptom** 395 396 The web page to be debugged cannot be found in Chrome on the PC. 397 398**Possible Causes** 399 400The port forwarding may be invalid due to the following reasons: 401 * The device is disconnected from the PC. As a result, all forwarding tasks in hdc are cleared. 402 * The hdc service is restarted. As a result, all forwarding tasks in hdc are cleared. 403 * 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. 404 * Exceptions occur when multiple forwarding tasks are forwarded to the same port. 405 406**Solution** 407 408 * Ensure that the local **tcp:9222** (or other configured port) on the PC is not occupied. 409 * Ensure that the domain socket exists on the device. 410 * Ensure that the process ID in the domain socket name is the same as that of the application to be debugged. 411 * Delete unnecessary forwarding tasks from hdc. 412 * 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. 413 414 - 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). 415  416 417 - If an error page is displayed, port forwarding fails. For details, see [What should I do if port forwarding fails](#what-should-i-do-if-port-forwarding-fails). 418  419 420 * 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: 421 - Ensure that the port number in **Configure** on the Chrome debugging page is the same as the TCP port number specified for port forwarding. 422 - In this topic, the default TCP port number is **9222**. 423 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). 424 425### What should I do if the Chrome browser on the PC cannot find the web page to be debugged after the wireless debugging mode is enabled? 426**Symptom** 427 428 After the wireless debugging mode is enabled for ArkWeb, the Chrome on the PC cannot detect the web page to be debugged. 429 430**Possible Causes** 431 432* The wireless debugging mode is not enabled. 433* The network between the debugging tool and the device to be debugged is disconnected. 434 435**Solution** 436 437* Ensure that the port can be used by applications. 438* Ensure that the debugging tool and the device to be debugged are in the same LAN and the network between them is normal. 439