Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to pass a function to Puppeteer's page.evaluate()

I am using Puppeteer to parse a webpage and can't find a definitive answer to my question.

I am trying to pass a function as an argument to page.evaluate() An object is OK to pass but can't seem to pass a function. Here's a contrived example:

const obj = {
 thing: 'thing1',
};

const myfunction = () => {
 return `great ${stuff}`;
};

await page.evaluate((obj, function)=>{
 const thing = myfunction;
},(obj, function));

Is it possible to pass a function as an argument to puppeteers page.evaluate()?

like image 462
Falko Avatar asked Sep 21 '19 12:09

Falko


People also ask

How do you pass a function in page to evaluate?

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

No, you cannot pass functions like that. The passed data needs to be serializable via JSON.stringify, which is not possible for functions.

Alternative: Expose the function

To use a function from your Node.js environment inside the page, you need to expose it via page.exposeFunction. When called the function is executed inside your Node.js environment

await page.exposeFunction('myfunction', text => `great ${text}`);
await page.evaluate(async (object) => {
  return await window.myfunction(object); // 'great example'
}, 'example');

Alternative: Define the function inside page.evaluate

To use a function inside the page context, you can either define it inside of the context. This way, the function does not have access to your Node.js variables.

await page.evaluate((obj) => {
  const myfunction = (stuff) => `great ${stuff}`;
  return myfunction(obj); // 'great example'
}, 'example');
like image 174
Thomas Dondorf Avatar answered Oct 17 '22 04:10

Thomas Dondorf