Puppeteer log inside page.evaluate

Viewed 28492

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.

12 Answers

The easiest way to get it to work exactly like you'd expect

const page = await browser.newPage();
page.on('console', (log) => console[log._type](log._text));

Update for version 1.15.x and above - Jan 2020

In the latest version args has been replaced with _args.

So when you are using page.evaluate() or page.evaluateHandle() and you want to get the console.log() text from the browser context back to node, use the following code and make sure to set the listener before any console.log() calls:

Code:

    // First we register our listener.
    page.on('console', msg => {
    for (let i = 0; i < msg._args.length; ++i)
        console.log(`${i}: ${msg._args[i]}`);
    });

    // Then we call the log.
    page.evaluate(() => console.log('Hello World'));

Explanation:

You can't see the console.log() text in your node console or set node breakpoints inside page.evaluate() or page.evaluateHandle(), because the code inside those functions is running only in the browser context. If you would launch puppeteer in none headless mode you would see the console.log() message showing in the browser.

Sidenote:

In most cases you don't really need to log inside the browser context and you can do the same work in the 'Console' tab of your browser 'Developer tools' section.

I like @Vaviloff's answer, but you will log the whole ConsoleMessage object when you may just want the text. Thus, I personally use the below:

const EOL = require('os').EOL;
const _page = await browser.newPage();

_page.on('console', _fCleanLog);

function _fCleanLog(ConsoleMessage) {
    console.log(ConsoleMessage.text + EOL);
}
const page = await browser.newPage();
page.on("console", msg => {
for (let i = 0; i < msg.args().length; ++i)
console.log(`${i}: ${msg.args()[i]}`);
});

try this one if none of the above works. shows no error logs but only the log I created.

I am trying to share my workaround if it helps anybody in future.

  1. Print all the console outputs to stdout including warning, error, log:

    page = await browser.newPage();
    page.on("console", (consoleObj) => console.log(consoleObj.text()));
    
  2. Print everything except warning:

    page.on('console', consoleObj => {
        if (consoleObj.type() !== 'warning') {
            console.log(consoleObj.text());
        }
    })
    
  3. Print only logs (Ex: console.logs).

    page.on('console', consoleObj => {
        if (consoleObj.type() === 'log') {
            console.log(consoleObj.text());
        }
    })
    

The last one helped me more to debug efficiently.

I share this solution for future readers who would more like to know how to get the returned value of an evaluation instead.

const element = await page.$("a selector");
const text = await page.evaluate(element => element.textContent);
await page.evaluate(()=>{
      var string = 'I want to print this';
      return string;
}).then(console.log);
        

Today in 2021 with puppeteer 8.x.x the main answer not show us the full description of the console object. For example, you can't get all the error stack trace text, message.text() contain just a few information about the js errors.

My best way to do this in another comment here https://stackoverflow.com/a/66801550/9026103

Related