Scale Your Automation Testing with AI

  • CheckRun end-to-end parallel tests & reduce test execution time by 5x
  • CheckGenerate tests scripts using natural language with KaneAI
  • CheckAccelerate your testing process with Autoheal, SmartWait & RCA
...

How to Handle Playwright Alerts and Dropdowns

In this tutorial, learn how to handle Playwright alerts and dropdowns including prompt and modal alerts, plus single-select, multi-select, and more.

Last Modified on: November 25, 2025

  • Share:

When you work with Playwright, alerts and dropdowns often appear as part of normal web application flow. Knowing how to handle Playwright alerts and dropdowns allows you to keep your automated tests running without interruption.

By handling these elements the right way, you can avoid unexpected test failures, match real user actions more closely, and ensure your tests give consistent results.

Overview

What Are Alerts in Playwright?

Alerts in Playwright are browser dialogs triggered by the page. You capture them with the dialog event, read their message, and accept, dismiss, or enter text to continue testing.

What Are Dropdowns in Playwright?

Dropdowns in Playwright are selectable lists built with native <select> elements or custom UI controls. You interact with them using selectOption for native selects or standard clicks for custom dropdown components.

How to Handle Playwright Alerts?

Playwright lets you work with browser dialogs like alerts, confirms, and prompts through thepage.on('dialog') event. You can listen for these dialogs, read their messages, and choose whether to accept or dismiss them.

  • Open the Target Page: Load the page that triggers an alert by using page.goto() before handling any dialog events.
  • Listen for Dialog Events: Attach a handler with page.on('dialog') to capture alerts, confirms, or prompts when they appear.
  • Read the Dialog Message: Use the dialog object's message() method to inspect the alert text if needed for validation.
  • Accept or Dismiss the Dialog: Call dialog.accept() or dialog.dismiss() depending on the expected behavior of the test.
  • Handle Prompt Inputs: For prompt dialogs, pass an input string into dialog.accept() to simulate user entry.
  • Assert Outcomes: Confirm that the page's response to the alert matches expected behavior using expect() checks.
  • Finish the Test: Complete any remaining steps and close the context or browser to keep test runs stable and consistent.

How to Handle Playwright Dropdowns?

Dropdowns in Playwright can be managed by using select_option() or standard locators when working with custom UI components. These methods allow you to pick values by label, index, or value attributes.

  • Navigate to the Target Page: Use page.goto() to reach the page where the dropdown is located before interacting with it.
  • Identify the Dropdown Element: Locate the dropdown using selectors like get_by_role(), locator(), or CSS selectors for standard HTML select tags.
  • Select Options by Value, Label, or Index: Use select_option() to choose items based on attributes that match your test’s needs.
  • Work With Custom Dropdowns: For non-standard dropdown widgets, click to open the menu and target the option using get_by_text() or similar locators.
  • Check Selected Values: Validate the selected option with expect() assertions to ensure the correct value was used.
  • Simulate Keyboard Navigation: Use keyboard.press() when testing dropdowns that support arrow keys or search-based selection.
  • Wrap Up the Test: Complete assertions, close the page or context, and maintain consistent cleanup across test runs.

What Are Playwright Alerts?

In Playwright, alerts are browser dialogs that appear while a page is running to show a message or request an action. You typically encounter them as simple alerts, confirmation boxes, or prompts that ask for text input before the page can continue processing other interactions.

Here, you’ll rely heavily on good Playwright functions and selectors since alerts and dropdowns often appear only after user interaction, and these functions and selectors make targeting those elements much more reliable.

Note

Note: Run Playwright tests across over 3000 real environments. Try LambdaTest Now!

How to Handle Alerts in Playwright?

Playwright allows handling prompt alerts and modal dialogs that interrupt normal page interaction. Prompt alerts can be handled using page.on("dialog") to provide input, and modal dialogs are handled via standard DOM interactions.

Prompt Alert

Prompt alerts request input from the user and pause interaction until a value is entered and OK or Cancel is clicked.

Test Scenario:

  • Navigate to the Javascript Alert Box Demo page.
  • Click the Click Me button under the Prompt box.
  • Enter a value and accept the prompt.

Implementation:

The test script below listens for the prompt alert, enters a value, and verifies that the text appears in the output.

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

