[selenium] How to check if an alert exists using WebDriver?

I need to check the existence of Alert in WebDriver.

Sometimes it pops up an alert but sometimes it will not pop up. I need to check if the alert exists first, then I can accept or dismiss it or it will say: no alert found.

This question is related to selenium webdriver alert

The answer is


The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait object.

boolean isDialogPresent(WebDriver driver) {
    IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
    return (alert != null);
}

I found catching exception of driver.switchTo().alert(); is so slow in Firefox (FF V20 & selenium-java-2.32.0).`

So I choose another way:

    private static boolean isDialogPresent(WebDriver driver) {
        try {
            driver.getTitle();
            return false;
        } catch (UnhandledAlertException e) {
            // Modal dialog showed
            return true;
        }
    }

And it's a better way when most of your test cases is NO dialog present (throwing exception is expensive).


I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

WebDriverWait wait = new WebDriverWait(driver, 300 /*timeout in seconds*/);
if(wait.until(ExpectedConditions.alertIsPresent())==null)
    System.out.println("alert was not present");
else
    System.out.println("alert was present");

ExpectedConditions is obsolete, so:

        WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(15));
        wait.Until(SeleniumExtras.WaitHelpers.ExpectedConditions.AlertIsPresent());

C# Selenium 'ExpectedConditions is obsolete'


I would suggest to use ExpectedConditions and alertIsPresent(). ExpectedConditions is a wrapper class that implements useful conditions defined in ExpectedCondition interface.

public boolean isAlertPresent(){
    boolean foundAlert = false;
    WebDriverWait wait = new WebDriverWait(driver, 0 /*timeout in seconds*/);
    try {
        wait.until(ExpectedConditions.alertIsPresent());
        foundAlert = true;
    } catch (TimeoutException eTO) {
        foundAlert = false;
    }
    return foundAlert;
}

Note: this is based on the answer by nilesh, but adapted to catch the TimeoutException which is thrown by the wait.until() method.


This code will check whether the alert is present or not.

public static void isAlertPresent(){
    try{
    Alert alert = driver.switchTo().alert();
    System.out.println(alert.getText()+" Alert is Displayed"); 
    }
    catch(NoAlertPresentException ex){
    System.out.println("Alert is NOT Displayed");
    }
    }

public boolean isAlertPresent() 
{ 
    try 
    { 
        driver.switchTo().alert(); 
        return true; 
    }   // try 
    catch (NoAlertPresentException Ex) 
    { 
        return false; 
    }   // catch 
}   // isAlertPresent()

check the link here https://groups.google.com/forum/?fromgroups#!topic/webdriver/1GaSXFK76zY


public static void handleAlert(){
    if(isAlertPresent()){
        Alert alert = driver.switchTo().alert();
        System.out.println(alert.getText());
        alert.accept();
    }
}
public static boolean isAlertPresent(){
      try{
          driver.switchTo().alert();
          return true;
      }catch(NoAlertPresentException ex){
          return false;
      }
}

public boolean isAlertPresent() {

try 
{ 
    driver.switchTo().alert(); 
    system.out.println(" Alert Present");
}  
catch (NoAlertPresentException e) 
{ 
    system.out.println("No Alert Present");
}    

}


Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception?

Examples related to webdriver

WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? ImportError: No module named 'selenium' how to use List<WebElement> webdriver How to get attribute of element from Selenium? Selenium Finding elements by class name in python Open web in new tab Selenium + Python When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly How can I start InternetExplorerDriver using Selenium WebDriver

Examples related to alert

Swift alert view with OK and Cancel: which button tapped? Bootstrap Alert Auto Close How to reload a page after the OK click on the Alert Page How to display an alert box from C# in ASP.NET? HTML - Alert Box when loading page How to show an alert box in PHP? Twitter Bootstrap alert message close and open again How to handle login pop up window using Selenium WebDriver? How to check if an alert exists using WebDriver? chrome undo the action of "prevent this page from creating additional dialogs"