Skip to content
Advertisement

Puppeteer Cannot read property getElementById of undefined

I’m trying to pass a value to the browser created by the puppeteer, but this error appears:

Cannot read property ‘getElementById’ of undefined

async function start() {
    const browser = await puppeteer.launch({
        headless : false
    });
    const page = await browser.newPage();
    await page.goto('https://www.google.com/recaptcha/api2/demo?invisible=true');

    await page.document.getElementById("g-recaptcha-response").innerHTML === response.text
    
    await Promise.all([
        page.click('#recaptcha-demo-submit'),
    ]);
}

The error is in this line:

await page.document.getElementById("g-recaptcha-response").innerHTML === response.text

what am I doing wrong?

Thanks.

Advertisement

Answer

You can only use getElementById in the page context. Use page.evaluate, eg:

const html = await page.evaluate(() => {
    return document.getElementById("g-recaptcha-response").innerHTML;
});
console.log(html);

That’ll take the the innerHTML of that element, send it back to Puppeteer, and log it in Node.

If you want to pass something to the page, you’ll have to pass it to page.evaluate, eg

await page.evaluate((arg) => {
    return document.getElementById("g-recaptcha-response").value = arg;
}, '123');

That’ll set the value of the textarea to 123.

Advertisement