Dialog Handling

Back

Loading concept...

Dialog Handling in Playwright: The Doorbell Story

The Big Picture

Imagine you’re at home and someone rings the doorbell. You have choices:

  • Answer it (accept)
  • Ignore it (dismiss)
  • Ask “Who’s there?” and then decide

Web browsers have these same “doorbells” called dialogs. They pop up and wait for you to respond before anything else happens. Playwright helps you answer these doorbells automatically!


What Are Browser Dialogs?

Browser dialogs are little popup windows that pause everything until you respond. There are three types:

graph TD A["Browser Dialogs"] --> B["Alert"] A --> C["Confirm"] A --> D["Prompt"] B --> E["Just says OK"] C --> F["Says OK or Cancel"] D --> G["Asks for text input"]

Think of them like three different friends knocking on your door:

  • Alert Friend: Just wants to tell you something. You say “OK, got it!”
  • Confirm Friend: Asks a yes/no question. You say “Yes” or “No”
  • Prompt Friend: Asks you to write something down

1. Alert Dialogs

What Is It?

An alert is the simplest dialog. It shows a message and has ONE button: OK.

Real Life Example: When a website says “Your file has been saved!” - that’s an alert!

The Code

// Listen for dialogs BEFORE they appear
page.on('dialog', async dialog => {
  console.log(dialog.message());
  await dialog.accept();
});

// Now trigger the alert
await page.click('#show-alert');

What’s Happening:

  1. We tell Playwright “Hey, watch for doorbells!”
  2. When one rings, read the message
  3. Click the OK button (accept)

Key Points

  • Alert has only ONE button (OK)
  • You can ONLY accept it
  • The message tells you what’s happening

2. Confirm Dialogs

What Is It?

A confirm dialog asks a yes/no question. It has TWO buttons: OK and Cancel.

Real Life Example: “Are you sure you want to delete this photo?” - that’s a confirm dialog!

The Code

// Accept the confirm (click OK)
page.on('dialog', async dialog => {
  if (dialog.type() === 'confirm') {
    await dialog.accept();
  }
});

// OR dismiss it (click Cancel)
page.on('dialog', async dialog => {
  if (dialog.type() === 'confirm') {
    await dialog.dismiss();
  }
});

What’s Happening:

  • accept() = Click “OK” (Yes, do it!)
  • dismiss() = Click “Cancel” (No, stop!)

The Difference

Action What Happens
accept() User clicked OK
dismiss() User clicked Cancel

3. Prompt Dialogs

What Is It?

A prompt dialog asks for text input. It has a text box AND two buttons: OK and Cancel.

Real Life Example: “What’s your name?” with a text box - that’s a prompt!

The Code

// Answer the prompt with text
page.on('dialog', async dialog => {
  if (dialog.type() === 'prompt') {
    // Type "Playwright" in the box
    await dialog.accept('Playwright');
  }
});

The Magic Part: When you accept() a prompt, you can pass in your answer!

// Different scenarios
await dialog.accept('Hello');   // Types "Hello"
await dialog.accept('');        // Empty answer
await dialog.dismiss();         // Clicks Cancel

4. Dialog Events

What Is It?

A dialog event fires whenever ANY dialog appears. It’s like setting up a doorbell camera that catches everyone!

Setting Up the Listener

// Listen for ALL dialogs
page.on('dialog', async dialog => {
  console.log('Type:', dialog.type());
  console.log('Message:', dialog.message());
});

Dialog Properties

Property What It Tells You
type() ‘alert’, ‘confirm’, or ‘prompt’
message() The text shown in the dialog
defaultValue() Default text in prompt box

Smart Handler Example

page.on('dialog', async dialog => {
  switch(dialog.type()) {
    case 'alert':
      await dialog.accept();
      break;
    case 'confirm':
      await dialog.accept();
      break;
    case 'prompt':
      await dialog.accept('My Answer');
      break;
  }
});

5. Accepting and Dismissing

The Two Responses

Every dialog needs ONE of two responses:

graph LR A["Dialog Appears"] --> B{Your Choice} B --> C["accept"] B --> D["dismiss"] C --> E["OK / Submit"] D --> F["Cancel / Close"]

Accept

// Simple accept
await dialog.accept();

// Accept with value (for prompts)
await dialog.accept('My answer here');

When to use: When you want to proceed, agree, or submit.

Dismiss

// Always just dismiss - no arguments
await dialog.dismiss();

When to use: When you want to cancel, close, or say no.

Important Rules

  1. You MUST respond - If you don’t, the test hangs forever!
  2. Set listener FIRST - Listen before the dialog appears
  3. One response only - Each dialog gets one accept OR dismiss

Complete Example

Here’s everything working together:

const { test } = require('@playwright/test');

test('handle all dialogs', async ({ page }) => {
  // Set up the doorbell watcher
  page.on('dialog', async dialog => {
    const type = dialog.type();
    const msg = dialog.message();

    console.log(`Got ${type}: ${msg}`);

    if (type === 'alert') {
      await dialog.accept();
    }
    else if (type === 'confirm') {
      // Accept if asking about saving
      if (msg.includes('save')) {
        await dialog.accept();
      } else {
        await dialog.dismiss();
      }
    }
    else if (type === 'prompt') {
      await dialog.accept('Test User');
    }
  });

  // Now do your test actions
  await page.goto('https://example.com');
  await page.click('#trigger-dialogs');
});

Quick Reference Table

Dialog Type Buttons accept() dismiss()
Alert OK Clicks OK N/A
Confirm OK, Cancel Clicks OK Clicks Cancel
Prompt OK, Cancel Submits text Clicks Cancel

Common Mistakes to Avoid

Mistake 1: Setting listener too late

// WRONG - dialog appears before listener
await page.click('#show-alert');
page.on('dialog', ...);

// RIGHT - listener first
page.on('dialog', ...);
await page.click('#show-alert');

Mistake 2: Forgetting to respond

// WRONG - test will hang!
page.on('dialog', dialog => {
  console.log(dialog.message());
  // Forgot to accept or dismiss!
});

// RIGHT
page.on('dialog', async dialog => {
  console.log(dialog.message());
  await dialog.accept();
});

Mistake 3: Using wrong method

// WRONG - accept() without await
page.on('dialog', dialog => {
  dialog.accept(); // Missing await!
});

// RIGHT
page.on('dialog', async dialog => {
  await dialog.accept();
});

You Did It!

Now you can handle any browser dialog like a pro:

  • Alert - Just acknowledge with accept()
  • Confirm - Choose accept() or dismiss()
  • Prompt - Provide text with accept('your text')
  • Events - Use page.on('dialog', ...) to catch them all
  • Always respond - Never leave a dialog hanging!

Remember: Set up your listener BEFORE triggering dialogs, and ALWAYS respond!

Loading story...

Story - Premium Content

Please sign in to view this story and start learning.

Upgrade to Premium to unlock full access to all stories.

Stay Tuned!

Story is coming soon.

Story Preview

Story - Premium Content

Please sign in to view this concept and start learning.

Upgrade to Premium to unlock full access to all content.