1

Considering the following code:

const puppeteer = require('puppeteer');

const run = async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://www.facebook.com/pg/fotosdacurva/photos/?tab=albums', { waitUntil: 'networkidle' });

    const data = await page.evaluate(() => {
        console.log("ola");

        const tds = Array.from(document.querySelectorAll('#content_container a'))
        return tds.map(td => td.textContent)
    });

    //console.log(data);
    await page.screenshot({ path: 'example.png' });

    await browser.close();
};

run();

console.log inside page.evaluate() function is not working and I cant figure out why? I think it might be related to async behavior. The function is being executed as the "data" variable is being set.

Thank you.

brpaz
  • 3,618
  • 9
  • 48
  • 75

3 Answers3

3

If you want to listen to console of the browser, you can simply use the console event of puppeteer. For example, check this example from their docs,

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

What it will do is, everytime there is a console message, a event will be triggered and it'll catch that event, and print the messages for you on your nodeJS console.

Just remember that if you print a dom element or array, the original browser console will print it properly however in nodeJS, you will probably see [object Object] or similar texts instead.

Md. Abu Taher
  • 17,395
  • 5
  • 49
  • 73
  • `msg.args()` is a function: https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#class-consolemessage – davesnx Nov 12 '19 at 22:12
2

You can listen for console events on the page and then write to your own console:

const page = await browser.newPage();
page.on('console', console.log);

It's not exactly the same as console.log() but it is helpful. It will give you output that looks like this:

ConsoleMessage {
  type: 'log',
  text: 'ola',
  args:
   [ JSHandle {
       _context: [Object],
       _client: [Object],
       _remoteObject: [Object],
       _disposed: false } ] }

https://github.com/GoogleChrome/puppeteer/blob/master/docs/api.md#event-console

Mark
  • 90,562
  • 7
  • 108
  • 148
0

In 2021 you need to use async await to get args from JSHandle object. If you make Promise.all(args) and next time tries to evaluate on executionContext of JSHandle it will show the object of consoleMessage.

In this case, check my full answer there https://stackoverflow.com/a/66801550/9026103

Igor Kurkov
  • 4,318
  • 2
  • 30
  • 31