Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 979
rajesh paripelly Avatar asked Oct 22 '25 05:10

rajesh paripelly


1 Answers

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));
like image 101
Muzzamil Avatar answered Oct 26 '25 03:10

Muzzamil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!