Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

google chrome extension - puppeteer-web: "Puppeteer is not a constructor"

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).

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");

Throws the error puppeteer/utils/browser/puppeteer-web.js:10877 (anonymous function) Uncaught TypeError: Puppeteer is not a constructor.

What am I missing here?

Chrome version: Version 69.0.3497.100

Node version: 7.4.0

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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'"

Tested with following code,

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);

Result:

How did I find it:

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

The asyncawait check here helped me find the culprit.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...