puppeteer-web:"Puppeteer不是构造函数" [英] puppeteer-web: "Puppeteer is not a constructor"

查看:203
本文介绍了puppeteer-web:"Puppeteer不是构造函数"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试遵循此处将木偶戏包捆绑在一起的说明,目的是将其包含在chrome扩展程序中,作为在浏览器窗口中进行脚本操作的一种令人讨厌的方式(具体来说,就是将页面打印为PDF,据我所知,这仅凭Chrome Extension API是不可能实现的).

I'm trying to follow the instructions here to bundle puppeteer, with the intention of including it in a chrome extension as a hacky way of scripting operations in the browser window (specifically, printing a page to PDF, which is surprisingly impossible with just the Chrome Extension API as far as I can tell).

按照上面链接中的README,我已经按照以下步骤设置了Chrome扩展程序:

As per the README in the link above, I've set up my Chrome extension as follows:

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版

Chrome version: Version 69.0.3497.100

节点版本:7.4.0

Node version: 7.4.0

推荐答案

Chrome扩展程序不允许unsafe-eval,这就是puppeteer无法在chrome扩展程序上工作的原因.在manifest.json上设置以下内容.

Chrome extensions does not allow unsafe-eval, that is reason why puppeteer is not working on chrome extension. Set the following on 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扩展程序.

The code is running perfectly if I run it directly or put it on a page, but wasn't working from chrome extension only.

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

The asyncawait check here helped me find the culprit.

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

这篇关于puppeteer-web:"Puppeteer不是构造函数"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