test("Prompt alert", async ({ page }) => {
await page.goto("https://www.lambdatest.com/selenium-playground/javascript-alert-box-demo
");

page.on("dialog", async (alert) => {
console.log(alert.message());
await alert.accept("koushik");
});

await page.locator("button:has-text('Click Me')").nth(2).click();

await expect(page.locator("#prompt-demo")).toContainText("'koushik'");
});

LambdaTest Playwright Alerts and Dropdowns GitHub Repository

Code Walkthrough:

  • Imports and Test Setup: Imports expect and test from Playwright and defines a test named Prompt alert with a page object.
  • Navigation: Navigates the browser to the JavaScript alert demo page using page.goto() method.
  • Dialog Handling: Sets up a dialog event listener that logs the alert message and accepts it with the input koushik.
  • Trigger Prompt: Clicks the third button with text Click Me to trigger the prompt dialog.
  • Verification: Verifies that the element with ID #prompt-demo contains the text koushik.

Once an alert is handled, Playwright assertions help confirm the page updated as expected, whether that’s a message appearing or a field changing value.

Test Execution:

Now, let's run the test for Playwright alerts (prompt and modal) using the following command:

npx playwright test tests/alerts.test.ts
Playwright Tests for Alerts

You can also check out this video on handling Playwright alerts by Vignesh Srinivasa Raghavan, a Senior SDET with 10+ years of expertise in software automation testing, specializing in web, mobile, API, and performance testing.

What Are Playwright Dropdowns?

In Playwright, dropdowns are HTML elements that allow you to select one or more options from a predefined list, typically implemented using the <select> tag. They are commonly used in forms and interactive interfaces to present choices without cluttering the page.

Dropdowns can be single-select or multi-select, and interacting with them requires choosing the correct option by value, label, or index.

How to Handle Dropdowns in Playwright?

Dropdowns allow you to select single or multiple options. Playwright provides selectOption() for standard HTML <select> elements, and standard DOM interactions for custom dropdowns like Bootstrap or jQuery-based dropdowns.

Single-Select Dropdown

Single-select dropdowns allow choosing only one option at a time.

Test Scenario:

  • Navigate to the Select Dropdown Demo page.
  • Select an option from the dropdown using index, label, or value.

Implementation:

The test script below selects an option from a single-select dropdown.

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

test("Single-select dropdown", async ({ page }) => {
  await page.goto("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");
  
  await page.selectOption("#select-demo", {
    index: 5 // alternatively, use label: "Tuesday" or value: "Friday"
  });
});

Code Walkthrough:

  • Imports and Test Setup: Imports test from Playwright and defines a test named Single-select dropdown with a page object.
  • Navigation: Navigates the browser to the select dropdown demo page using the page.goto() method.
  • Dropdown selection: Uses page.selectOption() on #select-demo to select the option at index: 5 (alternatively can use label or value).

Multi-Select Dropdown

Multi-select dropdowns allow selecting multiple options simultaneously.

Test Scenario:

  • Navigate to the Select Dropdown Demo page.
  • Select multiple options using a mix of index, label, and value.

Implementation:

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

test("Multi-select dropdown", async ({ page }) => {
  await page.goto("https://www.lambdatest.com/selenium-playground/select-dropdown-demo");

  await page.selectOption("#multi-select", [
    { label: "Texas" },
    { index: 2 },
    { value: "Washington" }
  ]);
});

Code Walkthrough:

  • Imports and Test Setup: Imports test from Playwright and defines a test named Multi-select dropdown with a page object.
  • Navigation: Navigates the browser to the select dropdown demo page using page.goto().
  • Dropdown Selection: Uses page.selectOption() on #multi-select to select multiple options with label, index, and value.

Bootstrap / jQuery Dropdown

Custom dropdowns like Bootstrap or jQuery require opening the menu and selecting items using DOM locators.

Test Scenario:

Implementation:

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

test("Bootstrap/jQuery dropdown", async ({ page }) => {
  await page.goto("https://www.lambdatest.com/selenium-playground/jquery-dropdown-search-demo");

  await selectCountry("India");
  await selectCountry("Denmark");
  await selectCountry("South Africa");

  async function selectCountry(countryName) {
    await page.click("#country+span");
    await page.locator("ul#select2-country-results")
      .locator("li", { hasText: countryName })
      .click();
  }
});

Code Walkthrough:

  • Imports and Test Setup: Imports test from Playwright and defines a test named Bootstrap/jQuery dropdown with a page object.
  • Navigation: Navigates the browser to the jQuery dropdown search demo page using page.goto().
  • Country Selection: Calls selectCountry() for each country: "India", "Denmark", and "South Africa".
  • Function Definition: Defines selectCountry(countryName) which clicks the dropdown #country+span, locates the results list ul#select2-country-results, finds the li containing the given country, and clicks it.

Test Execution:

Now, let's run the test for Playwright dropdowns using the following command:

npx playwright test tests/dropdown.test.ts
Playwright Tests for Dropdowns

Scale Playwright Testing With LambdaTest

You can leverage the true capabilities of the Playwright test automation framework by running the test on cloud grids like LambdaTest.

Cloud testing platforms like LambdaTest offers Playwright cloud that allows you to run Playwright tests online on 50+ browsers and browser versions such as Chrome, Firefox, Opera, Edge, etc.

  • Parallel Testing at Scale: Run Playwright test scripts across real browsers and OS combinations, including Chromium, WebKit, Edge, and Firefox. Supports Windows, Linux, and macOS.
  • Playwright SDK for Faster Cloud Execution: Integrate the Playwright SDK for efficient workflows, granular control over test runs, and consistent cross-environment results.
  • Auto Heal Capability: Locator recovery ensures test resilience even if the application UI changes, maintaining stable automation at scale.
  • Visual Testing: AI-native SmartUI platform for visual testing across desktop and mobile environments, compatible with Playwright.

To get started, check out this documentation on Playwright testing with LambdaTest.

...

Conclusion

You now have a clear view of how Playwright handles alerts and dropdowns. You can detect, read, and control alerts, including prompts and modal dialogs, without interrupting your test flow.

Also, you can also manage single-select, multi-select, and custom dropdowns with direct, reliable interactions. With these skills, you can create stable tests that handle real user scenarios and respond accurately to page behavior.

Citations

Frequently Asked Questions (FAQs)

How do you handle simple alerts in Playwright?
Use page.on('dialog', callback) to capture simple alerts. Inside the callback, log dialog.message() to verify content and call dialog.accept() to close the alert, ensuring your Playwright test continues without interruption while confirming the alert text matches expectations.
How can you dismiss a confirmation alert in Playwright?
Listen for the dialog event in Playwright and call dialog.dismiss() to cancel the action. This allows you to test user cancellation flows and verify that the page responds correctly when a confirmation alert is rejected during automated testing.
How do you send text to a prompt alert in Playwright?
Use dialog.accept('your text') inside the Playwright dialog listener. This inputs the desired value into the prompt alert and accepts it, enabling Playwright tests to simulate user input and verify that the page handles the entered text correctly.
How do you handle alerts triggered by dynamic actions in Playwright?
Set up page.on('dialog', handler) in Playwright before triggering the action that opens the alert. This ensures the alert is captured immediately, preventing test failures and allowing automated responses like accept, dismiss, or validation of the alert message.
How can you verify alert text in Playwright before responding?
Inside the Playwright dialog event, log or assert dialog.message() to validate the alert content. This ensures that your automated Playwright test only proceeds if the alert text matches expectations, making tests reliable and reflective of real user interactions.
How do you select an option by value in a dropdown using Playwright?
Use page.selectOption('selector', 'value') in Playwright to pick a specific option. This works for both single and multi-select dropdowns, letting automated Playwright tests interact with the correct choice and verify that the selected value is properly applied in the form.
Can you select multiple options in a dropdown using Playwright?
For multi-select dropdowns in Playwright, pass an array of values to page.selectOption('selector', ['value1','value2']). This allows automated testing of forms with multiple selections, confirming that all chosen options are registered correctly by the page.
How do you verify the selected option in a dropdown with Playwright?
Use page.$eval('selector', el => el.value) for single-select or map el.selectedOptions for multi-select in Playwright. This ensures that your test validates the dropdown state after selection, confirming that the correct options are active.
How do you select an option by visible text in a dropdown using Playwright?
Map through the dropdown options using page.$eval in Playwright to find the one matching the visible text, then pass its value to selectOption. This approach works when values are dynamic but displayed text is consistent, allowing reliable automated selection.
How do you handle custom-styled dropdowns in Playwright?
For non-native dropdowns in Playwright, use standard DOM interactions like page.click() on the dropdown and option elements. selectOption won’t work, so you must mimic real user clicks to ensure the test interacts correctly with custom UI components.

Did you find this page helpful?

Helpful

NotHelpful

More Related Hubs

ShadowLT Logo

Start your journey with LambdaTest

Get 100 minutes of automation test minutes FREE!!