Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I pass a variable to a callback in puppeteer's $eval?

The following code doesn't work due to a ReferenceError when trying to access uid. I understand that the eval code is running inside the browser's context and thus doesn't have access to this variable, but I don't know how to pass the variable's value regardless:

var uid = '[email protected]';
await page.$eval('#uid', el => el.value = uid);
like image 778
ivarec Avatar asked Apr 15 '18 19:04

ivarec


People also ask

What is Page $$ eval?

$$eval() method. This method runs Array. from(document. querySelectorAll(selector)) within the page and passes the result as the first argument to the pageFunction .

How do you evaluate a function to pass a page?

You cannot pass a function directly into page. evaluate() , but you can call another special method ( page. exposeFunction ), which expose your function as a global function (also available in as an attribute of your page window object), so you can call it when you are inside page.

How do you evaluate a page in a puppeteer?

evaluate() method. Evaluates a function in the page's context and returns the result. If the function passed to page. evaluteHandle returns a Promise, the function will wait for the promise to resolve and return its value.


1 Answers

The third argument of page.$eval() passes in arguments, so you would do:

await page.$eval('#uid', (el, _uid) => el.value = _uid, uid);

page.$eval() docs as of Puppeteer 1.3.0:

page.$eval(selector, pageFunction[, ...args])

  • selector <string> A selector to query page for
  • pageFunction <function> Function to be evaluated in browser context
  • ...args <...Serializable|JSHandle> Arguments to pass to pageFunction
  • returns: <Promise<Serializable>> Promise which resolves to the return value of pageFunction
like image 165
tony19 Avatar answered Nov 29 '22 06:11

tony19