保持相同的 Puppeteer 页面打开 NodeJS

Cur*_*tis 2 javascript node.js puppeteer

我正在开发一个 API,围绕在 Puppeteer 打开的页面上运行一些 JS 开发,但我不想保持打开/关闭并等待页面加载,因为它是一个内容繁重的页面。

是否可以forever start在节点脚本上运行启动页面并使其永远打开,然后在需要在此页面上运行某些 javascript 时调用单独的节点脚本?

我已尝试以下操作,但页面似乎未保持打开状态:

keepopen.js

'use strict';
const puppeteer = require('puppeteer');

(async() => {
    const start = +new Date();
    const browser = await puppeteer.launch({args: ['--no-sandbox']});
    const page = await browser.newPage();
    await page.goto('https://www.bigwebsite.com/', {"waitUntil" : "networkidle0"});
    const end =  +new Date();
    console.log(end - start);
    //await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

runjs.js

'use strict';

const puppeteer = require('puppeteer');

(async() => {
    const start = +new Date();
    const browser = await puppeteer.launch({args: ['--no-sandbox']});
    const page = await browser.targets()[browser.targets().length-1].page();
    const hash = await page.evaluate(() => {
        return runFunction();
    });
    const end =  +new Date();
    console.log(hash);
    console.log(end - start);
    //await browser.close();
})();
Run Code Online (Sandbox Code Playgroud)

我运行以下命令:forever start keepopen.js然后runjs.js但出现错误:

(node:1642) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'evaluate' of null
Run Code Online (Sandbox Code Playgroud)

Tho*_*orf 5

像这样在两个 Node.js 脚本之间共享资源是不可能的。您需要一个使浏览器保持打开状态的服务器。

代码示例

下面是一个使用express库启动服务器的示例。调用/start-browser将启动浏览器并将浏览器和页面对象存储在当前函数之外。这样,第二个函数(在/run访问时调用)可以使用该page对象来运行其中的代码。

const express = require('express');
const app = express();

let browser, page;

app.get('/start-browser', async function (req, res) {
    browser = await puppeteer.launch({args: ['--no-sandbox']});
    page = await browser.newPage();
    res.end('Browser started');
});

app.get('/run', async function (req, res) {
    await page.evaluate(() => {
        // ....
    });
    res.end('Done.'); // You could also return results here
});

app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

请记住,这是一个帮助您入门的最小示例。在现实场景中,您需要捕获错误,并且可能还需要不时重新启动浏览器。