3

Why I can't see my messages at console.log in page.evaluate, page.$, page.$$, page.$eval, page.$$eval And can't to get access to variables out that?

let variable = 0;
const divColors = await page.evaluate(() => {
      const divs = Array.from(document.querySelectorAll('.map-filters div'));
      let text = divs.map((element, index) => {
        console.log(element.textContent)
        variable =1;
        return element.style.color;
      })
      return text;
    })

Why I can't do variable=1 and console.log(element.textContent) in this example?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Andrey Kadnikov
  • 455
  • 5
  • 13

1 Answers1

7

You're using console.log inside of page.evaluate, so it is logging its output to the Chromium browser and not to node output. To see console messages from browser in node's console one needs to subscribe to them after page object is created and before console.log is used in the script:

const page = await browser.newPage();

page.on('console', consoleObj => console.log(consoleObj.text()));

page.evaluate(...);

As for variable variable, there are in fact two of them in your script.

The first one exists in node.js context:

let variable = 0;

And the other one — in web page context:

page.evaluate( () => {
    variable = 1;
})

They are completely different. Think of page.evaluate as of a portal into another world: objects that exist there are only present inside of a javascript runtime on a page open in the web browser that puppeteer is driving. node has its own runtime with its own set of objects.

You may pass data into page.evaluate from node:

let variable = 420;

page.evaluate(variable => {

    // it is now passed here from outside
    console.log(variable) 

}, variable);
Vaviloff
  • 16,282
  • 6
  • 48
  • 56