在 运行 electron-builder 之后,Puppeteer 在 React 应用程序中失败

Puppeteer fails in React app after running electron-builder

我在 React 应用程序中的一些后端 js 中使用 puppeteer。

关于 puppeteer 组件的代码相当简单,并且在 yarn 中的正常开发脚本中测试应用程序时它可以工作。可能相关的代码相当简单:

const puppeteer = require('puppeteer');
  try {
     let browser = await puppeteer.launch({headless: false, 
     executablePath: process.env.CHROMIUM_PATH,
     args: ["--no-sandbox",
            "--disable-setuid-sandbox"]
});}
  catch (error) {
    return await error;
  }

但是,当我使用 electron-builder 将项目编译成可执行文件时,我收到以下错误消息:

Error: Failed to launch the browser process! spawn 
<project directory in AppData>\node_modules\puppeteer\.local-chromium\win32\chrome-win\chrome.exe 
ENOENT TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md

我以为可能是我的依赖有问题,但我觉得我已经尝试了一切

有人指导吗?

.local-chromium 文件摘要:

.local-chromium
  |win32
    |chrome-win
      |locales
      |MEIPreload
      |swiftshader
      |files within chrome-win

Files within chrome-win include:
-chrome.exe
-chrome_proxy.exe
-chrome_pwalauncher.exe
-chrome.dll
-Other PAK files, and smaller applications

除了子目录外,.local-chromium 或 win32 中没有任何内容

看来问题与解压缩失败有关。 GitHub.

上实际上有一个未解决的问题

在这种情况下,一种可能的解决方法是手动解压缩 zip 文件并将其提取到 chrome-win 文件夹中。

对于 Mac(GitHub 问题的解决方法)是这样的:

unzip node_modules/puppeteer/.local-chromium/chrome-mac.zip
cp -r chrome-mac/Chromium.app/ ./node_modules/puppeteer/.local-chromium/mac-756035/chrome-mac/Chromium.app/

所以我认为在您的情况下,您应该在 win32chrome-win 文件夹中查找 zip 文件并将其复制到 chrome-win 文件夹。

正如 sebasaenz 所建议的,这是 puppeteer 访问 Chromium 的问题。我查看了未压缩的目录,但所有文件看起来都已提取。

我无法弄清楚 .local-chromium 的问题所在,所以我决定转换角度,将 puppeteer 引导到我的正常 chrome.exe 到 运行 本身。您可以使用 puppeteer.launch:

中的 executablePath 参数执行此操作
let browser = await puppeteer.launch({executablePath: "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"})

chrome.exe 对您来说可能位于不同的位置,但我很确定我的是默认位置

这确实让我的应用程序在打包时可以工作,不幸的是,这意味着如果 chrome 路径不同,当移动到另一台机器时它不会自动工作。不过,对于一个工作程序来说,这并不是最糟糕的折衷。

我的应用安装在 resources/app.asar.unpacked 目录中。它抛出的错误是

spawn <install_directory>\win-unpacked\resources\app.asar\node_modules\puppeteer\.local-chromium\win64-856583\chrome-win\chrome.exe ENOENT

所以,当启动 puppeteer 时,我这样做:

async function openBrowser() {
  var executablePath = 
    puppeteer
      .executablePath()
      .replace("app.asar", "app.asar.unpacked")

  const browser = await puppeteer.launch({ 
    executablePath: executablePath
  });

  return browser
}

第一遍有效,尚未分发给用户。还没有在 OSX.

上测试过

Puppeteer 失败,因为它找不到它的可执行文件,使用下面的解决方案,这对我的产品和开发环境都有效。


"build": {
   "asar": true,
   "asarUnpack": "node_modules/puppeteer/.local-chromium/**/*"
 }


 function getChromiumExecPath() {
    return puppeteer.executablePath().replace('app.asar', 'app.asar.unpacked');
 }

 export function createBrowser(options = {}) {
     return puppeteer.launch({
            ...options,
            executablePath: getChromiumExecPath()
      });
 }