How to check if an alert exists using WebDriver?
Asked Answered
E

10

91

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.

Easiness answered 13/7, 2012 at 9:12 Comment(0)
W
94
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

Whopper answered 13/7, 2012 at 9:22 Comment(5)
In the link you can see hos to accept or dismiss the alert windowBordereau
The slightly wrong answer below and the one on #8245223 are a much better way to do that. The try/catch model, as well as being clunky, logs a message about there not being an alert.Mangan
ExpectedConditions.alertIsPresent() gives you exactly the same thing, but in a nicer way and in just one line :)Erickericka
ExpectedConditions doesn't save much more code then the simple try catch.Desegregate
One issue with this approach is that while checking to see if the alert exists, the context has been switched to the alert. This might be problematic if you aren't expecting it.Preterhuman
S
31

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);
}
Showker answered 16/6, 2015 at 22:4 Comment(1)
Thank you. This should be the answer b/c the other solutions do not address exceptions.Anaclitic
E
13

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");
Erickericka answered 16/7, 2012 at 2:58 Comment(4)
add a ".apply(driver)" after the "alertIsPresent()" or do it properly and use waitMangan
I find that this throws a TimeoutException.Stefaniastefanie
TimeoutException when expected condition was not met in given timeout. Was Alert present at all?Erickericka
@Erickericka links are brokenNeolamarckism
S
9

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

Sinewy answered 12/8, 2013 at 8:21 Comment(3)
When I call a C# implementation of your function, it throws the exception, but it also closes the alert.Oldfashioned
despite that it also closes the alert, so far I found that this approach is fastest when dealing with alert detection, even faster than ExpectedConditions.alertIsPresentCormophyte
The main problem with this approach is it eating the alert. When alert is not there driver.switchTo().alert() it taking around 6-10 ms in FF 62Pistil
S
8

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.

Stefaniastefanie answered 16/7, 2015 at 11:34 Comment(1)
Another note: In C#, this is the WebDriverTimeoutException. I suppose that is because there is a System.TimeoutException class that could have easily gotten mixed up with that.Luana
P
3

ExpectedConditions is obsolete, so:

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

C# Selenium 'ExpectedConditions is obsolete'

Patton answered 19/6, 2018 at 17:9 Comment(1)
I wish they would add an option to the DefaultWait, so we can disable the Exception on a Timeout event. I had to make my own override of this class, so I can disable it, otherwise I have to put yet another Try/Catch block around the await and it's just soo many try/catchs everywhere, already, didn't want to add one more just to silence the timeout, also it slows down the bot with the Throw.Zygophyllaceous
T
2
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;
      }
}
Tuneful answered 19/3, 2018 at 14:33 Comment(0)
S
2

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");
    }
    }
Shaughn answered 17/4, 2018 at 10:40 Comment(0)
A
1

public boolean isAlertPresent() {

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

}

Audun answered 17/12, 2017 at 5:21 Comment(1)
Add some more detailed description.Arlinda
S
0

i tried both methods and both worked, but I encountered another error because of my usage driver.manage.window.setPosition Somehow this method is interrupting the alert. When I disable this, alert works as expected and the methods below work as well.

      try{
          driver.switchTo().alert();
          return true;
      }catch(NoAlertPresentException ex){
          return false;
      }
}

---OR---

public void verifyAlertIsDisplayed(){
        WebDriverWait wait=new WebDriverWait(Driver.get(),3);
        Alert alert= wait.until(ExpectedConditions.alertIsPresent());
        if (alert != null){
            Assert.assertTrue(true);
        }else{
            Assert.fail();
        }
    }
Shoulder answered 23/1, 2024 at 14:23 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.