I'm using puppeteer with headless=false
option, in order to let user type some details in a form, and then read the result, programmatically.
I want the cursor/focus will be on the first input field when the page loaded, but the focus is always on the address bar.
Is there a way to move the cursor/focus inside the page?
I already tried await page.focus(selector)
.
Please find the below example:
const puppeteer = require('puppeteer');
(async () => {
const browser = await puppeteer.launch({ headless: false});
const page = await browser.newPage();
let selector = ".w3-white.w3-padding.notranslate>form>input[name='firstname']";
await page.goto('https://www.w3schools.com/html/html_forms.asp');
await page.waitForSelector(selector,{waitUntil :"networkidle2"});
await page.focus(selector);
await page.type(selector,"aaa");
//await browser.close();
})();
I would like that after the page was loaded, the user will be able to type inside the input field, without having to "move" into the field first (by mouse or tab).
The problem you are experiencing is that you are setting the cursor inside the page, but the focus of the browser itself is still on the address bar.
To make the browser focus the page itself, you need to call page.bringToFront()
which will set the focus of the browser to the tab. You should do it right after creating the page like this:
const page = await browser.newPage();
await page.bringToFront();
In addition, as already pointed out in the other answer, you are giving invalid options to the page.waitForSelector
function. This is simply ignored by puppeteer (and not related to your problem), but should be removed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With