Lesson 4
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
1import { test, expect } from '@playwright/test'; 2 3test('handle pop-ups and dialogs', async ({ page }) => { 4 // Navigate to the login page 5 await page.goto('http://localhost:3000/login'); 6 7 // Set up the dialog event listener 8 page.on('dialog', async dialog => { 9 await dialog.dismiss(); 10 expect(dialog.message()).toBe('Login Failed'); 11 }); 12 13 // Enter incorrect login credentials to trigger the alert dialog 14 await page.fill('#username', 'wronguser'); 15 await page.fill('#password', 'wrongpassword'); 16 await page.click('button[type="submit"]'); 17});

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.

Handling Multiple Dialogs with Mixed Actions

When you setup a dialog event listener, it handles all subsequent dialog events. In some cases, you might need to perform different actions on multiple dialogs, such as initially dismissing one and then accepting another. Here’s how to handle such scenarios in Playwright:

Example of Mixed Dialog Actions

TypeScript
1import { test, expect } from '@playwright/test'; 2 3test('handle multiple dialogs with mixed actions', async ({ page }) => { 4 // Navigate to the page 5 await page.goto('http://localhost:3000/mixed-dialogs'); 6 7 let count = 0; 8 9 // Set up a dialog event listener to handle multiple dialogs with different actions 10 page.on('dialog', async dialog => { 11 if (count === 0) { 12 expect(dialog.message()).toBe('First Dialog Message'); 13 await dialog.dismiss(); // Dismiss the first dialog 14 } else if (count === 1) { 15 expect(dialog.message()).toBe('Second Dialog Message'); 16 await dialog.accept(); // Accept the second dialog 17 } 18 count++; 19 }); 20 21 // Perform actions that trigger the dialogs 22 await page.click('#trigger-mixed-dialogs'); 23 24 // Wait one second to make sure all the dialogs were handled 25 await page.waitForTimeout(1000); 26 27 // Verify that both dialogs were handled 28 expect(count).toBe(2); 29});

In this example, an event listener is configured to perform different actions based on the order of the dialogs encountered:

  1. First Dialog:

    • The first dialog is dismissed, typically used to cancel an operation or ignore a prompt.
  2. Second Dialog:

    • The second dialog is accepted, often to confirm an operation or proceed with an action.

By implementing this strategy, you ensure that each dialog is handled according to your test scenarios, maintaining a reliable and accurate automation workflow.

Why It Matters

Handling pop-ups and dialogs is essential for creating seamless and predictable automation scripts. In real-world applications, pop-ups can interrupt your automated workflow, causing failures if they're not handled correctly. Whether you're performing automated tests or scraping data, managing these interruptions will make your scripts more robust and less prone to breaking.

Managing pop-ups and dialogs efficiently allows your tests to handle unexpected events gracefully and ensures the reliability of your automation tasks. Ready to tackle this challenge? Let’s move on to the practice section to solidify your understanding.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.