Selenium + Java · Lesson 20 of 44

0/44 done

Module 20: Alerts & Popups

20. Handling JavaScript Alerts, Confirms & Prompt Dialogs

15 minlesson

Your task

Implement acceptAlertAndGetText:

  1. Accept WebDriver driver.
  2. Switch to alert, store getText(), call accept(), and return the text.

Write it in the editor, then press Check answer (Ctrl + Enter).

Handling Native JavaScript Alerts

java
import org.openqa.selenium.Alert;

// Simple Alert (OK only):
Alert simpleAlert = driver.switchTo().alert();
System.out.println("Alert text: " + simpleAlert.getText());
simpleAlert.accept();

// Confirm Dialog (OK / Cancel):
Alert confirmDialog = driver.switchTo().alert();
confirmDialog.dismiss(); // Clicks Cancel

// Prompt Dialog (Input + OK / Cancel):
Alert prompt = driver.switchTo().alert();
prompt.sendKeys("QA Confirmation");
prompt.accept();

Key Takeaways & Walkthrough Summary

Browser JavaScript dialogs block DOM execution until the user accepts or dismisses them. In this lesson, you will master the Alert interface: accept, dismiss, getText, and sendKeys for prompt dialogs. Let's handle alerts!

Part of the Selenium + Java course (Selenium with Java). Practice this concept live in the Selenium Online Compiler or explore our free automation practice form.

Common Doubts & Lesson Q&A

What happens if I call driver.switchTo().alert() when no alert is present?

It throws NoAlertPresentException. Always use WebDriverWait with ExpectedConditions.alertIsPresent() before switching.

Ready? Solve the task in the editor

Use Check answer to mark it complete. Hints are there if you need them.

Java
Skip