Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

headless false - focus always on address bar

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).

like image 956
Tal Ben Shalom Avatar asked Apr 24 '19 08:04

Tal Ben Shalom


1 Answers

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.

like image 142
Thomas Dondorf Avatar answered Sep 21 '22 05:09

Thomas Dondorf