Tal Ben Shalom
Tal Ben Shalom

Reputation: 123

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

Upvotes: 5

Views: 2564

Answers (3)

Anselmo Park
Anselmo Park

Reputation: 1011

I invoked mouse.click() function to move my cursor from address bar to the page.

await page.mouse.click(0, 0);

The way to use browser.newPage() works as I expect, but that case uses more memory. So I uses click() function.

Upvotes: 0

Thomas Dondorf
Thomas Dondorf

Reputation: 25270

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.

Upvotes: 10

Vaviloff
Vaviloff

Reputation: 16856

There is one little thing that needs to be corrected, waitUntil is an option for page.goto:

await page.goto('https://www.w3schools.com/html/html_forms.asp',{waitUntil :"networkidle2"});

With this in place your example works fine with puppeteer 1.11 and node 8.6

Upvotes: 0

Related Questions