chrome-devtools

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Chrome DevTools Agent Skill

Chrome DevTools Agent 技能

Browser automation via executable Puppeteer scripts. All scripts output JSON for easy parsing.
通过可执行的Puppeteer脚本实现浏览器自动化。所有脚本均输出JSON格式,便于解析。

Quick Start

快速开始

CRITICAL: Always check
pwd
before running scripts.
重要提示:运行脚本前务必检查
pwd

Installation

安装

Step 1: Install System Dependencies (Linux/WSL only)

步骤1:安装系统依赖(仅Linux/WSL)

On Linux/WSL, Chrome requires system libraries. Install them first:
bash
pwd  # Should show current working directory
cd .claude/skills/chrome-devtools/scripts
./install-deps.sh  # Auto-detects OS and installs required libs
Supports: Ubuntu, Debian, Fedora, RHEL, CentOS, Arch, Manjaro
macOS/Windows: Skip this step (dependencies bundled with Chrome)
在Linux/WSL系统中,Chrome需要依赖系统库,请先安装:
bash
pwd  # Should show current working directory
cd .claude/skills/chrome-devtools/scripts
./install-deps.sh  # Auto-detects OS and installs required libs
支持系统:Ubuntu、Debian、Fedora、RHEL、CentOS、Arch、Manjaro
macOS/Windows:跳过此步骤(Chrome已捆绑依赖)

Step 2: Install Node Dependencies

步骤2:安装Node依赖

bash
npm install  # Installs puppeteer, debug, yargs
bash
npm install  # Installs puppeteer, debug, yargs

Step 3: Install ImageMagick (Optional, Recommended)

步骤3:安装ImageMagick(可选,推荐)

ImageMagick enables automatic screenshot compression to keep files under 5MB:
macOS:
bash
brew install imagemagick
Ubuntu/Debian/WSL:
bash
sudo apt-get install imagemagick
Verify:
bash
magick -version  # or: convert -version
Without ImageMagick, screenshots >5MB will not be compressed (may fail to load in Gemini/Claude).
ImageMagick可实现截图自动压缩,使文件大小保持在5MB以下:
macOS:
bash
brew install imagemagick
Ubuntu/Debian/WSL:
bash
sudo apt-get install imagemagick
验证:
bash
magick -version  # or: convert -version
如果未安装ImageMagick,超过5MB的截图将不会被压缩(可能无法在Gemini/Claude中加载)。

Test

测试

bash
node navigate.js --url https://example.com
bash
node navigate.js --url https://example.com

Output: {"success": true, "url": "https://example.com", "title": "Example Domain"}

Output: {"success": true, "url": "https://example.com", "title": "Example Domain"}

undefined
undefined

Available Scripts

可用脚本

All scripts are in
.claude/skills/chrome-devtools/scripts/
CRITICAL: Always check
pwd
before running scripts.
所有脚本位于
.claude/skills/chrome-devtools/scripts/
目录下
重要提示:运行脚本前务必检查
pwd

Script Usage

脚本用法

  • ./scripts/README.md
  • ./scripts/README.md

Core Automation

核心自动化功能

  • navigate.js
    - Navigate to URLs
  • screenshot.js
    - Capture screenshots (full page or element)
  • click.js
    - Click elements
  • fill.js
    - Fill form fields
  • evaluate.js
    - Execute JavaScript in page context
  • navigate.js
    - 导航至指定URL
  • screenshot.js
    - 捕获截图(整页或指定元素)
  • click.js
    - 点击元素
  • fill.js
    - 填充表单字段
  • evaluate.js
    - 在页面上下文执行JavaScript

Analysis & Monitoring

分析与监控

  • snapshot.js
    - Extract interactive elements with metadata
  • console.js
    - Monitor console messages/errors
  • network.js
    - Track HTTP requests/responses
  • performance.js
    - Measure Core Web Vitals + record traces
  • snapshot.js
    - 提取带有元数据的交互元素
  • console.js
    - 监控控制台消息/错误
  • network.js
    - 追踪HTTP请求/响应
  • performance.js
    - 测量核心Web指标并记录性能轨迹

