Alerts, confirms, prompts and modals
BeginnerBrowser alert, confirm and prompt dialogs, a toast that disappears, and an in-page modal dialog.
Practice area
Confirm result:
Prompt result:
Tasks to automate
- Click the alert button, read the alert text, accept it.
- Click the confirm button and dismiss it; assert the page says Cancelled. Repeat and accept.
- Click the prompt button, type your name, accept; assert the page greets you by name.
- Click the toast button and assert the toast appears, then disappears within 5 seconds.
- Open the modal, assert its title, close it with the Escape key and with the button.
Model solutions
Try the tasks first. These show one good way, not the only way.
Selenium (Java)
driver.findElement(By.id("pg-confirm-btn")).click();
Alert confirm = new WebDriverWait(driver, Duration.ofSeconds(5)).until(ExpectedConditions.alertIsPresent());
confirm.dismiss();
assertEquals("Cancelled", driver.findElement(By.id("pg-confirm-result")).getText());
driver.findElement(By.id("pg-prompt-btn")).click();
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("Asha");
prompt.accept();
// Toast: wait for it to appear, then to go away
WebDriverWait wait = new WebDriverWait(driver, Duration.ofSeconds(6));
driver.findElement(By.id("pg-toast-btn")).click();
wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("pg-toast")));
wait.until(ExpectedConditions.invisibilityOfElementLocated(By.id("pg-toast")));
Playwright (TypeScript)
// Register the dialog handler BEFORE the click that triggers it
page.once('dialog', (d) => d.dismiss());
await page.locator('#pg-confirm-btn').click();
await expect(page.locator('#pg-confirm-result')).toHaveText('Cancelled');
page.once('dialog', (d) => d.accept('Asha'));
await page.locator('#pg-prompt-btn').click();
await expect(page.locator('#pg-prompt-result')).toContainText('Asha');
await page.locator('#pg-toast-btn').click();
await expect(page.locator('#pg-toast')).toBeVisible();
await expect(page.locator('#pg-toast')).toBeHidden({ timeout: 6000 });
Element IDs on this page are stable and will not change. Nothing you do here is sent to a server.
