Saturday, November 21, 2026

Playwright TypeScript - Page, Locator and Other Important Classes

Playwright TypeScript - Page, Locator and Other Important Classes

Playwright with TypeScript provides powerful classes and interfaces for browser automation and API testing. Understanding Page, Locator, Browser, BrowserContext, Frame, Keyboard, Mouse, and other important classes helps you build a reusable and maintainable automation framework.

Playwright TypeScript - Page, Locator and Other Important Classes


1. Important Playwright Classes and Interfaces

Playwright provides several classes and interfaces to control browsers, interact with web elements, manage browser sessions, and perform API testing.

Class or Interface Description
BrowserRepresents a browser instance such as Chromium, Firefox, or WebKit.
BrowserContextRepresents an isolated browser session.
PageRepresents a single browser tab or page.
LocatorRepresents an element or group of elements on a page.
FrameRepresents an iframe inside a webpage.
FrameLocatorUsed to locate and interact with elements inside an iframe.
BrowserTypeProvides methods to launch browser instances.
APIRequestContextUsed for making API requests.
APIResponseRepresents an API response.
RequestRepresents an HTTP request.
ResponseRepresents an HTTP response.
DownloadRepresents a downloaded file.
DialogRepresents JavaScript dialogs such as alerts and confirms.
KeyboardProvides keyboard interaction methods.
MouseProvides mouse interaction methods.
TouchscreenProvides touchscreen interaction methods.
JSHandleRepresents a JavaScript object in the browser context.

2. Page Class

The Page class represents a browser tab. It provides methods to navigate, interact with elements, take screenshots, and handle browser events.

Import Page

import { Page } from '@playwright/test';

Page Example

import { test, expect } from '@playwright/test';

test('Page class example', async ({ page }) => {
    await page.goto('https://example.com');

    const title: string = await page.title();
    console.log(title);

    const url: string = page.url();
    console.log(url);

    await page.reload();
    await page.goBack();
    await page.goForward();

    await page.screenshot({
        path: 'homepage.png'
    });

    await expect(page).toHaveTitle(/Example/);
});

Important Page Methods

MethodDescription
page.goto(url)Navigate to a URL.
page.url()Get current URL.
page.title()Get page title.
page.reload()Reload page.
page.goBack()Navigate backward.
page.goForward()Navigate forward.
page.screenshot()Take screenshot.
page.locator()Locate elements.
page.getByRole()Locate by accessible role.
page.getByText()Locate by text.
page.getByLabel()Locate by label.
page.getByPlaceholder()Locate by placeholder.
page.waitForLoadState()Wait for page load state.
page.waitForURL()Wait for URL change.
page.evaluate()Execute JavaScript in the page.
page.close()Close page.

3. Locator Class

The Locator class is used to find and interact with HTML elements. Locators are automatically re-evaluated when used, making them suitable for dynamic web applications.

Import Locator

import { Locator } from '@playwright/test';

Locator Example

import { test, expect, Locator } from '@playwright/test';

test('Locator example', async ({ page }) => {
    await page.goto('https://example.com');

    const heading: Locator = page.locator('h1');
    const text = await heading.textContent();

    console.log(text);

    await expect(heading).toBeVisible();
});

Important Locator Methods

MethodDescription
locator()Find elements using CSS or XPath.
click()Click an element.
dblclick()Double-click an element.
fill()Enter text into an input.
type()Type text character by character.
press()Press a keyboard key.
clear()Clear input value.
check()Check a checkbox.
uncheck()Uncheck a checkbox.
selectOption()Select a dropdown option.
hover()Hover over an element.
focus()Focus an element.
blur()Remove focus.
textContent()Get text content.
innerText()Get visible text.
inputValue()Get input value.
getAttribute()Get attribute value.
isVisible()Check visibility.
isEnabled()Check enabled state.
count()Count matching elements.
nth()Select element by zero-based index.
first()Select first matching element.
last()Select last matching element.
filter()Filter matching elements.
waitFor()Wait for a locator state.

