写在前面:
"puppeteer-core": "^23.10.0",
"electron": "^30.5.0"
puppeteer文档: puppeteer.bootcss.com/
electron中文网: electron.nodejs.cn/
首先,在electron中打开新窗口后我们需要调用 puppeteer.connect 去连接窗口,那么需要先打开electron的调试端口,
app.commandLine.appendSwitch('remote-debugging-port', '9222');
打开调试端口后,我们就可以开始使用fetch来访问这个端口来获取所有可调试页面
const debugPort = 9222; // 确保与上面启用的调试端口一致
await fetch(`http://localhost:${debugPort}/json/list`).then((res) => res.json());
查看结果:
[
{
description: '',
devtoolsFrontendUrl: '/devtools/inspector.html?ws=localhost:9222/devtools/page/173B91655CB3C0E4CE5D4D3755E5E1B5',
id: '173B91655CB3C0E4CE5D4D3755E5E1B5',
title: '***.com',
type: 'page',
url: 'https://www.***.com/',
webSocketDebuggerUrl: 'ws://localhost:9222/devtools/page/173B91655C***5E5E1B5'
},
{
description: '',
devtoolsFrontendUrl: '/devtools/inspector.html?ws=localhost:9222/devtools/page/2BA5C5947CD249CC4706FCF1C9223278',
id: '2BA5C5947CD249CC4706FCF1C9223278',
parentId: 'DC8162669F9F357A0D38754644B1BEB8',
title: '鎷煎澶?,
type: 'webview',
url: 'https://mobile.yangkeduo.com/',
webSocketDebuggerUrl: 'ws://localhost:9222/devtools/page/2BA5C5947CD***FCF1C9223278'
},
{
description: '',
devtoolsFrontendUrl: '/devtools/inspector.html?ws=localhost:9222/devtools/page/DC8162669F9F357A0D38754644B1BEB8',
id: 'DC8162669F9F357A0D38754644B1BEB8',
title: '楸煎澶?,
type: 'page',
url: 'http://localhost:5173/#/video-download',
webSocketDebuggerUrl: 'ws://localhost:9222/devtools/page/DC8162669F9F357***754644B1BEB8'
},
{
description: '',
devtoolsFrontendUrl: '/devtools/inspector.html?ws=localhost:9222/devtools/page/62857886A1F32C53804A52ECCF52DC53',
id: '62857886A1F32C53804A52ECCF52DC53',
title: 'Service Worker https://www.***.com/sw.js',
type: 'service_worker',
url: 'https://www.***.com/sw.js',
webSocketDebuggerUrl: 'ws://localhost:9222/devtools/page/62857886A***53804A52ECCF52DC53'
}
]
拿到自己需要的对象,然后使用devtoolsFrontendUrl这个url去连接,不要用ws连接,ws连接的时候会报协议错误,例如c站这个博主的解决方案就成功的把我带进了深渊
拿到devtoolsFrontendUrl之后就可以使用puppeteer来对窗口进行自动化操作了。