chrome-devtools
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseChrome 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 before running scripts.
pwd重要提示:运行脚本前务必检查。
pwdInstallation
安装
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 libsSupports: 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, yargsbash
npm install # Installs puppeteer, debug, yargsStep 3: Install ImageMagick (Optional, Recommended)
步骤3:安装ImageMagick(可选,推荐)
ImageMagick enables automatic screenshot compression to keep files under 5MB:
macOS:
bash
brew install imagemagickUbuntu/Debian/WSL:
bash
sudo apt-get install imagemagickVerify:
bash
magick -version # or: convert -versionWithout ImageMagick, screenshots >5MB will not be compressed (may fail to load in Gemini/Claude).
ImageMagick可实现截图自动压缩,使文件大小保持在5MB以下:
macOS:
bash
brew install imagemagickUbuntu/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.combash
node navigate.js --url https://example.comOutput: {"success": true, "url": "https://example.com", "title": "Example Domain"}
Output: {"success": true, "url": "https://example.com", "title": "Example Domain"}
undefinedundefinedAvailable Scripts
可用脚本
All scripts are in
.claude/skills/chrome-devtools/scripts/CRITICAL: Always check before running scripts.
pwd所有脚本位于目录下
.claude/skills/chrome-devtools/scripts/重要提示:运行脚本前务必检查。
pwdScript Usage
脚本用法
./scripts/README.md
./scripts/README.md
Core Automation
核心自动化功能
- - Navigate to URLs
navigate.js - - Capture screenshots (full page or element)
screenshot.js - - Click elements
click.js - - Fill form fields
fill.js - - Execute JavaScript in page context
evaluate.js
- - 导航至指定URL
navigate.js - - 捕获截图(整页或指定元素)
screenshot.js - - 点击元素
click.js - - 填充表单字段
fill.js - - 在页面上下文执行JavaScript
evaluate.js
Analysis & Monitoring
分析与监控
- - Extract interactive elements with metadata
snapshot.js - - Monitor console messages/errors
console.js - - Track HTTP requests/responses
network.js - - Measure Core Web Vitals + record traces
performance.js
- - 提取带有元数据的交互元素
snapshot.js - - 监控控制台消息/错误
console.js - - 追踪HTTP请求/响应
network.js - - 测量核心Web指标并记录性能轨迹
performance.js
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.pngImportant: Always save screenshots to directory.
./docs/screenshotsbash
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/screenshotsAutomatic 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
undefinedDefault: 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
undefinedbash
undefinedKeep 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]"
undefinednode 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]"
undefinedParse JSON Output
解析JSON输出
bash
undefinedbash
undefinedExtract 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
undefinednode network.js --url https://example.com --output /tmp/requests.json
undefinedExecution Protocol
执行规范
Working Directory Verification
工作目录验证
BEFORE executing any script:
- Check current working directory with
pwd - Verify in directory
.claude/skills/chrome-devtools/scripts/ - If wrong directory, to correct location
cd - Use absolute paths for all output files
Example:
bash
pwd # Should show: .../chrome-devtools/scripts执行任何脚本之前:
- 使用检查当前工作目录
pwd - 确认位于目录
.claude/skills/chrome-devtools/scripts/ - 如果目录错误,使用切换至正确位置
cd - 所有输出文件使用绝对路径
示例:
bash
pwd # 应显示:.../chrome-devtools/scriptsIf wrong:
如果目录错误:
cd .claude/skills/chrome-devtools/scripts
undefinedcd .claude/skills/chrome-devtools/scripts
undefinedOutput Validation
输出验证
AFTER screenshot/capture operations:
- Verify file created with
ls -lh <output-path> - Read screenshot using Read tool to confirm content
- Check JSON output for success:true
- 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截图/捕获操作完成后:
- 使用验证文件已创建
ls -lh <output-path> - 使用读取工具查看截图以确认内容
- 检查JSON输出中的
success:true - 报告文件大小和压缩状态
示例:
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:
- Check error message for selector issues
- Use snapshot.js to discover correct selectors
- Try XPath selector if CSS selector fails
- Verify element is visible and interactive
Example:
bash
undefined如果脚本执行失败:
- 检查错误信息,确认是否为选择器问题
- 使用查找正确的选择器
snapshot.js - 如果CSS选择器失败,尝试使用XPath选择器
- 验证元素是否可见且可交互
示例:
bash
undefinedCSS 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')]"
undefinednode click.js --url https://example.com --selector "//button[contains(text(),'Submit')]"
undefinedCommon 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 before running scripts
✅ Always validate output after screenshots
✅ Use snapshot.js to discover selectors
✅ Test selectors with simple commands first
pwd❌ 工作目录错误 → 输出文件保存至错误位置
❌ 跳过输出验证 → 静默失败
❌ 使用复杂CSS选择器而未测试 → 选择器错误
❌ 未检查元素可见性 → 超时错误
✅ 运行脚本前始终验证
✅ 截图后始终验证输出
✅ 使用查找选择器
✅ 先使用简单命令测试选择器
pwdsnapshot.jsCommon 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"
fibash
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"
fiForm 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:
- - Show browser window
--headless false - - Keep browser open for chaining
--close false - - Set timeout (milliseconds)
--timeout 30000 - - Wait strategy
--wait-until networkidle2
See for complete options.
./scripts/README.md所有脚本支持:
- - 显示浏览器窗口
--headless false - - 保持浏览器打开以便链式执行
--close false - - 设置超时时间(毫秒)
--timeout 30000 - - 等待策略
--wait-until networkidle2
完整选项请查看。
./scripts/README.mdOutput 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 to discover selectors:
snapshot.jsbash
node snapshot.js --url https://example.com | jq '.elements[] | {tagName, text, selector}'使用查找选择器:
snapshot.jsbash
node snapshot.js --url https://example.com | jq '.elements[] | {tagName, text, selector}'Troubleshooting
故障排除
Common Errors
常见错误
"Cannot find package 'puppeteer'"
- Run: in the scripts directory
npm install
"error while loading shared libraries: libnss3.so" (Linux/WSL)
- Missing system dependencies
- Fix: Run in scripts directory
./install-deps.sh - 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: then
npm rebuildnpm 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 rebuildnpm install
Chrome not found
- Puppeteer会在时自动下载Chrome
npm install - 如果下载失败,手动触发:
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: or
--wait-until load--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: or
magick -versionconvert -version - Check file was actually compressed in output JSON:
"compressed": true - For very large pages, use to capture only needed area
--selector
元素未找到
- 先使用查找正确的选择器:
snapshot.jsnode 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 -versionconvert -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
外部资源
- Puppeteer Documentation
- Chrome DevTools Protocol
- Scripts README
- Puppeteer Documentation
- Chrome DevTools Protocol
- Scripts README