How to check if an alert exists using WebDriver?


We can check if an alert exists with Selenium webdriver. An alert is created with the help of Javascript. We shall use the explicit wait concept in synchronization to verify the presence of an alert.

Let us consider the below alert and check its presence on the page. There is a condition called alertIsPresent which we will use to check for alerts. It shall wait for a specified amount of time for the alert after which it shall throw an exception.

We need to import org.openqa.selenium.support.ui.ExpectedConditions and import org.openqa.selenium.support.ui.WebDriverWait to incorporate expected conditions and WebDriverWait class.

Example

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.concurrent.TimeUnit;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.openqa.selenium.support.ui.ExpectedConditions;

public class VerifyAlert{
   public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","C:\Users\ghs6kor\Desktop\Java\chromedriver.exe");
      WebDriver driver = new ChromeDriver();
      String u ="https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm"driver.get(u);
      driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
      // identify and click submit
      WebElement t = driver.findElement(By.name("submit"));
      t.click();
      // Explicit wait condition for alert
      WebDriverWait w = new WebDriverWait(driver, 5);
      //alertIsPresent() condition applied
      if(w.until(ExpectedConditions.alertIsPresent())==null)
      System.out.println("Alert not exists");
      else
      System.out.println("Alert exists");
      driver.close();
   }
}

Output

Updated on: 18-Sep-2020

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements