Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loading and using a JS module in puppeteer

I'm building an npm package for internal use. One of it's functions is DOM parsing so I need to load it inside a browser. I would like to use puppeteer for testing.

In the docs, I've found page.injectFile() to use for local JS files. However, my file is a module (file I'm injecting is already transpiled to regular JavaScript) and I don't know what to do after injecting it into a puppeteer's browser page.

My code so far:

const puppeteer = require('puppeteer');

(async () => {
  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  page.injectFile('../build/MyModule')
    .then(result => console.log(result))
    .then(error => console.log(error));
})();

I get an error, ReferenceError: require is not defined because I'm using require in MyModule. Can I even use JS modules like this in puppeteer and if yes, what's the corret way to get an instance of MyModule and use it?

like image 735
dnmh Avatar asked Oct 04 '17 13:10

dnmh


1 Answers

I really doubt puppeteer can achieve this since it is just a nodejs driver for headless chrome.

If you need to use custom module with cmd require(...) inside, you would probably need to use module bundler like webpack to generate a bundle file with all the dependencies, then inject into puppeteer page.

Just my 2 cents.

like image 131
LeOn - Han Li Avatar answered Oct 17 '22 13:10

LeOn - Han Li