Usage Patterns

使用模式

Single Command

单命令执行

bash
pwd  # Should show current working directory
cd .claude/skills/chrome-devtools/scripts
node screenshot.js --url https://example.com --output ./docs/screenshots/page.png
Important: Always save screenshots to
./docs/screenshots
directory.
bash
pwd  # Should show current working directory
cd .claude/skills/chrome-devtools/scripts
node screenshot.js --url https://example.com --output ./docs/screenshots/page.png
注意:请始终将截图保存至
./docs/screenshots
目录。

Automatic Image Compression

自动图片压缩

Screenshots are automatically compressed if they exceed 5MB to ensure compatibility with Gemini API and Claude Code (which have 5MB limits). This uses ImageMagick internally:
bash
undefined
如果截图大小超过5MB,将自动进行压缩,以确保与Gemini API和Claude Code(均有5MB大小限制)兼容。此功能内部使用ImageMagick:
bash
undefined

Default: auto-compress if >5MB

默认:超过5MB时自动压缩

node screenshot.js --url https://example.com --output page.png
node screenshot.js --url https://example.com --output page.png

Custom size threshold (e.g., 3MB)

自定义大小阈值(如3MB)

node screenshot.js --url https://example.com --output page.png --max-size 3
node screenshot.js --url https://example.com --output page.png --max-size 3

Disable compression

禁用压缩

node screenshot.js --url https://example.com --output page.png --no-compress

**Compression behavior:**
- PNG: Resizes to 90% + quality 85 (or 75% + quality 70 if still too large)
- JPEG: Quality 80 + progressive encoding (or quality 60 if still too large)
- Other formats: Converted to JPEG with compression
- Requires ImageMagick installed (see imagemagick skill)

**Output includes compression info:**
```json
{
  "success": true,
  "output": "/path/to/page.png",
  "compressed": true,
  "originalSize": 8388608,
  "size": 3145728,
  "compressionRatio": "62.50%",
  "url": "https://example.com"
}
node screenshot.js --url https://example.com --output page.png --no-compress

**压缩行为:**
- PNG:先调整为原大小的90%并设置质量为85(如果仍过大,则调整为75%大小+70质量)
- JPEG:质量设为80并启用渐进式编码(如果仍过大,则质量设为60)
- 其他格式:转换为JPEG并进行压缩
- 需要安装ImageMagick(请参考ImageMagick技能)

**输出包含压缩信息:**
```json
{
  "success": true,
  "output": "/path/to/page.png",
  "compressed": true,
  "originalSize": 8388608,
  "size": 3145728,
  "compressionRatio": "62.50%",
  "url": "https://example.com"
}

Chain Commands (reuse browser)

链式命令(复用浏览器)

bash
undefined
bash
undefined

Keep browser open with --close false

保持浏览器打开,使用--close false

node navigate.js --url https://example.com/login --close false node fill.js --selector "#email" --value "user@example.com" --close false node fill.js --selector "#password" --value "secret" --close false node click.js --selector "button[type=submit]"
undefined
node navigate.js --url https://example.com/login --close false node fill.js --selector "#email" --value "user@example.com" --close false node fill.js --selector "#password" --value "secret" --close false node click.js --selector "button[type=submit]"
undefined

Parse JSON Output

解析JSON输出

bash
undefined
bash
undefined

Extract specific fields with jq

使用jq提取特定字段

node performance.js --url https://example.com | jq '.vitals.LCP'
node performance.js --url https://example.com | jq '.vitals.LCP'

Save to file

保存至文件

node network.js --url https://example.com --output /tmp/requests.json
undefined
node network.js --url https://example.com --output /tmp/requests.json
undefined

Execution Protocol

执行规范

Working Directory Verification

工作目录验证

