问题
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