Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

331
Views
Puppeteer - How to pass a function inside evaluate method that can use htmlElements?

I have a nodeJS discord bot that generate a gif and return it to client. But I want to use puppeteer in order to generate it faster using my gpu. In order to do that, I try to pass the canvas generated in the evaluate function of puppeteer, but inside my function, the canvas doesn't exist anymore.

How to pass the function and have access to the canvas in html ?

Code:

async useCanvas() {
    let result = null;

    if (browser === null) await this.openBrowser();

    const ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36";
    const page = await browser.newPage();
    try {
        await page.setExtraHTTPHeaders({'Accept-Language': 'en-US,en;q=0.9'});
        await page.setUserAgent(ua);
        await page.setJavaScriptEnabled(true);

        await page.goto("http://perdu.com");
        await page.waitForSelector('body');
        await page.exposeFunction("func", async (canvas) => console.log(canvas))

        result = await page.evaluate(async () => {
            const canvas = document.createElement("canvas");
            document.body.appendChild(canvas);
            await func(canvas);
        });
    } catch (e) {
        console.log(e);
    }

    await page.close();

    return result;
}

The console log display {}.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The only way I know how to make this work is to pass in a path to a file that contains your function to puppeteer. The way to do this is the following:

Set up a file with your evaluate function:

// evaluate.js
window.yourCustomFunction = () => {
  // your logic here
}

Add a script tag to your page and calling the function within evaluate:

// page.js
await page.addScriptTag({ path: 'path/to/your/script/' });

const result = await page.evaluate(() => {
   return window.yourCustomFunction();
})
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!