首次使用Lighthouse遇Fetch失败错误,请求技术协助
解决TypeError: Failed to fetch browser webSocket URL from http://127.0.0.1:9222/json/version错误
这个错误核心是Lighthouse无法连接到指定端口(9222)的浏览器调试接口,按以下步骤排查解决:
确保浏览器以远程调试模式启动
不能直接打开普通浏览器窗口,必须通过命令行启动浏览器并开启远程调试端口。示例命令:- Windows:
chrome.exe --remote-debugging-port=9222 - Mac:
/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome --remote-debugging-port=9222 - Linux:
google-chrome --remote-debugging-port=9222
启动后再运行Lighthouse代码,确保端口和配置里的port:9222完全一致。
- Windows:
检查端口是否被占用
用命令查看9222端口是否被其他程序占用:- Windows:
netstat -ano | findstr :9222 - Mac/Linux:
lsof -i :9222
如果端口被占用,要么终止占用进程,要么修改Lighthouse配置里的port为其他未被占用的数值,同时启动浏览器时用对应端口参数。
- Windows:
改用代码自动启动浏览器(更省心)
手动启动浏览器容易出错,可通过puppeteer自动启动带调试端口的浏览器。操作步骤:- 先安装依赖:
npm install puppeteer - 使用修改后的代码:
const fs = require('fs'); const puppeteer = require('puppeteer'); const lighthouse = require('lighthouse/core/index.cjs'); (async () => { // 自动启动Chrome并开启远程调试 const browser = await puppeteer.launch({ headless: 'new', // 设为false可看到浏览器窗口 args: [`--remote-debugging-port=9222`], }); const lighthouseOptions = { logLevel: 'info', output: 'html', onlyCategories: ['performance'], port: 9222, }; const runnerResult = await lighthouse("https://www.google.com/", lighthouseOptions); const reportHtml = runnerResult.report; fs.writeFileSync('./lighthouse-report.html', reportHtml); // 结束后关闭浏览器 await browser.close(); })();这段代码会自动处理浏览器的启动和关闭,避免端口不匹配或浏览器未启动的问题。
- 先安装依赖:
排查防火墙/代理干扰
暂时关闭本地防火墙或代理工具,确认是否是它们阻止了Lighthouse访问本地调试接口。
内容的提问来源于stack exchange,提问作者SeleniumUser
相关产品推荐
相关产品推荐

