7

Can someone explain why this code isn't working. I have a console log before I run page.evaluate() which logs what I expect, but the console log inside page.evaluate never runs.

const puppeteer = require('puppeteer');

(async () => {
  try {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://www.example.com');
    page.on('response', async response => {
      const url = response.url();
      if (url.includes('something')) {
        console.log('this code runs');
        await page.evaluate(() => {
          console.log("this code doesn't run");
        });
      }
    });    
  } catch (err) {
    console.log(err);
  }
})();

Nic Stelter
  • 641
  • 2
  • 7
  • 19

4 Answers4

9

Console log doesn't work in page.evaluate()

https://github.com/GoogleChrome/puppeteer/issues/1944

Nic Stelter
  • 641
  • 2
  • 7
  • 19
9

The code inside page.evaluate is run in the browser context, so the console.log works, but inside the Chrome console and not the Puppeteer one.

To display the logs of the Chrome context inside the Puppeteer console, you can set dumpio to true in the arguments when launching a browser using Puppeteer:

const browser = await puppeteer.launch({
    dumpio: true
})
Triphael
  • 101
  • 1
  • 4
6

Try to use this code for display console.log from evaluate

page.on('console', msg => {
  for (let i = 0; i < msg.args().length; ++i)
    console.log(`${i}: ${msg.args()[i]}`);
});
page.evaluate(() => console.log('hello', 5, {foo: 'bar'}));

https://pptr.dev/#?product=Puppeteer&version=v1.20.0&show=api-event-console

dmowski
  • 106
  • 1
  • 3
2

Console.log works but in the browser context. I'm guessing here that you are trying to see the log in the CLI. If you want to see the log set headless to false and then see the log in the browser console.