依赖信息:
electron ^13.0.0
puppeteer ^9.0.0
vue-cli-plugin-electron-builder ~2.1.1
// background.js
主线程增加监听,渲染层会有个按钮向主线程发送通知,以调起puppeteer脚本唤起浏览器
ipcMain.on("Start", () => {
puppeteer.launch({
headless: false
}).then(async browser => {
const page = await browser.newPage();
await page.goto('https://www.google.com');
console.log(await page.title());
await browser.close();
})
})
启动命令:
npm run electron:serve
点击按钮,控制台报错:
UnhandledPromiseRejectionWarning: Error: Could not find expected browser (chrome) locally. Run `npm install` to download the correct Chromium revision (869685).
at ChromeLauncher.launch (webpack:///./node_modules/puppeteer/lib/cjs/puppeteer/node/Launcher.js?:82:27)
(node:8885) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
参考puppeteer/troubleshooting.md at main · puppeteer/puppeteer · GitHub
提示的问题是找不到可以启动的浏览器程序。
由于没有设置executablePath指定可以启动的浏览器,打印默认的Chromuim的位置
console.log(puppeteer.executablePath)
显示:dist_electron/.local-chromium/mac-869685/chrome-mac/Chromium.app/Contents/MacOS/Chromium
可见electron-build的开发环境下,puppeteer默认是在运行相对目录dist_electron中找Chromium的启动文件npm run electron:serve 启动命令不会讲node_modules/puppeteer/.local-chromium目录复制到dist_electron下。
解决方法:
目前是手动将node_modules/puppeteer/.local-chromium目录复制到dist_electron下。