About this lesson
Handle a confirm alert in Selenium Java: accept() for OK, dismiss() for Cancel
Learn Selenium JavaIntermediateAlerts & Popups
How it works
A confirm dialog, from JavaScript's confirm(), asks a yes or no question and returns the answer to the page. In Selenium both answers go through the same Alert: accept() presses OK and dismiss() presses Cancel.
Unlike a simple alert, the choice changes what the page does next. On the Alerts page the answer is written into the confirmResult paragraph, so the test can check that the page reacted to OK or to Cancel, not only that a dialog appeared.
A confirm has no text box. Calling sendKeys() on it throws ElementNotInteractableException with "User dialog does not have a text box input field".
About the assignment
Clicking the confirm button asks whether you want to proceed. You read the question, answer OK, and then read the page's result paragraph to see the answer it recorded.
What you will do
- Click the confirm button, which you locate by its label.
- Switch to the alert, keep its text, and accept it.
- Print the stored question after the label
Alert text:. - Read
confirmResultfrom the page and print its text after the labelResult:.
Common mistakes
Calling dismiss() by habit
Cancel writes a different result into
confirmResult, so the second line no longer matches.Reading the result before answering
The page is blocked while the dialog is open. Finding
confirmResultfirst throwsUnhandledAlertException.Asserting only the dialog text
The dialog proves the question was asked. The result paragraph proves the page acted on the answer, which is the part that matters to users.
In a real test suite
Delete buttons and "leave without saving" flows often use confirms. Good tests cover both branches: Cancel keeps the record, OK removes it.
Lesson 40 handled a simple alert. Lesson 42 adds a text box to the dialog with a prompt.
Related lessons
- Handle Simple AlertThe basic alert switch, read and accept.
- Handle Prompt AlertPrompts, which take typed input before OK.
- Get Element Text with getText()Read the result paragraph with
getText().
To try one of these calls on any page without a task, open the Online Selenium Java Compiler.
Starter code
The editor above opens with this code. Fill in the TODO lines, then run and submit it.
import org.openqa.selenium.*;
import org.openqa.selenium.chrome.ChromeDriver;
public class Main {
public static void main(String[] args) throws Exception {
WebDriver driver = new ChromeDriver();
driver.get("https://testkru.com/Interactions/Alerts");
// TODO: Click "Show Confirm" button
// TODO: Get alert text, then accept
// TODO: Print alert text and the result from confirmResult element
driver.quit();
}
}