由于 Chrome 修订,Firebase puppeteer PDF 功能超时

jul*_*ics 5 chromium node.js firebase google-cloud-functions puppeteer

我有一个 Firebase 函数来创建 PDF 文件。最近,由于“Chrome 修订版”而超时?我既不明白错误消息,也不明白出了什么问题。当我在 MacOS 下将其本地部署时,该功能有效。

TimeoutError: Timed out after 30000 ms while trying to connect to the browser! Only Chrome at revision r818858 is guaranteed to work.
    at Timeout.onTimeout (/workspace/node_modules/puppeteer/lib/cjs/puppeteer/node/BrowserRunner.js:204:20)
    at listOnTimeout (internal/timers.js:549:17)
    at processTimers (internal/timers.js:492:7) 
Run Code Online (Sandbox Code Playgroud)

功能:

const puppeteer = require('puppeteer');
const createPDF = async (html, outputPath) => {

    let pdf;

    try {
        const browser = await puppeteer.launch({
            args: ['--no-sandbox']
        });
        const page = await browser.newPage();

        await page.emulateMediaType('screen');

        await page.setContent(html, {
            waitUntil: 'networkidle0'
        });

        pdf = await page.pdf({
           // path: outputPath,
            format: 'A4',
            printBackground: true,
            margin: {
                top: "50px",
                bottom: "50px"
            }
        });

        await browser.close();

    } catch (e) {
        console.error(e);
    }

    return pdf;
};
Run Code Online (Sandbox Code Playgroud)

Emm*_*uel 2

TimeoutError:尝试连接浏览器时 30000 毫秒后超时!

上述错误来自文档中提到的事实:

当您安装 Puppeteer 时,它会下载最新版本的 Chromium

每次执行 Puppeteer 时,您都会在后端运行 Chromium,Puppeteer 将尝试连接到该 Chromium,因此当它无法连接到浏览器时,就会出现此错误。

经过多次测试后,我能够通过headless在启动选项上添加参数来执行云函数,因为文档提到它应该是true默认的,我不太明白为什么手动设置它可以让云函数正确完成。一开始,我尝试设置timeout0禁用由于超时而导致的错误,但似乎这不是必需的,因为仅添加headless它就可以正确完成,但如果您发现超时存在相同的问题,则可以添加它。最后我的代码如下所示:

const createPDF = async (html, outputPath) => {

    let pdf;

    try {
        const browser = await puppeteer.launch({
            args: ['--no-sandbox'],
            headless: true,
            timeout: 0
        });
        const page = await browser.newPage();

        await page.emulateMediaType('screen');

        await page.setContent(html, {
            waitUntil: 'networkidle0'
        });

        pdf = await page.pdf({
           // path: outputPath,
            format: 'A4',
            printBackground: true,
            margin: {
                top: "50px",
                bottom: "50px"
            }
        });

        await browser.close();
        console.log("Download finished"); //Added this to debug that it finishes correctly

    } catch (e) {
        console.error(e);
    }

    return pdf;
};
Run Code Online (Sandbox Code Playgroud)