Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function is not defined when called in page.evaluate() [duplicate]

When I call a function normally, it works, but when I call it in page.evaluate(), the function is not defined. Here's a demo:

const puppeteer = require('puppeteer');
(async () => {
    const browser = await puppeteer.launch()
    const page = await browser.newPage()

    page.on('console', msg => console.log(msg.text())) // so console.log() works in page.evaluate()
    const test = () => console.log('works')
    await test() // it runs

    await page.evaluate(() => test()) // ReferenceError: test is not defined
})()
like image 948
Alex Avatar asked Apr 12 '26 19:04

Alex


1 Answers

The page context that Puppeteer spawns (in its virtual browser) is not the same as the Node context that you write the implementation code in. When page.evaluate is passed a function, that function is serialized, then passed to the browser, and deserialized and evaluated (in that different context). Here, the page context doesn't have access to test, because that variable is only defined in Node, not on the page.

You can put a function into the page if you want, though, by defining it in the page context.

await page.evaluate(() => {
  window.test = () => console.log('works');
});
await page.evaluate(() => test())

or

await page.evaluate(() => {
  const test = () => console.log('works');
  test();
});
like image 155
CertainPerformance Avatar answered Apr 15 '26 08:04

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!