From ef7ae7cbb458d9b070a7bba0a9a146396d89af43 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=90=B4=E5=9D=A4=E8=94=9A?= Date: Fri, 17 Apr 2026 11:57:51 +0800 Subject: [PATCH] =?UTF-8?q?fix:=20=E4=BB=8E=20HTTP=20API=20=E5=8A=A8?= =?UTF-8?q?=E6=80=81=E8=8E=B7=E5=8F=96=20Chrome=20WebSocket=20URL=EF=BC=8C?= =?UTF-8?q?=E8=A7=A3=E5=86=B3=20DevToolsActivePort=20=E8=BF=87=E6=97=B6?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 改用 /json/version HTTP API 获取最新 wsUrl,避免 Chrome 重启后 DevToolsActivePort 文件中的 wsPath 过期导致连接失败;原有 wsPath 回退逻辑保留。 Co-Authored-By: Claude Sonnet 4.5 --- scripts/cdp-proxy.mjs | 33 +++++++++++++++++++++++++++++---- 1 file changed, 29 insertions(+), 4 deletions(-) diff --git a/scripts/cdp-proxy.mjs b/scripts/cdp-proxy.mjs index af12281..85d3a59 100755 --- a/scripts/cdp-proxy.mjs +++ b/scripts/cdp-proxy.mjs @@ -101,9 +101,34 @@ function checkPort(port) { }); } -function getWebSocketUrl(port, wsPath) { - if (wsPath) return `ws://127.0.0.1:${port}${wsPath}`; - return `ws://127.0.0.1:${port}/devtools/browser`; +async function getWebSocketUrl(port, wsPath) { + // 优先从 HTTP API 获取最新 wsPath(避免 DevToolsActivePort 文件过时) + try { + const url = await new Promise((resolve, reject) => { + const req = http.get(`http://127.0.0.1:${port}/json/version`, { timeout: 2000 }, (res) => { + let data = ''; + res.on('data', chunk => data += chunk); + res.on('end', () => { + try { + const json = JSON.parse(data); + if (json.webSocketDebuggerUrl) { + resolve(json.webSocketDebuggerUrl.replace('ws://[::1]', 'ws://127.0.0.1')); + } else { + reject(new Error('无 webSocketDebuggerUrl')); + } + } catch (e) { reject(e); } + }); + }); + req.on('error', reject); + req.on('timeout', () => { req.destroy(); reject(new Error('timeout')); }); + }); + console.log(`[CDP Proxy] 从 HTTP API 获取 wsUrl: ${url}`); + return url; + } catch { + // 回退到文件中的 wsPath + if (wsPath) return `ws://127.0.0.1:${port}${wsPath}`; + return `ws://127.0.0.1:${port}/devtools/browser`; + } } // --- WebSocket 连接管理 --- @@ -129,7 +154,7 @@ async function connect() { chromeWsPath = discovered.wsPath; } - const wsUrl = getWebSocketUrl(chromePort, chromeWsPath); + const wsUrl = await getWebSocketUrl(chromePort, chromeWsPath); if (!wsUrl) throw new Error('无法获取 Chrome WebSocket URL'); return connectingPromise = new Promise((resolve, reject) => {