人偶网络:"Puppeteer is not a constructor"

puppeteer-web: "Puppeteer is not a constructor"

我正在尝试遵循 instructions here to bundle puppeteer,目的是将其包含在 chrome 扩展中,作为在浏览器 window 中编写脚本操作的一种 hacky 方式(具体来说,将页面打印为 PDF,据我所知,仅使用 Chrome 扩展名 API 这是不可能的)。

根据上面 link 中的 README,我设置了我的 Chrome 扩展如下:

background.html

<script src="./puppeteer/utils/browser/puppeteer-web.js"></script>
<script src="background.js"></script>

background.js

const puppeteer = require("puppeteer");

引发错误 puppeteer/utils/browser/puppeteer-web.js:10877 (anonymous function) Uncaught TypeError: Puppeteer is not a constructor

我在这里错过了什么?

Chrome版本:版本69.0.3497.100

节点版本:7.4.0

Chrome 扩展不允许 unsafe-eval,这就是 puppeteer 不处理 chrome 扩展的原因。在 manifest.json.

上设置以下内容
"content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"

使用以下代码进行测试,

const puppeteer = require('puppeteer');

async function getTitle() {
  const browser = await puppeteer.connect({
    browserWSEndpoint: 'ws://127.0.0.1:9222/devtools/browser/9f0a2240-2cb7-4efa-ac3c-8ef883d36d12',
  });
  const page = await browser.newPage();
  await page.goto('http://example.com');
  const title = await page.title();
  await page.close();
  await browser.disconnect();
  return title;
}

getTitle().then(console.log);

结果:

我是怎么找到它的:

如果我直接 运行 代码或将其放在页面上,则代码 运行 是完美的,但不能仅从 chrome 扩展程序运行。

这里的 asyncawait 检查帮助我找到了罪魁祸首。

let asyncawait = true;
try {
  new Function('async function test(){await 1}');
} catch (error) {
  asyncawait = false;
}