部署含Puppeteer的Firebase函数时Chrome找不到的问题求助
解决Firebase Functions部署Puppeteer时找不到Chrome的问题
核心原因
Firebase Functions的部署环境不会自动适配本地安装的Puppeteer Chromium——本地下载的Chromium是针对当前系统的,而Firebase运行环境为Linux,且部署过程中可能未正确打包Chromium文件。
具体解决方案
1. 改用Firebase环境预装的Chrome
修改Puppeteer启动代码,指定系统Chrome的固定路径:
const browser = await puppeteer.launch({ headless: true, args: ["--no-sandbox", "--disable-setuid-sandbox"], executablePath: "/usr/bin/google-chrome-stable" });
同时在package.json中添加环境变量,跳过本地Chromium下载:
{ "scripts": { "install": "PUPPETEER_SKIP_CHROMIUM_DOWNLOAD=true npm install" } }
2. 强制部署时包含Puppeteer自带的Chromium
如果坚持使用Puppeteer自带的Chromium,需修改firebase.json配置,确保Chromium文件被打包:
{ "functions": { "source": ".", "runtimeOptions": { "nodeVersion": "16" }, "ignore": [ "node_modules/**/!(*chromium*)" ] } }
并在package.json中固定Chromium缓存目录:
{ "config": { "puppeteer": { "cacheDirectory": "./node_modules/puppeteer/.local-chromium" } } }
3. 替换为puppeteer-core
puppeteer-core不包含Chromium,更适合服务器环境:
- 卸载原版Puppeteer:
npm uninstall puppeteer
- 安装对应版本的
puppeteer-core:
npm install puppeteer-core@19.0.0
- 修改启动代码指定系统Chrome路径:
const puppeteer = require('puppeteer-core'); const browser = await puppeteer.launch({ headless: true, args: ["--no-sandbox", "--disable-setuid-sandbox"], executablePath: "/usr/bin/google-chrome-stable" });
4. 补充权限相关启动参数
若仍有访问权限问题,添加--disable-dev-shm-usage参数优化内存访问:
const browser = await puppeteer.launch({ headless: true, args: [ "--no-sandbox", "--disable-setuid-sandbox", "--disable-dev-shm-usage" ], executablePath: "/usr/bin/google-chrome-stable" });
内容的提问来源于stack exchange,提问作者HunterWhiteDev
相关产品推荐
相关产品推荐

