Handling Alerts & Popups
Click "Delete" on a recipe card in RecipeBox and the browser throws up a native JavaScript confirm() dialog: "Are you sure you want to delete this recipe?" with OK and Cancel buttons. This is not a regular HTML element — you can't findElement() your way into it. It's rendered by the browser itself, and Selenium has a completely separate API for it: driver.switchTo().alert().
Switching to the Alert
driver.findElement(By.xpath("//button[@class='delete-btn']")).click();
// The confirm() dialog is now open - grab a handle to it
Alert deleteAlert = driver.switchTo().alert();
getText()
Reads the message displayed inside the dialog — useful for asserting the right confirmation text appeared.
String message = deleteAlert.getText();
System.out.println("Alert says: " + message);
// Expected: "Are you sure you want to delete this recipe?"
accept() and dismiss()
| Method | Equivalent to |
|---|---|
| accept() | Clicking OK — confirms the action (here, deletes the recipe). |
| dismiss() | Clicking Cancel (or the X) — backs out, recipe stays. |
// Confirm the delete
deleteAlert.accept();
// ...or back out instead
// deleteAlert.dismiss();
Full Worked Example: Deleting a Recipe
WebElement deleteBtn = driver.findElement(By.xpath(
"//h3[contains(text(),'Paneer')]/following-sibling::button[@class='delete-btn']"));
deleteBtn.click();
Alert deleteAlert = driver.switchTo().alert();
System.out.println("Confirm message: " + deleteAlert.getText());
deleteAlert.accept(); // clicks OK, recipe gets deleted
// Back on the main page now - verify the recipe is gone
List<WebElement> remaining = driver.findElements(By.xpath("//h3[contains(text(),'Paneer')]"));
System.out.println("Recipes still matching 'Paneer': " + remaining.size()); // expect 0
sendKeys() for a Prompt
If a dialog is a JS prompt() instead of a confirm() (it asks for text input, not just OK/Cancel), the same Alert object also supports typing into it before accepting:
Alert renamePrompt = driver.switchTo().alert();
renamePrompt.sendKeys("Paneer Tikka Masala");
renamePrompt.accept();