Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a thunk to puppeteer's $.eval

The function setValue receives a value and returns a function. Inside the second function I'm trying to console log the value of value but I get

Error: Evaluation failed: ReferenceError: value is not defined

My code bellow. It can be tested on try-puppeteer, just copy and paste my code and remove the require statement.

const puppeteer = require('puppeteer');

(async () => {
  const USERNAME = 'helloworld';
  const setValue = (value) => (input) => { console.log(value) };

  const browser = await puppeteer.launch();
  const page = await browser.newPage();

  await page.goto('http://example.com');
  await page.$eval('.selector', setValue(USERNAME));

  await browser.close();
})();
like image 727
André Herculano Avatar asked Jun 02 '18 14:06

André Herculano


1 Answers

This is a problem that is common to any library that is executed in Node.js and evaluates code in browser (Protractor, TestCafe, Nightmare, etc). A function is stringified and passed to a browser as a string. Original scope of (input) => { console.log(value) } is lost, and value is expected to be a global, which is undefined.

As the documentation mentions, additional arguments are supposed to be passed to $eval.

It should be:

await page.$eval('.selector', (el, value) => { console.log(value) }, USERNAME);

console.log will work but obviously, won't display anything in Node console, because it refers to browser console.

like image 172
Estus Flask Avatar answered Oct 19 '22 17:10

Estus Flask