Alerts
Simple alert, an alert after 5 seconds, a confirm box and a prompt – the four JavaScript dialogs you must know how to handle.
Practice tasks
- Click the first button, switch to the alert and accept it.
- Click the timer button, wait for the alert with an explicit wait, then accept it.
- Accept the confirm box and assert the result reads
You selected Ok. - Dismiss the confirm box and assert the result reads
You selected Cancel. - Type your name in the prompt and assert the result shows it.
- Dismiss the prompt and assert the result says it was cancelled.
Sample automation code
driver.findElement(By.id("alert-button")).click();
driver.switchTo().alert().accept();
driver.findElement(By.id("timer-alert-button")).click();
new WebDriverWait(driver, Duration.ofSeconds(10)).until(ExpectedConditions.alertIsPresent());
driver.switchTo().alert().accept();
driver.findElement(By.id("confirm-button")).click();
driver.switchTo().alert().dismiss();
Assert.assertEquals(driver.findElement(By.id("confirm-result")).getText(), "You selected Cancel");
driver.findElement(By.id("prompt-button")).click();
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("Karthik");
prompt.accept();
page.on('dialog', d => d.accept()); // accept everything
await page.getByTestId('alert').click();
page.once('dialog', d => d.dismiss()); // dismiss just the next one
await page.getByTestId('confirm').click();
await expect(page.getByTestId('confirm-result')).toHaveText('You selected Cancel');
page.once('dialog', d => d.accept('Karthik'));
await page.getByTestId('prompt').click();
await expect(page.getByTestId('prompt-result')).toContainText('Karthik');