Puppeteer log inside page.evaluate

A lot of the answers provided previously no longer work today. Also one thing that can be very annoying on some pages, is the "warning" messages which pollutes the output. One way to fix that is to filter for the type of the message. The following code helps reduce the noise and works with current versions of Puppeteer:

const browser = await puppeteer.launch();
const page = await browser.newPage();
page.on('console', consoleMessageObject => function (consoleMessageObject) {
    if (consoleMessageObject._type !== 'warning') {
        console.debug(consoleMessageObject._text)
    }
});

await page.goto('https://google.com');
const result = await page.evaluate(() => {
    console.log('Browser scope.');
    return 'Normal scope.';
});
console.log(result)

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 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 ]