All challenges · Core Interactions
Challenge 14 of 29 · Building fluency · Core Interactions
Handle a JavaScript Alert
Browser alerts block the page until handled. Set up a listener before triggering one so the dialog is dealt with and the page carries on.
Skills you will practise
- dialog events
- listener before action
- alerts
The concept
alert(), confirm() and prompt() open native browser dialogs that pause the page's JavaScript until someone responds. Playwright exposes them through the dialog event. By default, if no listener is registered, Playwright dismisses dialogs automatically, which means a confirm() returns false and your “Delete” action quietly does nothing.
To control the outcome, register a listener before the action that opens the dialog. Inside it you can read dialog.message(), then call dialog.accept() (optionally with prompt text) or dialog.dismiss().
Order matters. The listener has to exist before the click, because the dialog appears during the click.
The fragile version
await page.getByRole('button', { name: 'Delete' }).click();
page.on('dialog', d => d.accept());Why it breaks: The listener is attached after the dialog has already opened and been auto-dismissed, so the deletion is cancelled and the test checks the wrong outcome.
A robust Playwright version
page.once('dialog', async dialog => {
expect(dialog.message()).toContain('Are you sure');
await dialog.accept();
});
await page.getByRole('button', { name: 'Delete' }).click();
await expect(page.getByText('Item deleted')).toBeVisible();The listener is ready first, handles exactly one dialog, and the test asserts the result of accepting it.
This is a general example on a made-up page, not the challenge’s reference solution.
Common mistakes
- Registering the listener after the triggering action.
- Using
page.onwhen you mean one dialog;page.onceavoids handling later dialogs by surprise. - Forgetting to accept or dismiss inside a listener, which leaves the page stuck.
FAQ
Does Playwright handle alerts automatically?
Yes, it auto-dismisses them when there is no dialog listener.
How do I type into a prompt()?
await dialog.accept('your text').
How do I read the alert text?
Call dialog.message() inside the listener.
Try it
Practise this in Challenge 14. You write the code in the browser editor with no setup. It runs in a fresh Chromium, a hidden validator checks what actually happened, and you get pass or fail, the logs and a video of the run. Create a free account to open the practice page and its hints. The reference solution and the hidden validator are shown only after you pass. We never publish solutions here.