将重击传递给伪造者的$ .eval [英] Passing a thunk to puppeteer's $.eval
问题描述
函数 setValue
接收一个值并返回一个函数.在第二个函数中,我尝试控制台记录 value
的值,但得到
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
下面的代码.可以在 try-puppeteer 上进行测试,只需复制并粘贴我的代码并删除要求
语句.
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();
})();
推荐答案
对于在Node.js中执行并在浏览器中评估代码(量角器,TestCafe,噩梦等)的任何库,这都是一个常见问题.函数被字符串化并作为字符串传递给浏览器.(input)=>的原始范围{console.log(value)}
丢失,并且 value
应该是未定义的全局变量.
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.
作为文档提及,应该将其他参数传递给 $ eval
.
As the documentation mentions, additional arguments are supposed to be passed to $eval
.
应该是:
await page.$eval('.selector', (el, value) => { console.log(value) }, USERNAME);
console.log
可以使用,但显然不会在Node控制台中显示任何内容,因为它是指浏览器控制台.
console.log
will work but obviously, won't display anything in Node console, because it refers to browser console.
这篇关于将重击传递给伪造者的$ .eval的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!