How to Handle Alerts and Popups in Playwright: Complete TypeScript Tutorial for Beginners

Introduction

Learning how to handle alerts and popups in Playwright is an important skill for every QA Automation Engineer, SDET, software testing student, and Selenium engineer transitioning to Playwright.

Modern web applications frequently display JavaScript alerts, confirmation dialogs, prompt dialogs, browser popups, and custom modal windows during user interactions. These dialogs often appear during login, payment confirmation, file downloads, account deletion, or security verification. If your automation script cannot handle them correctly, your test execution may pause, fail, or produce unreliable results.

Playwright provides built-in APIs that make alert and popup handling simple and reliable. Unlike Selenium, Playwright automatically waits for events and offers event-driven APIs that reduce synchronization issues.

In this how to handle alerts and popups in Playwright tutorial, you’ll learn:


What Are Alerts and Popups in Playwright?

Alerts and popups are browser dialogs that interrupt normal user interaction until the user responds.

Common dialog types include:

TypePurpose
AlertShows a message with an OK button
Confirmation DialogAllows OK or Cancel
Prompt DialogAccepts user input
Browser PopupOpens a new browser tab or window
Modal DialogCustom HTML popup inside the page

JavaScript Alert

alert(“Operation Successful”);

Confirmation Dialog

confirm(“Do you want to continue?”);

Prompt Dialog

prompt(“Enter your username”);

Browser Popup

Examples include:

  • Payment gateway
  • Login window
  • OAuth authentication
  • Terms and Conditions page

Modal Dialog

Unlike JavaScript alerts, modal dialogs are built using HTML and CSS.

Examples:

  • Bootstrap Modal
  • Material UI Dialog
  • React Modal
  • Angular Modal

Benefits of Handling Alerts and Popups

Understanding how to handle alerts and popups in Playwright offers several advantages:


Step-by-Step Tutorial: How to Handle Alerts and Popups in Playwright

Step 1: Handle a Simple Alert

Playwright listens for dialog events using page.on(‘dialog’).

import { test, expect } from ‘@playwright/test’;

