How to define variables in a callback without parameters

245 Views Asked by At

In Puppeteer's evaluate function, I can access variables that seem to be predefined, but only in the scope of the function:

// Excerpt
page.evaluate(() => {
  alert("Hello world!!");
});

There aren't any parameters that get passed into the function either...

Whereas if it wasn't inside the evaluate function, I can't access all the variables. What's even more interesting is that the code inside evaluate has nothing to do with the code outside of it.

// Excerpt
page.evaluate(() => {
  console.log("Hello world!!");
});

The above code does not print inside the Node.js console, but rather in the Chromium browser.

How does this work and how can I do it too?

1

There are 1 best solutions below

0
Andrew Antsiferov On BEST ANSWER

Puppeteer wraps your function using Function constructor and Function#toString and then evaluate it in the custom context, like this:

let functionText = evaluateFunc.toString();

let newFunc = new Function(`
function alert() {...}

(${functionText})
`);

newFunc();

Therefore variables, functions, etc. outside of the function isn't accessible.

If you want to pass arguments inside evaluate function, see How can I pass variable into an evaluate function?