Search code examples
javascriptnode.jspuppeteer

Puppeteer log inside page.evaluate


How can I console.log something inside the page.evaluate, passing it to node and using it during the evaluation of the page?

I actually want to log the progress of the page.evaluate to the console and show some results to the user.


Solution

  • Update for puppeteer 12, adapted from the current documentation:

    page.on('console', async (msg) => {
      const msgArgs = msg.args();
      for (let i = 0; i < msgArgs.length; ++i) {
        console.log(await msgArgs[i].jsonValue());
      }
    });
    
    await page.evaluate(() => console.log('hello', 5));
    await page.evaluate(() => console.log({ foo: 'bar' }));
    await page.evaluate(() => console.log([1, 2, 3, 4, 5]));
    

    Shows the following results:

    hello  
    5  
    { foo: 'bar' }  
    [ 1, 2, 3, 4, 5 ]