Locator Practical Example

import { test, expect } from '@playwright/test';

test('Login form interaction', async ({ page }) => {
    await page.goto('https://example.com/login');

    const username = page.locator('#username');
    const password = page.locator('#password');
    const loginButton = page.locator('#login');

    await username.fill('admin');
    await password.fill('admin123');

    await expect(loginButton).toBeEnabled();
    await loginButton.click();
});

4. Different Ways to Create Locators

Playwright supports multiple locator strategies for identifying elements.

import { test } from '@playwright/test';

test('Different locator strategies', async ({ page }) => {
    await page.goto('https://example.com');

    // CSS selector
    await page.locator('#username').fill('admin');

    // Attribute selector
    await page.locator('[id="username"]').fill('admin');

    // XPath selector
    await page.locator('//input[@id="username"]').fill('admin');

    // Text locator
    await page.getByText('Login').click();

    // Role locator
    await page.getByRole('button', {
        name: 'Submit'
    }).click();

    // Label locator
    await page.getByLabel('Email').fill('test@gmail.com');

    // Placeholder locator
    await page.getByPlaceholder('Enter username').fill('admin');

    // Test ID locator
    await page.getByTestId('login-button').click();
});

Best Practice: Prefer getByRole(), getByLabel(), and getByTestId() when appropriate because they generally make tests more resilient and readable.

5. Browser Class

The Browser class represents an actual browser instance.

import { test, chromium, Browser } from '@playwright/test';

test('Browser example', async () => {
    const browser: Browser = await chromium.launch({
        headless: false
    });

    const page = await browser.newPage();

    await page.goto('https://example.com');

    console.log(await page.title());

    await browser.close();
});

Important Browser Methods

MethodDescription
browser.newPage()Create a new page with a new context.
browser.newContext()Create an isolated browser context.
browser.contexts()Get existing contexts.
browser.isConnected()Check browser connection.
browser.version()Get browser version.
browser.close()Close browser.

6. BrowserContext Class

A BrowserContext represents an isolated browser session. Different contexts can have separate cookies, local storage, and session storage.

import {
    test,
    chromium,
    Browser,
    BrowserContext,
    Page
} from '@playwright/test';

test('BrowserContext example', async () => {
    const browser: Browser = await chromium.launch({
        headless: false
    });

    const context: BrowserContext = await browser.newContext();
    const page: Page = await context.newPage();

    await page.goto('https://example.com');

    const cookies = await context.cookies();
    console.log(cookies);

    await context.clearCookies();

    await browser.close();
});

Important BrowserContext Methods

MethodDescription
newPage()Create a page.
pages()Get all pages.
cookies()Get cookies.
addCookies()Add cookies.
clearCookies()Clear cookies.
storageState()Get authentication storage state.
grantPermissions()Grant browser permissions.
clearPermissions()Clear browser permissions.
close()Close context.

7. Frame and FrameLocator

Frames are used when a webpage contains an iframe.

Example HTML

<iframe id="payment-frame"></iframe>

Using FrameLocator

import { test } from '@playwright/test';

test('Iframe example', async ({ page }) => {
    await page.goto('https://example.com');

    const paymentFrame = page.frameLocator(
        '#payment-frame'
    );

    await paymentFrame
        .locator('#card-number')
        .fill('123456789');

    await paymentFrame
        .getByRole('button', { name: 'Pay' })
        .click();
});

Frame vs FrameLocator

FrameFrameLocator
Represents an actual iframe frame.Provides a locator for an iframe.
Can access frame URL and evaluate JavaScript.Locates elements inside an iframe.
Obtained using page.frame().Obtained using page.frameLocator().
Useful for frame-level operations.Useful for UI automation.

8. Keyboard Class

The Keyboard class provides keyboard interaction methods.

import { test } from '@playwright/test';

test('Keyboard example', async ({ page }) => {
    await page.goto('https://example.com');

    await page.locator('#username').focus();

    await page.keyboard.type('admin');

    await page.keyboard.press('Tab');

    await page.keyboard.type('admin123');

    await page.keyboard.press('Enter');
});

