PastaLover
PastaLover

Reputation: 491

Imported functions not working in puppeteer

Importing a long JS function from a different file:

let startTheShow = require('./scraper.js');

And then trying to use that function on the page.

await page.evaluate(() => {

    startTheShow('info','hi','hi');


})

What is the expected result? The imported function will run on the page

What happens instead? "startTheShow is not defined"

Placing the raw script inside the evaluate instead of importing the module to the index, fixes the issue. Unfortunately this option makes a lot of mess in the index file. Any idea why I can't use this imported function?

Upvotes: 1

Views: 1204

Answers (1)

mbit
mbit

Reputation: 3013

From the docs:

pageFunction <function|string> Function to be evaluated in the page context

evaluate(() => startTheShow()) means there should be a startTheShow function in the page context which I'd assume there isn't any and the page context has no idea what startTheShow is. You should either pass the string version of ./scraper.js, or the startTheShow function to evaluate.

Example of passing strings from docs:

console.log(await page.evaluate('1 + 2')); // prints "3"

Upvotes: 2

Related Questions