Search code examples
c#winformsselenium-webdriverwebdriverselenium-chromedriver

How to Wait for an Alert in Selenium WebDriver with C#?


How can i set Selenium WebDriver to Wait for an Alert before accepting it instead of Thread.Sleep?

As website, sometimes loads very slowly or sometimes fast.

Thanks


Solution

  • You should apply webdriver wait for an alert to be present properly.

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

    OR write a boolean function to check alert present and use it for wait

    bool IsAlertShown(WebDriver driver) {
        try {
            driver.SwitchTo().Alert();
        } catch(NoAlertPresentException e) {
            return false;
        }
        return true;
    }
    

    Use it as below

    var wait = new WebDriverWait(driver, TimeSpan.FromSeconds(20));
    wait.Until(driver => IsAlertShown(driver));