This document provides a comprehensive guide to automating common UI elements and browser behaviors using Playwright with TypeScript.
await page.getByText('Submit').click();
await page.getByRole('button', { name: 'Submit' }).click();
await page.getByLabel('Username').fill('anbu');await page.getByLabel('Remember me').check();
await page.getByLabel('Remember me').uncheck();await page.getByLabel('Male').check();await page.selectOption('#country', 'India');
await page.selectOption('#country', { label: 'India' });await page.selectOption('#fruits', ['apple', 'banana']);const options = await page.locator('#country option').allTextContents();
console.log(options);page.once('dialog', async dialog => {
console.log(dialog.message());
await dialog.accept();
});
await page.click('#alertBtn');page.once('dialog', async dialog => {
await dialog.accept();
});
await page.click('#confirmBtn');const [newPage] = await Promise.all([
context.waitForEvent('page'),
page.click('a[target="_blank"]'),
]);
await newPage.waitForLoadState();const frame = page.frame({ name: 'iframeName' });
await frame?.click('#insideFrameBtn');await page.locator('#target').scrollIntoViewIfNeeded();await page.evaluate(() => window.scrollBy(0, 500));import data from './data.json';
console.log(data.username);import * as fs from 'fs';
import * as csv from 'csv-parse/sync';
const fileContent = fs.readFileSync('data.csv');
const records = csv.parse(fileContent, columns:true,skip_empty_lines:true,skip_records_with_empty_values:true);
console.log(records);// .env
// USERNAME=admin
import * as dotenv from 'dotenv';
dotenv.config();
console.log(process.env.USERNAME);await page.fill('#searchBox', 'Playwright');
await page.press('#searchBox', 'Enter');const rows = page.locator('table tr');
const count = await rows.count();
for (let i = 0; i < count; i++) {
console.log(await rows.nth(i).textContent());
}await page.fill('#datepicker', '2025-07-15');
await page.click('#datepicker');
await page.click('text=15');await page.click('text=Settings');import { expect } from '@playwright/test';
expect(await page.textContent('h1')).toBe('Welcome');
expect(await page.isVisible('text=Logout')).toBeTruthy();Playwright automatically waits for elements to be visible and actionable.
await page.click('#submit');// LoginPage.ts
export class LoginPage {
constructor(private page: Page) {}
async login(username: string, password: string) {
await this.page.fill('#user', username);
await this.page.fill('#pass', password);
await this.page.click('button[type="submit"]');
}
}
// test.ts
const loginPage = new LoginPage(page);
await loginPage.login('admin', 'password');await page.hover('#tooltipBtn');
const tooltipText = await page.locator('.tooltip').textContent();test.each([
['user1', 'pass1'],
['user2', 'pass2'],
])('Login with %s', async ({ page }, username, password) => {
await page.fill('#user', username);
await page.fill('#pass', password);
await page.click('#login');
});