How to pass a function in Puppeteers .evaluate() method?

前端 未结 6 1634
后悔当初
后悔当初 2020-12-08 10:06

Whenever I try to pass a function, like this:

var myFunc = function() { console.log(\"lol\"); };

await page.evaluate(func => {
 func();
 return true;
},          


        
6条回答
  •  佛祖请我去吃肉
    2020-12-08 11:01

    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.evaluate():

    var myFunc = function() { console.log("lol"); };
    await page.exposeFunction("myFunc", myFunc);
    
    await page.evaluate(async () => {
       await myFunc();
       return true;
    });
    

    Just remember that page.exposeFunction() will make your function return a Promise, then, you need to use async and await. This happens because your function will not be running inside your browser, but inside your nodejs application.

    1. exposeFunction() does not work after goto()
    2. Why can't I access 'window' in an exposeFunction() function with Puppeteer?
    3. How to use evaluateOnNewDocument and exposeFunction?
    4. exposeFunction remains in memory?
    5. Puppeteer: pass variable in .evaluate()
    6. Puppeteer evaluate function
    7. allow to pass a parameterized funciton as a string to page.evaluate
    8. Functions bound with page.exposeFunction() produce unhandled promise rejections
    9. exposed function queryseldtcor not working in puppeteer
    10. How can I dynamically inject functions to evaluate using Puppeteer?

提交回复
热议问题