Handling Pop-ups and Dialogs

Handling Pop-ups and Dialogs

Welcome back! After advancing through basic web interactions with Playwright, it’s time to delve into a crucial aspect of web automation: handling pop-ups and dialogs. Navigating these interruptions can be tricky, but mastering how to handle them will make your scripts more robust and reliable.

What You'll Learn

In this lesson, you'll learn how to manage alert dialogs using Playwright. Alert dialogs often appear in response to certain actions, such as failed login attempts or confirmation prompts before performing critical actions.

Let's consider a scenario where incorrect login credentials trigger an alert:

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

test('handle pop-ups and dialogs', async ({ page }) => {
  // Navigate to the login page
  await page.goto('http://localhost:3000/login');

  // Set up the dialog event listener
  page.on('dialog', async dialog => {
    await dialog.dismiss();
    expect(dialog.message()).toBe('Login Failed');
  });

  // Enter incorrect login credentials to trigger the alert dialog
  await page.fill('#username', 'wronguser');
  await page.fill('#password', 'wrongpassword');
  await page.click('button[type="submit"]');
});

The code snippet illustrates the essential steps: navigating to a login page, entering incorrect credentials, and then handling the resulting alert dialog.

In the dialog handling part of the code, the following steps are performed:

  1. Setting Up the Dialog Event Listener:

    • page.on('dialog', async dialog => { ... }) sets up an event listener for dialog events on the page. When an alert dialog is triggered, this callback function will be executed.
  2. Dismissing the Alert Dialog:

    • Inside the event listener, await dialog.dismiss(); is called to dismiss the alert dialog. This simulates the user action of clicking the "Cancel" button on a typical alert dialog. If you want to simulate the action of clicking the "OK" button, you can use await dialog.accept();.
  3. Verifying the Alert Message:

    • expect(dialog.message()).toBe('Login Failed'); verifies the text message of the alert dialog. dialog.message() retrieves the message displayed in the alert, and expect(...).toBe('Login Failed') checks if it matches the expected message "Login Failed." This ensures that the alert is the one triggered by the incorrect login credentials.

These steps together ensure that any alert dialog that appears as a result of the actions taken on the page is properly managed and validated to prevent disruptions in the automated workflow.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal