Passing a thunk to puppeteer's $.eval

时光怂恿深爱的人放手 提交于 2021-02-19 02:39:29

问题


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();
})();

回答1:


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.



来源:https://stackoverflow.com/questions/50657830/passing-a-thunk-to-puppeteers-eval

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!