Handling alert and confirm Dialogs in Playwright
To handle alert and confirm dialogs in Playwright tests, register a listener with page.on('dialog') before the action that opens the dialog, and call accept() or dismiss() inside it. You can accept or cancel a "Are you sure you want to delete?" confirmation after a Delete click, or the "Saved" notice after a Save click, from inside a test.
If you don't register a listener, Playwright dismisses the dialog automatically. For confirm, that means cancel, so a test that clicks Delete can fail because the memo is not deleted. In the other direction, if you register a listener and forget to close the dialog, the click never finishes and the test times out. I confirmed both behaviors in a test environment.
The test environment was Ubuntu 24.04, Node.js 22.23.4, @playwright/test 1.63.0, and TypeScript 5.9.3. I used only the Chromium that ships with Playwright, in headless mode. I did not test Firefox or WebKit, I did not test headed mode with a person operating the dialogs, and I did not test the print dialog from window.print().
- 1. The page I tested
- 2. Without a listener, dialogs are dismissed automatically
- 3. Pressing OK in confirm
- 4. Entering text in prompt
- 5. Checking the dialog message
- 6. Forgetting to close the dialog in a listener hangs the click
- 7. With waitForEvent, don't await the click first
- 8. The confirmation before leaving the page (beforeunload)
- 9. The dialogclosed event, which reports after the dialog is closed
The page I tested
I wrote a small server with Node.js's http module and served a page with the following buttons. The result of each click is shown in a paragraph with role="status".
const status = document.getElementById('status');
document.getElementById('alert').onclick = () => {
alert('保存しました');
status.textContent = 'alert を閉じました';
};
document.getElementById('confirm').onclick = () => {
const ok = confirm('メモ「' + document.getElementById('name').textContent + '」を削除しますか?');
status.textContent = ok ? '削除しました' : '削除をやめました';
};
document.getElementById('prompt').onclick = () => {
const name = document.getElementById('name');
const value = prompt('新しい名前', name.textContent);
if (value === null) { status.textContent = '名前の変更をやめました'; return; }
name.textContent = value;
status.textContent = '名前を「' + value + '」にしました';
};
The Save button opens an alert, the Delete button opens a confirm, and the Rename button opens a prompt with the current name (groceries) as the default value. The button labels are in Japanese, as shown in the code. There is also a body text field. When you change it, the page shows a beforeunload confirmation before you leave. In playwright.config.ts, I set the per-test timeout to 5 seconds.
Without a listener, dialogs are dismissed automatically
First, I clicked the three buttons without registering any listener.
import { test, expect } from '@playwright/test';
test('何もしないと、ダイアログは閉じられる', async ({ page }) => {
await page.goto('/');
const status = page.getByRole('status');
await page.getByRole('button', { name: '保存' }).click();
await expect(status).toHaveText('alert を閉じました');
await page.getByRole('button', { name: '削除' }).click();
await expect(status).toHaveText('削除をやめました');
await page.getByRole('button', { name: '名前を変える' }).click();
await expect(status).toHaveText('名前の変更をやめました');
});
The test passed. The clicks completed without stopping, confirm returned false, and prompt returned null. According to MDN's descriptions of confirm() and prompt(), both return these values when the user presses Cancel.
The official Playwright documentation on dialogs also says that Playwright dismisses dialogs automatically. If a button only shows an alert, you don't need to write anything in the test. You need to act when you want to test what happens after pressing OK on a confirm.
Pressing OK in confirm
To press OK, register a listener with page.once('dialog') before clicking the button, and call dialog.accept(). A listener registered with once is removed after it runs once.
test('confirm で OK を押す', async ({ page }) => {
await page.goto('/');
page.once('dialog', async (dialog) => {
console.log('type:', dialog.type(), '/ message:', dialog.message());
await dialog.accept();
});
await page.getByRole('button', { name: '削除' }).click();
await expect(page.getByRole('status')).toHaveText('削除しました');
});
type: confirm / message: メモ「買い物」を削除しますか?
The test passed, and the page showed "Deleted". As the Dialog API reference describes, type() returns the kind of dialog (alert, confirm, prompt, or beforeunload), and message() returns the text shown in the dialog. To press Cancel instead, call dialog.dismiss() in place of accept(). That also passed, and the page showed "Delete canceled".
Entering text in prompt
For prompt, pass the text to enter as the argument to accept(). defaultValue() returns the default value the page supplied.
test('prompt に文字を入れる', async ({ page }) => {
await page.goto('/');
page.once('dialog', async (dialog) => {
console.log('type:', dialog.type(), '/ message:', dialog.message(), '/ defaultValue:', dialog.defaultValue());
await dialog.accept('夕飯の材料');
});
await page.getByRole('button', { name: '名前を変える' }).click();
await expect(page.getByRole('status')).toHaveText('名前を「夕飯の材料」にしました');
});
type: prompt / message: 新しい名前 / defaultValue: 買い物

