</>

Technology

Playwright

Difficulty

Beginner

Interview Question

How do you handle browser dialogs (alert, confirm, prompt) in Playwright?

Answer

Handling Browser Dialogs in Playwright

Browser dialogs — alert(), confirm(), and prompt() — are handled using the dialog event.

Important: You must register the handler before the action that triggers the dialog.

Alert Dialog

TypeScript
// Register handler BEFORE the action that triggers the alert
page.on('dialog', async dialog => {
  console.log(dialog.type());    // 'alert'
  console.log(dialog.message()); // 'Are you sure?'
  await dialog.accept();          // Click OK
});

// This action triggers the alert
await page.getByRole('button', { name: 'Delete' }).click();

Confirm Dialog

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

// Dismiss the confirm dialog (click Cancel)
page.on('dialog', async dialog => {
  await dialog.dismiss();
});

Prompt Dialog (with input)

TypeScript
page.on('dialog', async dialog => {
  console.log(dialog.type());           // 'prompt'
  console.log(dialog.defaultValue());   // Default value in prompt
  await dialog.accept('My typed value'); // Type a value and click OK
});

One-time Handler (Better Practice)

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

test('handle confirm dialog', async ({ page }) => {
  await page.goto('/users');

  // Register handler before triggering the dialog
  page.once('dialog', dialog => dialog.accept());

  // Click delete button which triggers confirm()
  await page.getByRole('button', { name: 'Delete User' }).click();

  // Verify user was deleted
  await expect(page.locator('.user-list')).not.toContainText('John Doe');
});

Dialog Types

Dialog Typedialog.type()Methods Available
alert(msg)'alert'accept() only
confirm(msg)'confirm'accept() / dismiss()
prompt(msg)'prompt'accept(text) / dismiss()
beforeunload'beforeunload'accept() / dismiss()

Auto-dismiss All Dialogs

TypeScript
// Dismiss all dialogs automatically
page.on('dialog', dialog => dialog.dismiss());

// Accept all dialogs automatically
page.on('dialog', dialog => dialog.accept());

Follow AutomateQA

Related Topics