1

How to handle multiple alert popup confirmation in selenium. E.g: If accepting popup window, it's asking again and again for the same window. and if that popup closed after clicking 5th time confirmation/dismiss how can we handle the same.

So please help me on this...

2 Answers2

1

If you know the exact number of times this alert will pop up, you can use a simple loop with a hard coded number of retries. For example:

int retries = 5;

while (retries > 0) {
    alertTriggerButton.click();

     Alert alert = driver.switchTo().alert();
     alert.accept();

    retries--;

}

You should amend this code to make sure it works according to your page behavior so thinks like response times are taken into account (in other words - add relevant wait times if required).

Eugene S
  • 6,709
  • 8
  • 57
  • 91
1

You can use while. You're checking if the alert is present, and each time it is there, you resolve it according to that boolean value that you give it. When there is no new alert anymore, it will break and continue on.

public static void resolveAllAlerts(WebDriver driver, int timeout, boolean accept) {
    while (isAlertPresent(driver, timeout)) {
        resolveAlert(driver, accept);
    }
}


private static boolean isAlertPresent(WebDriver driver, int timeout) {
    try {
        Alert a = new WebDriverWait(driver, timeout).until(ExpectedConditions.alertIsPresent());
        if (a != null) {
            return true;
        } else {
            throw new TimeoutException();
        }
    } catch (TimeoutException e) {
        // log the exception;
        return false;
    }
}

private static void resolveAlert(WebDriver driver, boolean accept) {
    if (accept) {
        driver.switchTo().alert().accept();
    } else {
        driver.switchTo().alert().dismiss();
    }
}
StopTheRain
  • 367
  • 1
  • 5
  • 15