Playwright_UI_Elements_Interactions

Playwright UI Elements Interactions

Most web automation revolves around interacting with user interface (UI) elements. Whether you’re filling out a login form, selecting an option from a dropdown, uploading a file, or switching to another browser tab, Playwright provides simple and reliable APIs to perform these actions. In this guide, you’ll learn how to handle the most common UI interactions using Playwright with practical examples.


Common UI Elements in Web Applications

Most automation projects involve interacting with:

  • Buttons
  • Text fields
  • Text areas
  • Checkboxes
  • Radio buttons
  • Dropdown lists
  • Alerts and dialogs
  • Frames (iframes)
  • Multiple browser tabs/windows
  • File upload controls
  • Mouse and keyboard actions

Let’s explore each one.


Clicking Buttons

Buttons are one of the most frequently automated elements.

TypeScript

await page.getByRole('button', { name: 'Login' }).click();

Java

page.getByRole(
AriaRole.BUTTON,
new Page.GetByRoleOptions().setName("Login")
).click();

Best Practices

  • Prefer getByRole()
  • Avoid brittle XPath locators
  • Let Playwright handle auto-waiting

Handling Text Fields

Entering text into input fields is straightforward.

TypeScript

await page.getByLabel('Username').fill('admin');

Java

page.getByLabel("Username").fill("admin");

The fill() method automatically clears any existing value before entering new text.


Working with Text Areas

Text areas are handled in the same way as input fields.

TypeScript

await page.locator("#comments")
.fill("This is a Playwright tutorial.");

Reading Text from an Element

Sometimes you need to verify displayed text.

TypeScript

const message =
await page.locator(".success").textContent();
console.log(message);

Handling Checkboxes

Selecting a checkbox:

TypeScript

await page.getByLabel("Accept Terms").check();

Unselecting:

await page.getByLabel("Accept Terms").uncheck();

Checking status:

await expect(
page.getByLabel("Accept Terms")
).toBeChecked();

Handling Radio Buttons

Radio buttons are selected using check().

await page.getByLabel("Male").check();

Playwright automatically waits until the element is available.


Working with Dropdown Lists

For standard HTML <select> elements:

await page.locator("#country")
.selectOption("India");

Select by value:

await page.locator("#country")
.selectOption("IN");

Select by label:

await page.locator("#country")
.selectOption({
label: "India"
});

Handling Alerts and Dialogs

JavaScript alerts require event handling.

Example:

page.on("dialog", async dialog => {
console.log(dialog.message());
await dialog.accept();
});
await page.getByRole("button",
{ name: "Delete" }).click();

Rejecting a confirmation dialog:

await dialog.dismiss();

Working with Frames (iFrames)

Some applications load content inside iframes.

Playwright provides frameLocator().

await page
.frameLocator("#paymentFrame")
.getByRole("button",
{ name: "Pay Now" })
.click();

Advantages:

  • Cleaner syntax
  • Better readability
  • Automatic waiting

Handling Multiple Browser Tabs

When clicking a link that opens a new tab:

const pagePromise =
context.waitForEvent("page");
await page.getByText("Open Report").click();
const newPage =
await pagePromise;

Bring the new tab to the foreground:

await newPage.bringToFront();

File Upload

Uploading a file is simple.

await page
.locator("input[type='file']")
.setInputFiles("sample.pdf");

Uploading multiple files:

await page
.locator("input[type='file']")
.setInputFiles([
"a.pdf",
"b.pdf"
]);

File Download

Wait for a download event.

const downloadPromise =
page.waitForEvent("download");
await page.getByText("Download")
.click();
const download =
await downloadPromise;

Mouse Actions

Hover over an element:

await page.locator(".menu")
.hover();

Double click:

await page.locator("#save")
.dblclick();

Right click:

await page.locator("#settings")
.click({
button: "right"
});

Keyboard Actions

Typing text:

await page.keyboard.type("Playwright");

Pressing Enter:

await page.keyboard.press("Enter");

Keyboard shortcut:

await page.keyboard.press("Control+A");

Drag and Drop

Playwright has built-in drag-and-drop support.

await page
.locator("#source")
.dragTo(
page.locator("#target")
);

No third-party library is required.


Scrolling

Scroll to an element:

await page
.locator("#footer")
.scrollIntoViewIfNeeded();

Hover Menus

Many web applications reveal menus on hover.

await page
.locator(".products")
.hover();
await page
.getByText("Laptops")
.click();

Common Mistakes

Using Fixed Delays

Avoid:

await page.waitForTimeout(5000);

Prefer Playwright’s built-in synchronization.


Using XPath Everywhere

Use:

  • getByRole()
  • getByLabel()
  • getByTestId()

whenever possible.


Ignoring Accessibility Locators

Accessibility-based locators are more stable and easier to maintain.


Best Practices

  • Prefer semantic locators (getByRole, getByLabel)
  • Keep UI interactions inside Page Object classes
  • Avoid hard-coded waits
  • Handle dialogs using event listeners
  • Use frameLocator() for iframe interactions
  • Store reusable interaction methods in utility classes
  • Validate outcomes after every important action

Frequently Asked Questions

Does Playwright automatically wait before clicking?

Yes. Playwright waits until the element is visible, enabled, stable, and ready for interaction.


How do I upload files in Playwright?

Use the setInputFiles() method on a file input element.


How do I handle alerts?

Listen for the dialog event and call accept() or dismiss().


Can Playwright work with iframes?

Yes. Use frameLocator() to interact with elements inside frames.


How do I switch between browser tabs?

Wait for the "page" event from the browser context, then interact with the newly opened page.


Conclusion

Playwright provides a clean, modern, and reliable API for handling virtually every common UI interaction in web applications. Combined with its built-in auto-waiting mechanism, these APIs reduce test flakiness and simplify automation code.

Mastering these interactions is essential before moving on to advanced topics such as assertions, Page Object Model (POM), API testing, and framework design.


Related Articles

What is Playwright?

Playwright Architecture Explained

Playwright Setup with TypeScript

Playwright Setup with Java

Playwright Locator Strategies

Playwright Auto-Waiting Mechanism

Complete Playwright Tutorial


Discover more from Rotebit

Subscribe to get the latest posts sent to your email.

1 Comment

Leave a Reply