BEFORE executing any script:
  1. Check current working directory with
    pwd
  2. Verify in
    .claude/skills/chrome-devtools/scripts/
    directory
  3. If wrong directory,
    cd
    to correct location
  4. Use absolute paths for all output files
Example:
bash
pwd  # Should show: .../chrome-devtools/scripts
执行任何脚本之前:
  1. 使用
    pwd
    检查当前工作目录
  2. 确认位于
    .claude/skills/chrome-devtools/scripts/
    目录
  3. 如果目录错误,使用
    cd
    切换至正确位置
  4. 所有输出文件使用绝对路径
示例:
bash
pwd  # 应显示:.../chrome-devtools/scripts

If wrong:

如果目录错误:

cd .claude/skills/chrome-devtools/scripts
undefined
cd .claude/skills/chrome-devtools/scripts
undefined

Output Validation

输出验证

AFTER screenshot/capture operations:
  1. Verify file created with
    ls -lh <output-path>
  2. Read screenshot using Read tool to confirm content
  3. Check JSON output for success:true
  4. Report file size and compression status
Example:
bash
node screenshot.js --url https://example.com --output ./docs/screenshots/page.png
ls -lh ./docs/screenshots/page.png  # Verify file exists
截图/捕获操作完成后:
  1. 使用
    ls -lh <output-path>
    验证文件已创建
  2. 使用读取工具查看截图以确认内容
  3. 检查JSON输出中的
    success:true
  4. 报告文件大小和压缩状态
示例:
bash
node screenshot.js --url https://example.com --output ./docs/screenshots/page.png
ls -lh ./docs/screenshots/page.png  # 验证文件存在

Then use Read tool to visually inspect

然后使用读取工具进行视觉检查


5. Restart working directory to the project root.

5. 将工作目录恢复至项目根目录。

Error Recovery

错误恢复

If script fails:
  1. Check error message for selector issues
  2. Use snapshot.js to discover correct selectors
  3. Try XPath selector if CSS selector fails
  4. Verify element is visible and interactive
Example:
bash
undefined
如果脚本执行失败:
  1. 检查错误信息,确认是否为选择器问题
  2. 使用
    snapshot.js
    查找正确的选择器
  3. 如果CSS选择器失败,尝试使用XPath选择器
  4. 验证元素是否可见且可交互
示例:
bash
undefined

CSS selector fails

CSS选择器失败

node click.js --url https://example.com --selector ".btn-submit"
node click.js --url https://example.com --selector ".btn-submit"

Error: waiting for selector ".btn-submit" failed

错误:waiting for selector ".btn-submit" failed

Discover correct selector

查找正确的选择器

node snapshot.js --url https://example.com | jq '.elements[] | select(.tagName=="BUTTON")'
node snapshot.js --url https://example.com | jq '.elements[] | select(.tagName=="BUTTON")'

Try XPath

尝试XPath

node click.js --url https://example.com --selector "//button[contains(text(),'Submit')]"
undefined
node click.js --url https://example.com --selector "//button[contains(text(),'Submit')]"
undefined

Common Mistakes

常见错误

❌ Wrong working directory → output files go to wrong location ❌ Skipping output validation → silent failures ❌ Using complex CSS selectors without testing → selector errors ❌ Not checking element visibility → timeout errors
✅ Always verify
pwd
before running scripts ✅ Always validate output after screenshots ✅ Use snapshot.js to discover selectors ✅ Test selectors with simple commands first
❌ 工作目录错误 → 输出文件保存至错误位置 ❌ 跳过输出验证 → 静默失败 ❌ 使用复杂CSS选择器而未测试 → 选择器错误 ❌ 未检查元素可见性 → 超时错误
✅ 运行脚本前始终验证
pwd
✅ 截图后始终验证输出 ✅ 使用
snapshot.js
查找选择器 ✅ 先使用简单命令测试选择器

Common Workflows

常见工作流

Web Scraping

网页抓取

