QA Interview Hub · Knowledge base · Quizzes · Українська

Playwright › Interaction: actions, tabs, frames, files, dialogs

alert, confirm and prompt dialogs

Playwright automatically dismisses the native alert, confirm and prompt dialogs when nobody listens to the dialog event. Then confirm returns false, while beforeunload is accepted instead. If a listener exists, the auto-close is off and it must call accept() or dismiss() in every branch, otherwise the action stalls. HTML modals are not browser dialogs and are found like ordinary elements, for example with getByRole('dialog').

Playwright · Interaction

I press "Delete", see no confirmation, and the account is still there. Who answered "Cancel"?

The "Delete" button shows confirm("Delete the account?"). The test presses it and waits for the "Account deleted" message, which never appears. In the video there is no dialog at all: it showed up and vanished in milliseconds. There is no bug in the app code, and the account was not deleted because confirm returned false. Playwright answered: when nobody listens to a dialog, it closes it itself. This article is about that default, the "a listener exists, so you must close the dialog" trap, and why most "dialogs" in modern apps are not dialogs at all.

How it works and why. Native browser dialogs (alert, confirm, prompt and beforeunload) block JavaScript on the page until the user answers. Automation cannot leave a page hanging without an answer, so Playwright set a rule: if nobody is subscribed to the dialog event, the dialog is automatically dismissed. For alert this is harmless, while confirm returns false and prompt returns null. If a listener exists, responsibility moves to the test: Playwright closes nothing any more, and the listener must call accept or dismiss, otherwise the page hangs and the action that caused the dialog does not finish before the timeout.

What happens to a dialog

a dialog appears no dialoglistener a listener existson / once auto-dismiss:confirm → falseprompt → null the test mustaccept() ordismiss(), or thepage hangs
Figure 1. Two modes: without a listener Playwright answers (with a refusal), with a listener only the test answers.

Example: deletion "without confirmation". A test that does not know about the dialog:

// before: no dialog listener
await page.getByRole('button', { name: 'Delete' }).click();
await expect(page.getByText('Account deleted')).toBeVisible(); // timeout

The failure looks like a waiting problem, but the cause is upstream: confirm returned false, the app deleted nothing, so "Account deleted" will never appear. Raising the timeout is pointless. The fix: subscribe before the click, capture the text and answer.

let message = '';
page.once('dialog', async (dialog) => {
  message = dialog.message();
  await dialog.accept();
});
await page.getByRole('button', { name: 'Delete' }).click();

expect(message).toContain('Delete the account?');
await expect(page.getByText('Account deleted')).toBeVisible();

The assertions about the dialog text are deliberately kept outside the handler: if an expect inside the handler fails, the error escapes the callback as an unhandled promise rejection: the test fails, but the dialog stays unanswered and the failure points at the callback, not at a test step. So the handler only collects data and answers, and the test checks after the click. The Dialog object has type() (alert, confirm, prompt, beforeunload), message(), defaultValue() for a prompt, and accept(text?) and dismiss().

The "a listener exists, so you must close the dialog" trap. As soon as at least one dialog listener exists, the automatic dismissal is turned off. If the handler forgets accept or dismiss (for example in one branch of an if), the page hangs. Global listeners in a fixture or beforeEach are just as dangerous: "accept everything automatically" hides messages the test should have checked. For a one-off dialog prefer page.once: the handler removes itself and does not touch other steps. For a sequence of dialogs in one scenario, page.on with a branch on type() fits.

const seen: { type: string; message: string; defaultValue: string }[] = [];
page.on('dialog', async (dialog) => {
  seen.push({
    type: dialog.type(),
    message: dialog.message(),
    defaultValue: dialog.defaultValue(),
  });
  if (dialog.type() === 'prompt') await dialog.accept('Duplicate account');
  else await dialog.dismiss(); // confirm returns false
});

await page.getByRole('button', { name: 'Rename' }).click(); // prompt
await expect(page.getByRole('heading', { name: 'Duplicate account' })).toBeVisible();