Common Keyboard Methods

  • keyboard.press()
  • keyboard.type()
  • keyboard.insertText()
  • keyboard.down()
  • keyboard.up()

9. Mouse Class

The Mouse class is used for mouse interactions.

import { test } from '@playwright/test';

test('Mouse example', async ({ page }) => {
    await page.goto('https://example.com');

    await page.mouse.move(100, 200);

    await page.mouse.click(100, 200);

    await page.mouse.dblclick(100, 200);

    await page.mouse.wheel(0, 500);
});

Common Mouse Methods

  • mouse.click()
  • mouse.dblclick()
  • mouse.move()
  • mouse.down()
  • mouse.up()
  • mouse.wheel()

10. APIRequestContext Class

APIRequestContext is used for API testing without opening a browser UI. Playwright supports HTTP methods such as GET, POST, PUT, PATCH, and DELETE.

import {
    test,
    expect,
    APIRequestContext
} from '@playwright/test';

test('API request example', async ({ request }) => {
    const apiRequest: APIRequestContext = request;

    const response = await apiRequest.get(
        'https://petstore.swagger.io/v2/pet/1'
    );

    expect(response.status()).toBe(200);

    const responseBody = await response.json();

    console.log(responseBody);
});

Important APIRequestContext Methods

MethodDescription
get()Send GET request.
post()Send POST request.
put()Send PUT request.
patch()Send PATCH request.
delete()Send DELETE request.
fetch()Send a custom HTTP request.
dispose()Dispose request context.

11. How Playwright Classes Work Together

The following structure explains the relationship between Browser, BrowserContext, Page, and Locator.

Browser
   |
   +-- BrowserContext
           |
           +-- Page 1
           |     |
           |     +-- Locator
           |
           +-- Page 2
                 |
                 +-- Locator
  • Browser: Launches Chromium, Firefox, or WebKit.
  • BrowserContext: Creates an isolated browser session.
  • Page: Opens a browser tab.
  • Locator: Identifies an HTML element.
  • Keyboard: Performs keyboard interactions.
  • Mouse: Performs mouse interactions.

12. TypeScript Imports Cheat Sheet

Class or FunctionImport Statement
Pageimport { Page } from '@playwright/test'
Locatorimport { Locator } from '@playwright/test'
Browserimport { Browser } from '@playwright/test'
BrowserContextimport { BrowserContext } from '@playwright/test'
Frameimport { Frame } from '@playwright/test'
FrameLocatorimport { FrameLocator } from '@playwright/test'
APIRequestContextimport { APIRequestContext } from '@playwright/test'
APIResponseimport { APIResponse } from '@playwright/test'
Requestimport { Request } from '@playwright/test'
Responseimport { Response } from '@playwright/test'
Downloadimport { Download } from '@playwright/test'
Dialogimport { Dialog } from '@playwright/test'
Keyboardimport { Keyboard } from '@playwright/test'
Mouseimport { Mouse } from '@playwright/test'

Important: These types can be imported from @playwright/test. You generally do not need to create browser objects manually in every test because Playwright Test provides fixtures such as page, context, and browser.

13. Practical Exercise

Try creating a login page automation framework using the following classes:

  1. Browser: Launch Chromium.
  2. BrowserContext: Create a browser session.
  3. Page: Open the login page.
  4. Locator: Identify username and password fields.
  5. Keyboard: Enter login details.
  6. Mouse: Perform mouse interactions.
  7. FrameLocator: Handle iframe-based login.
  8. Expect: Validate login results.

Conclusion

Understanding Playwright classes and interfaces is important for building scalable TypeScript automation frameworks. Start with Browser, BrowserContext, Page, and Locator, then learn FrameLocator, Keyboard, Mouse, and APIRequestContext. These concepts will help you write maintainable UI and API automation tests.

`} {documentHtml}

No comments:

Post a Comment