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();
Note: If you try to call findElement() or interact with any page element while a native alert is open, Selenium throws an UnhandledAlertException. You must handle the alert (accept, dismiss, or read it) before doing anything else on the page.

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()

MethodEquivalent 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();
Note: Native browser alerts (alert(), confirm(), prompt()) are entirely different from custom HTML modal popups — a <div class="modal"> that many sites build to look like a dialog box. A custom modal is just a regular element sitting in the DOM; you interact with its buttons using ordinary findElement().click() calls, exactly like anything else on the page. switchTo().alert() is only for the browser's own native dialogs.
Next: RecipeBox's recipe detail page also embeds a nutrition-info <iframe> — see how to work with it in Handling Frames.