第 2 课
排错与性能:控制台、网络、Lighthouse 和性能 trace
用控制台消息和网络请求查清示例页的 404,用 evaluate_script 执行脚本;用 lighthouse_audit 找出两个问题并改到满分,再给 developer.chrome.com 录性能 trace、展开 LCP 拆解,最后模拟手机和慢网络。
课程目录第 2 / 3 课
学习位置仅保存在当前浏览器,有效期 180 天。
接入编程智能体:MCP 配置、权限开关、Skills 与冒烟脚本
本课对照 chrome-devtools-mcp 官方 Tool reference、CLI guide 与 README 编写;命令与输出在 Debian 13 x86_64 测试机上实跑,版本 chrome-devtools-mcp 1.13.0、Google Chrome 156(2026-11-16)。
本课目标
- 用控制台和网络工具查清上一课那个 404 从哪来
- 用 evaluate_script 在页面里执行一段 JavaScript
- 用 lighthouse_audit 找出无障碍和 SEO 问题,改完再验证
- 录一段性能 trace,读懂 LCP 拆解,并知道 CrUX 数据从哪来
前置条件
- 做完第 1 课:守护进程在运行,页面 1 是 Demo Shop,并且已经点过一次搜索
- 第 5 步需要能访问 developer.chrome.com
第 1 步:列出控制台消息
chrome-devtools list_console_messages 1
## Console messages
Showing 1-3 of 3 (Page 1 of 1).
msgid=1 [log] page ready (1 args)
msgid=2 [error] Failed to load resource: the server responded
with a status of 404 (File not found) (0 args)
msgid=3 [error] search failed 404 (2 args)
有两条 error:一条是浏览器报的资源加载失败,一条是页面脚本自己打的日志。用 msgid 看单条详情:
chrome-devtools get_console_message 1 3
ID: 3
Message: error> search failed 404
### Arguments
Arg #0: search failed
Arg #1: 404
测试机上另一次实跑时,这里还多了一段 ### Stack trace,指向 (index):16:22,也就是 index.html 里 console.error 那一行。官方说明控制台消息会带上经过 source map 还原的调用栈,所以打包后的项目也能定位到源码。
第 2 步:列出网络请求,查看失败的那一条
chrome-devtools list_network_requests 1
## Network requests
Showing 1-3 of 3 (Page 1 of 1).
reqid=1 GET http://127.0.0.1:8811/ [200]
reqid=2 GET http://127.0.0.1:8811/favicon.ico [200]
reqid=3 GET http://127.0.0.1:8811/api/search?q=headphones [404]
chrome-devtools get_network_request 1 --reqid 3
对照结果(节选):
## Request http://127.0.0.1:8811/api/search?q=headphones
Status: 404
### Request Headers
- referer:http://127.0.0.1:8811/
- accept:*/*
...
### Response Headers
- content-type:text/html;charset=utf-8
- server:SimpleHTTP/0.6 Python/3.13.5
### Response Body
...
<p>Error code: 404</p>
<p>Message: File not found.</p>
结论很清楚:页面请求了 /api/search,但本地的静态服务器上没有这个接口。请求体和响应体很大时,可以加 --responseFilePath 存到文件里,不在终端刷屏。
第 3 步:在页面里执行 JavaScript
chrome-devtools evaluate_script \
"() => document.querySelectorAll('button').length" --pageId 1
Script ran on page and returned:
1
返回值会按 JSON 序列化,所以函数要返回能转成 JSON 的值。官方 Configuration 文档提供了 --no-javascript-evaluation 开关,不想让智能体在页面里随意执行脚本时可以关掉。
第 4 步:用 Lighthouse 查问题,改完再验证
chrome-devtools lighthouse_audit 1 --outputDirPath lh
对照结果(长行已折行):
## Lighthouse audit results
Mode: navigation
Device: desktop
URL: http://127.0.0.1:8811/
### Category scores
- Accessibility: 95 (accessibility)
- Best Practices: 100 (best-practices)
- SEO: 90 (seo)
- Agentic Browsing: 100 (agentic-browsing)
### Audit summary
Passed: 34
Failed: 2
Total timing: 3968.18ms
### Failed audits
- landmark-one-main [accessibility]: Document does not have
a main landmark. (score: 0)
...
- meta-description [seo]: Document does not have a meta
description (score: 0)
...
### Reports
- /home/you/cdm-demo/lh/report.json
- /home/you/cdm-demo/lh/report.html
注意它没有 Performance 分数。官方 Tool reference 写明 lighthouse_audit 只查无障碍、SEO、最佳实践和 Agentic Browsing,性能要用下一步的 trace。
按报告改两处。用编辑器打开 index.html,在 <title> 前加一行描述,并用 <main> 包住正文:
<head>
<meta charset="utf-8">
<meta name="description" content="A tiny demo shop">
<title>Demo Shop</title>
</head>
<body>
<main>
<h1>Demo Shop</h1>
<label for="q">Search</label>
<input id="q" placeholder="Search products">
<button id="go">Search</button>
<p id="out"></p>
</main>
<script>
<script> 之后的部分保持不变。然后刷新页面,用 snapshot 模式只分析当前状态:
chrome-devtools navigate_page 1 --type reload
chrome-devtools lighthouse_audit 1 --mode snapshot
Successfully reloaded the page.
...
## Lighthouse audit results
Mode: snapshot
Device: desktop
URL: http://127.0.0.1:8811/
### Category scores
- Accessibility: 100 (accessibility)
- Best Practices: 100 (best-practices)
- SEO: 100 (seo)
- Agentic Browsing: 100 (agentic-browsing)
### Audit summary
Passed: 17
Failed: 0
navigation 模式会重新加载页面再审计,snapshot 模式只看当前页面,检查项更少,适合改完立刻复查。
第 5 步:录一段性能 trace
官方 README 的第一个示例就是检查 developer.chrome.com 的性能。先在新页面里打开它,再录 trace:
chrome-devtools new_page "https://developer.chrome.com/"
chrome-devtools performance_start_trace 2 --filePath trace.json.gz
对照结果(节选,数字每次不同):
## Pages
1: Demo Shop (http://127.0.0.1:8811/)
2: Chrome for Developers (https://developer.chrome.com/) [selected]
The raw trace data was saved to /home/you/cdm-demo/trace.json.gz.
The performance trace has been stopped.
## Summary of Performance trace findings:
URL: https://developer.chrome.com/
CPU throttling: 1x
Network throttling: none
...
## insight set id: NAVIGATION_0
Metrics (lab / observed):
- LCP: 716 ms, event: (eventKey: r-9438, ...), nodeId: 12
- LCP breakdown:
- TTFB: 486 ms, ...
- Load delay: 73 ms, ...
- Load duration: 3 ms, ...
- Render delay: 154 ms, ...
- CLS: 0.24, ...
Metrics (field / real users):
- LCP: 2795 ms (scope: url)
- INP: 135 ms (scope: url)
- CLS: 0.07 (scope: url)
...
Available insights:
- insight name: LCPBreakdown
- insight name: LCPDiscovery
- insight name: CLSCulprits
- insight name: RenderBlocking
- insight name: NetworkDependencyTree
- insight name: ThirdParties
performance_start_trace 默认会自动刷新页面并在加载完成后自动停止,所以要先用 navigate_page 或 new_page 打开目标网址。--filePath 把原始 trace 存下来,之后可以拖进 Chrome DevTools 的 Performance 面板查看。
输出分两组指标。lab 是这次在本机测到的;field 来自 CrUX,即真实 Chrome 用户的第 75 百分位数据。为了取 field 数据,工具会把 trace 里的网址发给 Google 的 CrUX 接口。内网或保密页面不想外发时,启动时加 --no-performance-crux。
第 6 步:展开一条 insight
挑上面列出的 LCPBreakdown 看详情:
chrome-devtools performance_analyze_insight 2 NAVIGATION_0 \
LCPBreakdown
对照结果(节选):
## Insight Title: LCP breakdown
...
The Largest Contentful Paint (LCP) time for this navigation
was 716 ms.
The LCP element (IMG, nodeId: 12) is an image fetched from
https://developer.chrome.com/static/images/io/
2026-ondemand_720.png
...
- Time to first byte: 486 ms (67.9% of total LCP time)
- Resource load delay: 73 ms (10.2% of total LCP time)
- Resource load duration: 3 ms (0.4% of total LCP time)
- Element render delay: 154 ms (21.5% of total LCP time)
## Estimated savings: none
这次 LCP 的大头是首字节时间 TTFB,说明慢在服务器响应,不在图片下载。智能体拿到这份拆解后,就能有针对性地给出优化建议。
第 7 步:模拟手机和慢网络
chrome-devtools emulate 1 --viewport "390x844x3,mobile,touch" \
--networkConditions "Slow 4G"
chrome-devtools take_screenshot 1 --filePath shop-mobile.png
chrome-devtools emulate 1
Emulation configured successfully
Emulating network conditions: Slow 4G
Default navigation timeout set to 25000 ms
Emulating viewport: {"deviceScaleFactor":3,"isMobile":true,
"hasTouch":true,"isLandscape":false,"width":390,"height":844}
...
Emulation configured successfully
每次调用 emulate 都会替换全部模拟设置,所以要一次把参数传全。最后一条不带参数的 emulate 1 用来恢复默认。
常见坑
- trace 录的是空白页:录之前先用
navigate_page打开目标网址,--reload默认会刷新当前页 - Lighthouse 里没有性能分:这是设计如此,性能看 trace
- insight 名称写错:只能用 trace 输出里 Available insights 列出的名字,insight set id 也要照抄
- 内网页面被发去 CrUX:启动时加
--no-performance-crux
小结
控制台、网络、脚本执行、Lighthouse 和性能 trace,正是你平时在 DevTools 里手动做的那几件事。现在它们都变成了有固定输入输出的命令,智能体可以自己调用、自己读结果。下一课把它接进编程智能体,并写一个能放进 CI 的冒烟脚本。
