本文同步发表于我的微信公众号,微信搜索 程语新视界 即可关注,每个工作日都有文章更新

   Web组件支持使用DevTools工具调试前端页面。DevTools是Web前端开发调试工具,支持在电脑上调试移动设备前端页面。开发者通过setWebDebuggingAccess()接口开启Web组件前端页面调试能力,使用DevTools在电脑上调试移动前端网页。

设备要求:HarmonyOS 4.1.0及以上版本

二、调试方式

调试方式 API版本要求 特点
无线调试 API 20+ 无需USB连接,配置简单
USB连接调试 任意版本 需要USB连接和端口转发

三、无线调试步骤

1. 代码开启Web调试开关

在应用中调用setWebDebuggingAccess()接口,设置TCP Socket端口号并启用Web调试功能:

// WebDebuggingWithWiFi.ets
import { webview } from '@kit.ArkWeb';
import { BusinessError } from '@kit.BasicServicesKit';

const DEBUGGING_PORT: number = 8888; // 自定义端口号

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  
  aboutToAppear(): void {
    try {
      // 配置Web开启无线调试模式,指定TCP Socket的端口
      webview.WebviewController.setWebDebuggingAccess(true, DEBUGGING_PORT);
    } catch (error) {
      console.error(`ErrorCode: ${(error as BusinessError).code}, Message: ${(error as BusinessError).message}`);
    }
  }

  build() {
    Column() {
      Web({ src: 'www.example.com', controller: this.controller })
    }
  }
}

2. 配置网络权限

module.json5中添加网络权限:

// module.json5
"requestPermissions": [
  {
    "name": "ohos.permission.INTERNET"
  }
]

3. 端口选择

  • 端口可用性:确保端口号可以被应用使用

  • 端口冲突:如果端口被占用,接口会抛出异常

  • 权限问题:应用无权限使用端口会导致调试模式开启失败

4. Chrome浏览器配置

步骤1:打开调试工具页面

  • 在电脑端Chrome浏览器地址栏输入:chrome://inspect/#devices

步骤2:配置网络发现

  • 确保勾选"Discover network targets"

  • 点击"Configure"按钮

  • 在"Target discovery settings"中添加:

    • 格式:被调试设备IP:端口号

    • 示例:192.168.0.3:8888

条件

  • 调试工具和被调试设备必须在同一局域网

  • 设备之间必须能够相互访问

  • 如果设备有多个IP地址,需使用与调试工具同一网段的IP

5. 等待发现被调试页面

配置成功后,Chrome调试页面将显示待调试的网页

6. 开始调试

点击对应页面的"inspect"链接,打开DevTools调试工具

四、USB连接调试步骤

1. 应用代码开启Web调试开关

// WebDebuggingWithUSB.ets
import { webview } from '@kit.ArkWeb';

@Entry
@Component
struct WebComponent {
  controller: webview.WebviewController = new webview.WebviewController();
  
  aboutToAppear() {
    // 配置Web开启调试模式(USB调试不需要指定端口)
    webview.WebviewController.setWebDebuggingAccess(true);
  }

  build() {
    Column() {
      Web({ src: 'www.example.com', controller: this.controller })
    }
  }
}

2. 配置网络权限

同样需要在module.json5中添加INTERNET权限。

3. 设备连接与准备

3.1 开启开发者模式和USB调试

开启开发者模式

  • 进入"设置 > 关于本机"

  • 连续七次单击"版本号"

  • 提示"开启开发者模式"后点击确认

  • 输入PIN码(如果已设置)

  • 设备自动重启

开启USB调试

  • USB数据线连接终端和电脑

  • 进入"设置 > 系统 > 开发者选项"

  • 打开"USB调试"开关

  • 在弹出的"允许USB调试"弹框中点击"允许"

3.2 使用hdc命令连接设备

检查设备连接

hdc list targets
  • 成功:返回设备ID

  • 失败:返回[Empty]

进入hdc shell

hdc shell

4. 端口转发

4.1 查询domain socket端口

在hdc shell中执行:

cat /proc/net/unix | grep devtools

执行结果将显示用于查询的domain socket端口:

注意事项

  • 如果没查询到结果,请确认:

    1. 应用已开启Web调试开关

    2. 应用已使用Web组件加载了网页

4.2 退出hdc shell
exit
4.3 执行端口转发
hdc fport tcp:9222 localabstract:webview_devtools_remote_38532

说明

  • webview_devtools_remote_后面的数字代表ArkWeb所在应用的进程号

  • 该数字不固定,需替换为自己查询到的值

  • 如果应用重新启动(进程号变化),需要重新配置端口转发

转发成功

4.4 检查端口转发
hdc fport ls
  • 成功:返回端口转发任务

  • 失败:返回[Empty]

5. Chrome浏览器配置

5.1 打开调试工具页面
chrome://inspect/#devices
5.2 配置本地端口监听
  • 确保勾选"Discover network targets"

  • 点击"Configure"按钮

  • 添加本地端口:localhost:9222

5.3 多应用调试配置

如需同时调试多个应用,可以添加多个端口号:

6. 等待发现被调试页面

