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 {}.
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();
})