Be careful when you call dialog.accept() with no argument. It doesn't press OK with the default value (groceries). It returns an empty string instead.
名前を「」にしました
If you want to press OK with the default value, pass the default value yourself.
page.once('dialog', (dialog) => dialog.accept(dialog.defaultValue()));
名前を「買い物」にしました
Checking the dialog message
To test the text of the dialog itself, collect the messages in an array inside page.on('dialog'), then compare them with expect after the actions. A listener added with on stays in place until you remove it with page.removeListener().
test('alert の文言を確かめる', async ({ page }) => {
await page.goto('/');
const messages: string[] = [];
page.on('dialog', async (dialog) => {
messages.push(`${dialog.type()}: ${dialog.message()}`);
await dialog.accept();
});
await page.getByRole('button', { name: '保存' }).click();
await page.getByRole('button', { name: '削除' }).click();
expect(messages).toEqual(['alert: 保存しました', 'confirm: メモ「買い物」を削除しますか?']);
await expect(page.getByRole('status')).toHaveText('削除しました');
});
The test passed. One listener received both the alert and the confirm.
Forgetting to close the dialog in a listener hangs the click
If the listener calls neither accept() nor dismiss(), Playwright doesn't close the dialog. The following test registers a listener that only logs the message.
test('リスナーで accept も dismiss も呼ばない', async ({ page }) => {
await page.goto('/');
page.on('dialog', (dialog) => console.log('message:', dialog.message()));
await page.getByRole('button', { name: '削除' }).click();
await expect(page.getByRole('status')).toHaveText('削除しました');
});
The message was logged, but the click never finished, and the test failed with a timeout (part of the output is omitted).
message: メモ「買い物」を削除しますか?
✘ 1 tests/forget.spec.ts:3:5 › リスナーで accept も dismiss も呼ばない (10.0s)
Test timeout of 5000ms exceeded.
Tearing down "context" exceeded the test timeout of 5000ms.
Error: locator.click: Test timeout of 5000ms exceeded.
Call log:
...
- performing click action
The call log stops at "performing click action" and says nothing about the dialog. Even the test's teardown (closing the context) timed out. The test had a 5-second limit but took 10.0 seconds.
The page.on('dialog') API reference says that a listener must always call accept() or dismiss(). If it doesn't, the page waits for the dialog to be handled and actions such as clicks never complete. If a click hangs with "performing click action" until the timeout, check whether your dialog listener is missing a call to close the dialog.
With waitForEvent, don't await the click first
You can also receive a dialog with page.waitForEvent('dialog'). However, if you await the click before waiting for the dialog, the test hangs in the same way as above.
test('waitForEvent の前に click を await する', async ({ page }) => {
await page.goto('/');
const dialogPromise = page.waitForEvent('dialog');
await page.getByRole('button', { name: '削除' }).click(); // ここで止まった
const dialog = await dialogPromise;
await dialog.accept();
});
waitForEvent also acts as a listener, so Playwright doesn't dismiss the dialog automatically. The click can't finish until the dialog is closed, and the accept() that would close the dialog doesn't run until the click finishes. Each waits for the other.
If you keep the click as a Promise without await, then await it after closing the dialog, the test passes.
test('waitForEvent でダイアログを受け取る', async ({ page }) => {
await page.goto('/');
const dialogPromise = page.waitForEvent('dialog');
const clickPromise = page.getByRole('button', { name: '削除' }).click();
const dialog = await dialogPromise;
console.log('message:', dialog.message());
await dialog.accept();
await clickPromise;
await expect(page.getByRole('status')).toHaveText('削除しました');
});
Use this form when you want to decide whether to accept or cancel based on the message. If you already know what to do, registering the listener with page.once('dialog') in advance is shorter.
The confirmation before leaving the page (beforeunload)
The "Leave this site?" confirmation that appears when you leave a page with unsaved input is delivered as a beforeunload dialog. To have the page show this confirmation when it closes, use page.close({ runBeforeUnload: true }), as described in the official documentation.
test('beforeunload の確認を受け取る', async ({ page }) => {
await page.goto('/');
await page.getByLabel('本文').fill('牛乳');
const dialogPromise = page.waitForEvent('dialog');
await page.close({ runBeforeUnload: true });
const dialog = await dialogPromise;
console.log('type:', dialog.type(), '/ message:', JSON.stringify(dialog.message()));
await dialog.accept();
await page.waitForEvent('close');
console.log('isClosed:', page.isClosed());
});
type: beforeunload / message: ""
isClosed: true
type() returned beforeunload, and message() returned an empty string. Calling accept() closed the page. Calling dismiss() kept the page open, and the text I had entered (milk) remained in the input field (isClosed: false). When I called page.close() without runBeforeUnload, the page closed without any dialog appearing.
When navigating to another URL with page.goto(), the beforeunload dialog also reached the listener if one was registered. Without a listener, page.goto() navigated away without being stopped by a dialog.
url: http://localhost:4173/?next
The official documentation says that without a listener, dialogs are dismissed automatically. For beforeunload, however, the page navigated away as if OK had been pressed. Reading Playwright 1.63.0's source code, I found that when there is no listener, the dialog is closed with accept only for beforeunload, and with dismiss for every other type.
async _close() {
if (this._type === "beforeunload")
await this._accept();
else
await this._dismiss();
}
The dialogclosed event, which reports after the dialog is closed
Playwright 1.63 adds a dialogclosed event that fires when a dialog is closed (see the dialogclosed event in the Page API reference). A dialogclosed listener does not need to close the dialog.
test('dialogclosed だけを聞く', async ({ page }) => {
await page.goto('/');
const closed: string[] = [];
page.on('dialogclosed', (dialog) => closed.push(`${dialog.type()}: ${dialog.message()}`));
await page.getByRole('button', { name: '削除' }).click();
await expect(page.getByRole('status')).toHaveText('削除をやめました');
console.log(closed);
});
[ 'confirm: メモ「買い物」を削除しますか?' ]
When you register only dialogclosed, Playwright closes the dialog automatically (a confirm is canceled), and you can still read its message afterward. Use this when you want to record which dialogs appeared without changing how they behave.





