How to check if an alert exists using WebDriver?

后端 未结 9 1703
名媛妹妹
名媛妹妹 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:12

    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.

    0 讨论(0)
  • 2020-12-01 09:17

    public boolean isAlertPresent() {

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

    }

    0 讨论(0)
  • 2020-12-01 09:27

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

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

    ExpectedConditions is obsolete, so:

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

    C# Selenium 'ExpectedConditions is obsolete'

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