bash
node evaluate.js --url https://example.com --script "
  Array.from(document.querySelectorAll('.item')).map(el => ({
    title: el.querySelector('h2')?.textContent,
    link: el.querySelector('a')?.href
  }))
" | jq '.result'
bash
node evaluate.js --url https://example.com --script "
  Array.from(document.querySelectorAll('.item')).map(el => ({
    title: el.querySelector('h2')?.textContent,
    link: el.querySelector('a')?.href
  }))
" | jq '.result'

Performance Testing

性能测试

bash
PERF=$(node performance.js --url https://example.com)
LCP=$(echo $PERF | jq '.vitals.LCP')
if (( $(echo "$LCP < 2500" | bc -l) )); then
  echo "✓ LCP passed: ${LCP}ms"
else
  echo "✗ LCP failed: ${LCP}ms"
fi
bash
PERF=$(node performance.js --url https://example.com)
LCP=$(echo $PERF | jq '.vitals.LCP')
if (( $(echo "$LCP < 2500" | bc -l) )); then
  echo "✓ LCP通过:${LCP}ms"
else
  echo "✗ LCP失败:${LCP}ms"
fi

Form Automation

表单自动化

bash
node fill.js --url https://example.com --selector "#search" --value "query" --close false
node click.js --selector "button[type=submit]"
bash
node fill.js --url https://example.com --selector "#search" --value "query" --close false
node click.js --selector "button[type=submit]"

Error Monitoring

错误监控

bash
node console.js --url https://example.com --types error,warn --duration 5000 | jq '.messageCount'
bash
node console.js --url https://example.com --types error,warn --duration 5000 | jq '.messageCount'

Script Options

脚本选项

All scripts support:
  • --headless false
    - Show browser window
  • --close false
    - Keep browser open for chaining
  • --timeout 30000
    - Set timeout (milliseconds)
  • --wait-until networkidle2
    - Wait strategy
See
./scripts/README.md
for complete options.
所有脚本支持:
  • --headless false
    - 显示浏览器窗口
  • --close false
    - 保持浏览器打开以便链式执行
  • --timeout 30000
    - 设置超时时间(毫秒)
  • --wait-until networkidle2
    - 等待策略
完整选项请查看
./scripts/README.md

Output Format

输出格式

All scripts output JSON to stdout:
json
{
  "success": true,
  "url": "https://example.com",
  ... // script-specific data
}
Errors go to stderr:
json
{
  "success": false,
  "error": "Error message"
}
所有脚本均向标准输出(stdout)输出JSON:
json
{
  "success": true,
  "url": "https://example.com",
  ... // 脚本特定数据
}
错误信息输出至标准错误(stderr):
json
{
  "success": false,
  "error": "Error message"
}

Finding Elements

查找元素

Use
snapshot.js
to discover selectors:
bash
node snapshot.js --url https://example.com | jq '.elements[] | {tagName, text, selector}'
使用
snapshot.js
查找选择器:
bash
node snapshot.js --url https://example.com | jq '.elements[] | {tagName, text, selector}'

Troubleshooting

故障排除

Common Errors

常见错误

"Cannot find package 'puppeteer'"
  • Run:
    npm install
    in the scripts directory
"error while loading shared libraries: libnss3.so" (Linux/WSL)
  • Missing system dependencies
  • Fix: Run
    ./install-deps.sh
    in scripts directory
  • Manual install:
    sudo apt-get install -y libnss3 libnspr4 libasound2t64 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1
"Failed to launch the browser process"
  • Check system dependencies installed (Linux/WSL)
  • Verify Chrome downloaded:
    ls ~/.cache/puppeteer
  • Try:
    npm rebuild
    then
    npm install
Chrome not found
  • Puppeteer auto-downloads Chrome during
    npm install
  • If failed, manually trigger:
    npx puppeteer browsers install chrome
"Cannot find package 'puppeteer'"
  • 解决方法:在脚本目录中运行
    npm install
"error while loading shared libraries: libnss3.so"(Linux/WSL)
  • 缺少系统依赖
  • 解决方法:在脚本目录中运行
    ./install-deps.sh
  • 手动安装:
    sudo apt-get install -y libnss3 libnspr4 libasound2t64 libatk1.0-0 libatk-bridge2.0-0 libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 libxrandr2 libgbm1
"Failed to launch the browser process"
  • 检查系统依赖是否已安装(Linux/WSL)
  • 验证Chrome是否已下载:
    ls ~/.cache/puppeteer
  • 尝试:
    npm rebuild
    然后
    npm install
Chrome not found
  • Puppeteer会在
    npm install
    时自动下载Chrome
  • 如果下载失败,手动触发:
    npx puppeteer browsers install chrome

Script Issues

脚本问题

Element not found
  • Get snapshot first to find correct selector:
    node snapshot.js --url <url>
Script hangs
  • Increase timeout:
    --timeout 60000
  • Change wait strategy:
    --wait-until load
    or
    --wait-until domcontentloaded
Blank screenshot
  • Wait for page load:
    --wait-until networkidle2
  • Increase timeout:
    --timeout 30000
Permission denied on scripts
  • Make executable:
    chmod +x *.sh
Screenshot too large (>5MB)
  • Install ImageMagick for automatic compression
  • Manually set lower threshold:
    --max-size 3
  • Use JPEG format instead of PNG:
    --format jpeg --quality 80
  • Capture specific element instead of full page:
    --selector .main-content
Compression not working
  • Verify ImageMagick installed:
    magick -version
    or
    convert -version
  • Check file was actually compressed in output JSON:
    "compressed": true
  • For very large pages, use
    --selector
    to capture only needed area
元素未找到
  • 先使用
    snapshot.js
    查找正确的选择器:
    node snapshot.js --url <url>
脚本挂起
  • 增加超时时间:
    --timeout 60000
  • 更改等待策略:
    --wait-until load
    --wait-until domcontentloaded
截图空白
  • 等待页面加载完成:
    --wait-until networkidle2
  • 增加超时时间:
    --timeout 30000
脚本权限被拒绝
  • 设置可执行权限:
    chmod +x *.sh
截图过大(>5MB)
  • 安装ImageMagick以启用自动压缩
  • 手动设置更低的阈值:
    --max-size 3
  • 使用JPEG格式替代PNG:
    --format jpeg --quality 80
  • 捕获特定元素而非整页:
    --selector .main-content
压缩未生效
  • 验证ImageMagick是否已安装:
    magick -version
    convert -version
  • 在输出JSON中检查文件是否已压缩:
    "compressed": true
  • 对于超大页面,使用
    --selector
    仅捕获所需区域

Reference Documentation

参考文档

Detailed guides available in
./references/
:
  • CDP Domains Reference - 47 Chrome DevTools Protocol domains
  • Puppeteer Quick Reference - Complete Puppeteer API patterns
  • Performance Analysis Guide - Core Web Vitals optimization
详细指南位于
./references/
目录下:
  • CDP Domains Reference - 47个Chrome DevTools Protocol域
  • Puppeteer Quick Reference - 完整Puppeteer API模式
  • Performance Analysis Guide - 核心Web指标优化

Advanced Usage

高级用法

Custom Scripts

自定义脚本

Create custom scripts using shared library:
javascript
import { getBrowser, getPage, closeBrowser, outputJSON } from './lib/browser.js';
// Your automation logic
使用共享库创建自定义脚本:
javascript
import { getBrowser, getPage, closeBrowser, outputJSON } from './lib/browser.js';
// 你的自动化逻辑

Direct CDP Access

直接访问CDP

javascript
const client = await page.createCDPSession();
await client.send('Emulation.setCPUThrottlingRate', { rate: 4 });
See reference documentation for advanced patterns and complete API coverage.
javascript
const client = await page.createCDPSession();
await client.send('Emulation.setCPUThrottlingRate', { rate: 4 });
高级模式和完整API覆盖请参考参考文档。

External Resources

外部资源