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

前端 未结 1 405
星月不相逢
星月不相逢 2021-01-14 01:47

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()

相关标签:
1条回答
  • 2021-01-14 02:17

    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');
    
    0 讨论(0)
提交回复
热议问题