Im new to Puppeteer. I'm using puppeteer to try to get canvas and run the toDataUrl() method. When I console log what im hoping is the canvas it seems to be getting the correct dom element
_remoteObject: {
type: 'object',
subtype: 'node',
className: 'HTMLCanvasElement',
description: 'canvas',
objectId: '-861002856273230536.3.2'
},
but any attempt to run a function using $eval (not sure that is correct?) fails.
const dataUrl = await page.$eval('canvas', (cnv) => {
return cnv.toDataUrl()
});
Could someone check my code please see what is going on?
const chromium = require('chrome-aws-lambda');
const puppeteer = require('puppeteer-core');
exports.handler = async function (event, context) {
const browser = await puppeteer.launch({
args: chromium.launch,
executablePath:
process.env.CHROME_EXECUTABLE_PATH ||
(await chromium.executablePath),
headless: true,
});
const page = await browser.newPage();
await page.goto('https://qifi.org/');
await page.focus('#ssid');
await page.keyboard.type('homebase');
await page.focus('#key');
await page.keyboard.type('tubulargagy');
await page.click('#generate');
const dataUrl = await page.$$eval('#qrcode + canvas', (cnv) => {
return cnv.map((canvas) => {
return {
data: canvas.toDataUrl(),
};
});
});
// const data = await page.$('canvas');
console.log('data', dataUrl);
// const title = await page.title();
await browser.close();
return {
statusCode: 200,
body: JSON.stringify({
status: 'Ok',
page: {
data: dataUrl,
},
}),
};
};
#qrcode + canvas is an incorrect selector. The <canvas> is the child of the #qrcode element, not the next sibling. You can use #qrcode canvas to select the desired element.
There's only one QR on the page so $$ seems like it should be $, although this shouldn't cause a failure. The code looks OK other than the selector mishap.
Here's a minimal, runnable example:
const puppeteer = require("puppeteer"); // ^13.5.1
let browser;
(async () => {
browser = await puppeteer.launch({headless: true});
const [page] = await browser.pages();
await page.goto("https://qifi.org/");
await page.type("#ssid", "homebase");
await page.type("#key", "tubulargagy");
await page.click("#generate");
console.log(await page.$eval("#qrcode canvas", el => el.toDataURL()));
})()
.catch(err => console.error(err))
.finally(() => browser?.close())
;