plaidshirt
plaidshirt

Reputation: 5671

WebDriver to close popup window after certain time

I have a Selenium WebDriver based test, which fill a form and send it for processing. During time period of processing a window is opened. Sometimes processing fails, but this window is not closed, so we can't get result. Purpose of this test is to get the result. I try to set a timeout for this window, so it should be closed after a predefined time (I set it to 10 seconds now.) by WebDriver and form should be resent. I use following code.

WebElement webElement;
try {
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    driver.findElement(sendButton).click();
    webElement = wait.until(ExpectedConditions.presenceOfElementLocated(By.className("button-resultdown")));
} catch (TimeoutException ex) {
    webElement = null;
} finally {
    driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
if (webElement == null) {
    driver.findElement(popUpClose).click();
    TimeUnit.SECONDS.sleep(4);
    driver.findElement(sendButton).click();
}

Popup window is not closed automatically after 10 seconds. I checked element locators, those are valid.

Upvotes: 0

Views: 607

Answers (1)

Sers
Sers

Reputation: 12255

Best practice is to not use explicit and implicit waits in same time, find more details here.
For popup close you can try to click using JavaScript or wait until popUpClose will be clickable.

JavascriptExecutor js = (JavascriptExecutor) driver;

driver.findElement(sendButton).click();

List<WebElement> elements = waitElements(driver, 5, By.className("button-resultdown"));
if (elements.size() == 0){
    List<WebElement> popUpCloseButtons = driver.findElements(popUpClose);
    System.out.println("Popup Close Buttons size: " + popUpCloseButtons.size());
    if (popUpCloseButtons.size() > 0)
        js.executeScript("arguments[0].click();", popUpCloseButtons.get(popUpCloseButtons.size() - 1));
        //popUpCloseButtons.get(popUpCloseButtons.size() - 1).click();
}

And custom wait method:

public List<WebElement> waitElements(WebDriver driver, int timeout, By locator) throws InterruptedException {
    List<WebElement> elements = new ArrayList<>();
    for (int i = 0; i < timeout; i++) {
        elements = driver.findElements(locator);
        if (elements.size() > 0)
            break;

        System.out.println("Not!");
        Thread.sleep(1000);
    }

    return elements;
}

Upvotes: 2

Related Questions