Whenever I try to pass a function, like this:
var myFunc = function() { console.log(\"lol\"); };
await page.evaluate(func => {
func();
return true;
},
Similar problems have been discussed in a puppeteer issue.
There are several way to deal with your problem. First rule is to keep it simple.
This is the fastest way to do things, you can just pass the function and execute it.
await page.evaluate(() => {
var myFunc = function(element) { element.innerHTML = "baz" };
var foo = document.querySelector('.bar');
myFunc(foo);
return true;
});
You can expose the function beforehand using a page.evaluate, or a page.addScriptTag
// add it manually and expose to window
await page.evaluate(() => {
window.myFunc = function(element) { element.innerHTML = "baz" };
});
// add some scripts
await page.addScriptTag({path: "myFunc.js"});
// Now I can evaluate as many times as I want
await page.evaluate(() => {
var foo = document.querySelector('.bar');
myFunc(foo);
return true;
});
You can pass an element handle to .evaluate and make changes as you seem fit.
const bodyHandle = await page.$('body');
const html = await page.evaluate(body => body.innerHTML, bodyHandle);
You can target one element and make changes as you want.
const html = await page.$eval('.awesomeSelector', e => {
e.outerHTML = "whatever"
});
The trick is to read the docs and keep it simple.