await page.getByRole('button', { name: 'Delete' }).click(); // confirm, answer: cancel
await expect(page.getByRole('heading', { name: 'Duplicate account' })).toBeVisible();
expect(seen.map((d) => d.type)).toEqual(['prompt', 'confirm']);

The dismiss() method checks the "negative" path: the user pressed "Cancel", and the data must stay. It is as important as the confirmation: a common mistake is to check only the success branch.

beforeunload. The "Leave the page?" dialog appears when the page has unsaved changes. In a test it is triggered, for example, with page.close({ runBeforeUnload: true }) and handled by the same listener. runBeforeUnload does not guarantee the page closes until the dialog is handled.

page.once('dialog', async (dialog) => {
  if (dialog.type() === 'beforeunload') await dialog.accept(); // leave anyway
  else await dialog.dismiss();
});
await page.close({ runBeforeUnload: true });

A native dialog or an HTML modal

Typical

page.on('dialog')

Catches only native browser dialogs. For an HTML modal the event never comes, so the listener does nothing and the test waits in vain.

Better

getByRole('dialog', { name })

A modal is ordinary page elements. Ordinary locators and web-first assertions work, with no listeners at all.

Figure 2. Before writing a listener, find out what you have: a native dialog or an element in the DOM.

Most "dialogs" in modern apps are HTML modals, not browser dialogs. They have no events: they are ordinary elements, best found through getByRole('dialog') with a name. A simple test: if you can inspect the dialog in DevTools and it carries the app's styling, it is HTML.

// an HTML modal is not a browser dialog: ordinary locators
const modal = page.getByRole('dialog', { name: 'Delete the account?' });
await expect(modal).toBeVisible();
await modal.getByRole('button', { name: 'Delete' }).click();
await expect(modal).toBeHidden();

Limits and alternatives. Native dialogs are rare today: apps move to HTML modals because those can be styled and tested. In Selenium dialogs are handled by driver.switchTo().alert(), and if a dialog is left unhandled, the next command fails with an "unexpected alert open" error. In Cypress dialogs are accepted automatically by default (alert and confirm return true), and cancelling has to be done explicitly through an event. In Playwright it is the opposite: the default is a refusal. So the Cypress habit ("it will be accepted anyway") is the cause of the mistake in the example above.

Common mistakes.

  • Pressing a "Delete" button with a confirm and no listener: the dialog is dismissed automatically and the deletion does not happen.
  • Subscribing after the click: the dialog was already dismissed automatically, or the test hung.
  • No accept/dismiss in one branch of the handler: the page hangs.
  • page.on instead of page.once in beforeEach: the handler becomes global for the whole file and hides other dialogs.
  • Looking for an HTML modal with page.on('dialog'): the event never comes, because it is not a native dialog.

Check yourself

A test presses "Delete" with a confirm and waits for "Account deleted", which does not appear. The test has no dialog listener. What happened, and why will a longer timeout not help?

Answer

With no listener Playwright dismissed the dialog automatically, so confirm returned false and the app did not delete anything. The expected message will never appear, so a longer timeout changes nothing. You need page.once('dialog', d => d.accept()) before the click.

A page.on('dialog') handler contains only if (dialog.type() === 'prompt') await dialog.accept('x'). What happens when a confirm appears?

Answer

A listener exists, so there is no automatic dismissal, and in the confirm branch nobody calls accept or dismiss. The page hangs and the action that started the dialog does not finish before the timeout. Every branch must answer (add else await dialog.dismiss()).

A test for the "Delete the account?" modal adds page.on('dialog', …), but the handler is never called, while the modal is visible on screen. Why?

Answer

It is an HTML modal, not a native browser dialog, so there is no dialog event. Ordinary locators work: page.getByRole('dialog', { name: … }) and the toBeVisible and toBeHidden assertions.

In an interview. Junior: Playwright dismisses native dialogs by default, so for a confirm I register page.once('dialog') beforehand and call accept. Middle/Senior: If a listener exists, the dialog must be closed in every branch, otherwise the page hangs. I check the dialog text outside the handler so a failed assertion does not get lost in a callback. I do not set a global "accept all": it hides what the test should check. I test custom modals as ordinary elements through getByRole('dialog'), because they are not browser dialogs.

More articles in this chapter