Wednesday, February 4, 2015

How to handle alert and confirm boxes and avoid the Race Condition

Method 1
-----------
Alert alert = null;
Wait<WebDriver> wait = new WebDriverWait(driver, 10, 50);
try {
   alert = wait.until(ExpectedConditions.alertIsPresent());
} catch (TimeoutException ignored) {
}
if (alert != null) {
   alert.accept(); // this line throws the exception
}

Method 2
-------------

public void clickOkOnAlertDialog(String dialogText) {

        Sync sync = Sync.start(20);
        while (sync.continueWaiting()) {
            wait = new WebDriverWait(driver, pageTimeoutInSeconds);
            wait.until(ExpectedConditions.alertIsPresent());
            Alert statusConfirm = driver.switchTo().alert();
            junit.framework.Assert.assertEquals(dialogText, statusConfirm.getText());
            try {
                statusConfirm.accept();
                return;
            } catch (WebDriverException e) {
                sync.sleep(250);
            }
        }
        throw new TimeoutException("Unable to locate and dismiss alert dialog: " + dialogText);
    }
   
Method 3 (Not a good way though)
-----------

((JavascriptExecutor) driver).executeScript("window.alert = function(msg){};");
((JavascriptExecutor) driver).executeScript("window.confirm = function(msg){return true;};");

How FirefoxDriver opens Firefox Browser 
A beta features which makes Firefox Faster 
Enable Firebug in Session started by FirefoxDriver 
How FirefoxDriver Executes the Selenium Commands 

1 comment:

  1. i have gone through your article and understood about handling of alert boxes. need of bit explanation and clarify the situation needed to use this condition.Thank you for sharing. for best selenium training Best selenium training institute in chennai

    ReplyDelete