Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

333
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda