I’m trying to use Google Puppeteer to run a function inside the evaluate() method. I’m passing the function as an argument, but I keep getting an error saying ‘func is not a function’. I’m not sure what I’m doing wrong.
Here’s what my code looks like:
let myFunction = () => {
console.log('Hello from myFunction');
};
try {
let result = await page.evaluate((myFunction) => {
myFunction(); // This line throws the error
}, myFunction);
} catch (error) {
console.error('Error:', error);
}
I’m using Puppeteer version 10.2 on Windows 10 with Node 8.2.1. Any ideas on how to fix this? I thought passing the function as an argument would work, but it doesn’t seem to be recognized inside evaluate(). What am I missing here?
I’ve run into this problem too, and it can be frustrating. One solution that worked for me was using Puppeteer’s exposeFunction() method instead of trying to pass the function directly to evaluate().
Here’s how you could modify your code:
await page.exposeFunction('myFunction', () => {
console.log('Hello from myFunction');
});
try {
let result = await page.evaluate(() => {
return myFunction();
});
} catch (error) {
console.error('Error:', error);
}
This approach ‘exposes’ your function to the page context, making it available within evaluate(). It’s cleaner and avoids the serialization issues. Just remember to call exposeFunction() before you use the function in evaluate(). This method has worked reliably for me across different Puppeteer versions.
I’ve encountered this issue before, and it’s a common pitfall when working with Puppeteer’s evaluate() method. The problem lies in how functions are serialized when passed to the browser context.
To resolve this, you need to stringify your function and then parse it inside the evaluate() method. Here’s a modified version of your code that should work:
let myFunctionString = myFunction.toString();
try {
let result = await page.evaluate((fnString) => {
const myFunction = new Function('return ' + fnString)();
myFunction();
}, myFunctionString);
} catch (error) {
console.error('Error:', error);
}
This approach ensures that your function is properly reconstructed in the browser context. Remember, Puppeteer runs in a separate JavaScript environment, so direct function passing doesn’t work as expected. By stringifying and then reconstructing the function, you bridge this gap effectively.
hey pete, i’ve had similar probs. try using page.evaluate(myFunction) instead. it worked 4 me. also, make sure ur function is defined before evaluate(). if that dont work, try updating puppeteer. older versions can be buggy with function passing. good luck!