Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: puppeteer focus() function

I am trying to login on the site using puppeteer and then some other stuff after I am logged in. Connection to site was successful, but I have problem with function focus(). It needs a selector as an parameter, but after inserting one, it show an error (selector is good, because I ran document.querySelector("input.login-field") in console of the site and returned this: <input class="login-field" type="text" inputmode="email" autocapitalize="none" name="m" placeholder="Email or username" value="">). What's the problem?

Here's my code:

const puppeteer = require('puppeteer');

(async () => {
const browser = await puppeteer.launch({headless: false, slowMo: 25});

const page = await browser.newPage();
await page.goto("site");
await page.focus("input.login-field");
await page.keyboard.type("information");
await browser.close();

})();
like image 998
vlado_sl Avatar asked Jun 09 '26 00:06

vlado_sl


1 Answers

If you're sure that the selector is good and it's working in the console in headful mode, try to wait until the page scripts are downloaded, started, and the needed element appeared in the DOM:

await page.goto("site");
await page.waitForSelector('input.login-field'); // <-- wait until it exists
await page.focus("input.login-field");
like image 168
Vaviloff Avatar answered Jun 10 '26 12:06

Vaviloff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!