How to check if an alert exists using WebDriver?

后端 未结 9 1704
名媛妹妹
名媛妹妹 2020-12-01 09:09

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

相关标签:
9条回答
  • 2020-12-01 09:33

    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");
    
    0 讨论(0)
  • 2020-12-01 09:33

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

    0 讨论(0)
  • 2020-12-01 09:37
    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

    0 讨论(0)
提交回复
热议问题