Some websites have focus events, meaning elements appear only when focused on a particular part. Playwright can handle this focused event with the focus() command.
This command ensures that the element is within focus during the test.
Syntax:
page.locator('class').focus();
The timeout default is 30secs, and 0 can be passed to skip timeout.
Example:
const {test, expect} = require('@playwright/test');
test('Focus', async ({browser})=>
{
const context = await browser.newContext();
const page = await context.newPage();
await page.goto("http://autopract.com/selenium/focus1/");
await page.pause();
await page.locator('//input[@type="text"]').focus();
});
- The focus was made on the input field.

- The input field is highlighted and focused on with its respective element name.