成功配置后,Chrome调试页面将显示待调试的网页。

7. 开始调试

点击"inspect"链接进入DevTools调试界面。

五、脚本工具

Windows平台批处理脚本

创建debug_web.bat文件:

@echo off
setlocal enabledelayedexpansion

:: Initialize port number and PID list
set PORT=9222
set PID_LIST=

:: Get the list of all forwarded ports and PIDs
for /f "tokens=2,5 delims=:_" %%a in ('hdc fport ls') do (
  if %%a gtr !PORT! (
    set PORT=%%a
  )
  for /f "tokens=1 delims= " %%c in ("%%b") do (
    set PID_LIST=!PID_LIST! %%c
  )
)

:: Increment port number for next application
set temp_PORT=!PORT!
set /a temp_PORT+=1
set PORT=!temp_PORT!

:: Get the domain socket name of devtools
for /f "tokens=*" %%a in ('hdc shell "cat /proc/net/unix | grep devtools"') do (
  set SOCKET_NAME=%%a
  :: Extract process ID
  for /f "delims=_ tokens=4" %%b in ("!SOCKET_NAME!") do set PID=%%b
  
  :: Check if PID already has a mapping
  echo !PID_LIST! | findstr /C:" !PID! " >nul
  if errorlevel 1 (
    :: Add mapping
    hdc fport tcp:!PORT! localabstract:webview_devtools_remote_!PID!
    if errorlevel 1 (
      echo Error: Failed to add mapping.
      pause
      exit /b
    )
    :: Add PID to list and increment port number for next application
    set PID_LIST=!PID_LIST! !PID!
    set temp_PORT=!PORT!
    set /a temp_PORT+=1
    set PORT=!temp_PORT!
  )
)

:: If no process ID was found, prompt the user
if "!SOCKET_NAME!"=="" (
  echo No process ID was found. Please open debugging in your application code.
  pause
  exit /b
)

:: Check mapping
hdc fport ls
echo.
echo Script executed successfully. Press any key to exit...
pause >nul

:: Try to open the page in Edge
start msedge chrome://inspect/#devices
:: If Edge is not available, then open the page in Chrome
if errorlevel 1 (
  start chrome chrome://inspect/#devices
)

endlocal

Linux/Mac平台Shell脚本

创建debug_web.sh文件:

#!/bin/bash

# Get current fport rule list
CURRENT_FPORT_LIST=$(hdc fport ls)

# Delete the existing fport rule one by one
while IFS= read -r line; do
  # Extract the taskline
  IFS=' ' read -ra parts <<< "$line"
  taskline="${parts[1]} ${parts[2]}"
  
  # Delete the corresponding fport rule
  echo "Removing forward rule for $taskline"
  hdc fport rm $taskline
  result=$?
  if [ $result -eq 0 ]; then
    echo "Remove forward rule success, taskline:$taskline"
  else
    echo "Failed to remove forward rule, taskline:$taskline"
  fi
done <<< "$CURRENT_FPORT_LIST"

# Initial port number
INITIAL_PORT=9222

# Get the current port number, use initial port number if not set previously
CURRENT_PORT=${PORT:-$INITIAL_PORT}

# Get the list of all PIDs that match the condition
PID_LIST=$(hdc shell cat /proc/net/unix | grep webview_devtools_remote_ | awk -F '_' '{print $NF}')

if [ -z "$PID_LIST" ]; then
  echo "Failed to retrieve PID from the device"
  exit 1
fi

# Increment the port number
PORT=$CURRENT_PORT

# Forward ports for each application one by one
for PID in $PID_LIST; do
  # Increment the port number
  PORT=$((PORT + 1))
  
  # Execute the hdc fport command
  hdc fport tcp:$PORT localabstract:webview_devtools_remote_$PID
  
  # Check if the command executed successfully
  if [ $? -ne 0 ]; then
    echo "Failed to execute hdc fport command"
    exit 1
  fi
done

# List all forwarded ports
hdc fport ls

说明

  • 给脚本添加执行权限:chmod +x debug_web.sh

  • 注意格式转换(Windows和Linux换行符差异)

  • 脚本会先删除所有端口转发,可能影响其他工具(如DevEco Studio)

六、调试方式对比

对比项 无线调试 USB调试
API版本 API 20+ 任意版本
连接方式 同一局域网 USB数据线
配置复杂度 简单 较复杂
端口配置 应用代码指定端口 需要端口转发
多应用调试 多端口配置 多端口转发
稳定性 受网络影响 稳定
移动性 可自由移动 受线缆限制

核心流程

  1. 开启调试:调用setWebDebuggingAccess(true)(USB)或带端口参数(无线)

  2. 权限配置:添加INTERNET权限

  3. 连接设备:同一局域网(无线)或USB连接(有线)

  4. 建立通道:直接配置IP:端口(无线)或端口转发(USB)

  5. Chrome配置:添加对应地址到chrome://inspect/#devices

  6. 开始调试:点击"inspect"进入DevTools

Logo

作为“人工智能6S店”的官方数字引擎,为AI开发者与企业提供一个覆盖软硬件全栈、一站式门户。

更多推荐