Playwright · Reliable end-to-end tests
How do you handle alerts, confirms and prompts?
Short answer
Register a dialog listener before the action that triggers it, then accept or dismiss. If no listener is registered, Playwright dismisses dialogs automatically.
Browser dialogs block the page until they are handled. Playwright surfaces them as events rather than as DOM elements. The listener must exist before the triggering action, or the dialog may be auto-dismissed before your code sees it.
page.on("dialog", async (dialog) => {
expect(dialog.type()).toBe("confirm");
expect(dialog.message()).toContain("Delete this item?");
await dialog.accept();
});
await page.getByRole("button", { name: "Delete" }).click();
await expect(page.getByText("Item deleted")).toBeVisible();Dialog actions and properties
dialog.accept()confirms an alert or confirmdialog.accept(text)fills and accepts a promptdialog.dismiss()cancels a confirm or promptdialog.type()returns alert, confirm, prompt or beforeunloaddialog.message()returns the text shown to the userdialog.defaultValue()returns the prompt's initial value
page.once("dialog", async (dialog) => {
await dialog.accept("Asha");
});
await page.getByRole("button", { name: "Rename" }).click();
await expect(page.getByRole("heading", { name: "Asha" })).toBeVisible();Use page.once when only one dialog is expected, and page.on when a flow can produce several. If a test deliberately verifies that a dialog appears, resolve a promise from the listener and await it, so the assertion is tied to the event rather than to a sleep.
Follow-ups you should expect
Interviewers use these to check whether the first answer was understanding or memorisation.
- 1What happens if no dialog listener is registered?
- 2How do you accept a prompt with text?
- 3When would you use page.once instead of page.on?
- 4How do you assert on the dialog message?
Say it in the interview
Browser dialogs are events, so I register a dialog listener before the click that opens one. I can assert on the type and message, then accept or dismiss, and for a prompt I pass the text to accept. If no listener exists, Playwright dismisses the dialog automatically, which can hide an unexpected confirmation. I use a one-time listener when only one dialog should appear.
Use this as a model, not a script. Saying it in your own words is what makes it survive follow-up pressure.
Related questions
Reading is step one
Now say it out loud.
Understanding an answer and delivering it under pressure are different skills. Rehearse this topic in a live Playwright mock interview and get scored feedback on depth, clarity and confidence.