test(‘Handle alert’, async ({ page }) => {

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

  page.on(‘dialog’, async dialog => {

    console.log(dialog.message());

    await dialog.accept();

  });

  await page.click(‘#showAlert’);

});

Explanation

When the alert appears:

  • Playwright captures it
  • Prints the alert message
  • Clicks OK
  • Continues test execution

Practical use case: Success message after submitting a form.


Step 2: Handle a Confirmation Dialog

test(‘Confirmation dialog’, async ({ page }) => {

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

  page.on(‘dialog’, async dialog => {

    await dialog.accept();

  });

  await page.click(‘#deleteRecord’);

});

Expected Behavior

The confirmation dialog appears after clicking Delete, and Playwright automatically accepts it.

Use case: Delete account, remove record, logout confirmation.


Step 3: Dismiss a Confirmation Dialog

test(‘Dismiss confirmation’, async ({ page }) => {

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

  page.on(‘dialog’, async dialog => {

    await dialog.dismiss();

  });

  await page.click(‘#cancelDelete’);

});

Explanation

Instead of clicking OK, Playwright clicks Cancel.

Use case: Validate cancel workflows.


Step 4: Handle Prompt Dialogs

Prompt dialogs require user input.

test(‘Prompt dialog’, async ({ page }) => {

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

  page.on(‘dialog’, async dialog => {

    await dialog.accept(‘John Smith’);

  });

  await page.click(‘#promptButton’);

});

Expected Behavior

The prompt receives John Smith as input and closes successfully.

Use case: Enter username, coupon code, or verification token.


Step 5: Verify Dialog Information

Playwright allows validation of dialog properties.

test(‘Verify dialog’, async ({ page }) => {

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

  page.on(‘dialog’, async dialog => {

    expect(dialog.type()).toBe(‘alert’);

    expect(dialog.message()).toContain(‘Saved’);

    await dialog.accept();

  });

  await page.click(‘#save’);

});

Why This Matters

Verifying dialog messages ensures the correct business logic is executed.


Handling Browser Popups

Browser popups open in a new window or tab.

Playwright uses waitForEvent(‘popup’).

test(‘Handle popup window’, async ({ page }) => {

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

  const popupPromise = page.waitForEvent(‘popup’);

  await page.click(‘#openPopup’);

  const popup = await popupPromise;

  await popup.waitForLoadState();

  expect(await popup.title()).toContain(‘Documentation’);

});

Practical Use Cases

  • Login with Google
  • OAuth authentication
  • Payment gateway
  • Help documentation
  • Terms and Conditions

Handling Modal Dialogs

HTML modals are regular web elements.

Example:

test(‘Bootstrap modal’, async ({ page }) => {

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

  await page.click(‘#openModal’);

  await expect(page.locator(‘.modal’)).toBeVisible();

  await page.locator(‘#username’).fill(‘Admin’);

  await page.locator(‘#closeModal’).click();

});

Important Note

Unlike JavaScript dialogs, HTML modals use normal Playwright locators.


Real-World Automation Examples

1. Delete Confirmation

page.on(‘dialog’, async dialog => {

  await dialog.accept();

});

await page.click(‘#delete’);

Scenario: Deleting customer records.


2. Login Popup

const popupPromise =

page.waitForEvent(‘popup’);

await page.click(‘#loginGoogle’);

const popup =

await popupPromise;

Scenario: OAuth authentication.


3. Coupon Prompt

page.on(‘dialog’, async dialog => {

  await dialog.accept(‘SAVE20’);

});

Scenario: Promotional discount.


4. Session Expiration Alert

page.on(‘dialog’, async dialog => {

  expect(dialog.message())

  .toContain(‘Session expired’);

  await dialog.accept();

});

Scenario: Banking applications.


5. Payment Success Alert

page.on(‘dialog’, async dialog => {

  expect(dialog.message())

      .toContain(‘Payment Successful’);

  await dialog.accept();

});

Scenario: E-commerce checkout.


Playwright vs Selenium

FeaturePlaywrightSelenium
Alert HandlingEvent-based APIswitchTo().alert()
Auto WaitingYesMostly manual
Popup HandlingwaitForEvent()Window handles
StabilityHighModerate
SynchronizationAutomaticExplicit waits often needed
Beginner FriendlyExcellentModerate

Why Playwright Is Easier

Playwright’s event-driven architecture reduces boilerplate code and improves test reliability, especially for asynchronous browser interactions.


Best Practices for Alert and Popup Automation

Follow these recommendations for stable automation:

  • Register the dialog listener before triggering the alert.
  • Use waitForEvent(‘popup’) for browser windows.
  • Verify dialog messages whenever possible.
  • Avoid hard-coded waits such as waitForTimeout().
  • Use assertions instead of manual delays.
  • Keep popup handling methods inside the Page Object Model.
  • Capture screenshots when popup-related tests fail.
  • Execute popup tests across Chromium, Firefox, and WebKit in CI/CD pipelines.

Common Issues & Troubleshooting Tips

ProblemSolution
Dialog not detectedRegister the event listener before clicking the triggering element.
Popup timeoutEnsure the popup is actually opened by the application.
Incorrect dialog messageValidate business logic and expected text.
HTML modal not foundUse the correct CSS or XPath locator after the modal becomes visible.
Flaky popup testsReplace fixed waits with Playwright assertions and auto-waiting features.

Playwright Interview Questions with Answers

1. How do you handle JavaScript alerts in Playwright?

Use page.on(‘dialog’) and call dialog.accept() or dialog.dismiss().


2. How do you dismiss a confirmation dialog?

Use:

await dialog.dismiss();


3. How do you enter text into a prompt dialog?

Use:

await dialog.accept(“Playwright”);


4. How do you automate browser popups?

Use:

page.waitForEvent(‘popup’);


5. How are HTML modals different from JavaScript alerts?

HTML modals are part of the DOM and are handled using standard Playwright locators. JavaScript alerts are browser dialogs handled through the dialog event.


FAQs

What is how to handle alerts and popups in Playwright?

It is the process of automating JavaScript dialogs, browser popups, and HTML modal windows using Playwright APIs such as page.on(‘dialog’) and page.waitForEvent(‘popup’).


How do I get started with how to handle alerts and popups in Playwright?

Install Playwright, create a test project, listen for dialog events, use dialog.accept() or dialog.dismiss(), and practice with sample applications that generate alerts and popups.


Is how to handle alerts and popups in Playwright suitable for beginners?

Yes. Playwright offers simple, event-based APIs with automatic waiting, making alert and popup handling easier than many traditional browser automation tools.

Leave a Comment

Your email address will not be published. Required fields are marked *