Sree
Sree

Reputation: 15

Implementing 'waitForNewWindow' in selenium webdriver

I am trying to implement a method 'waitForNewWindow' in Java using selenium WebDriver. This method is all about waiting to check if a new window is opened. If a new window is opened in the specified time, i need to return true, else return false.

public boolean waitForNewWindow(String target) {

    try {

        Thread.sleep(30000);
        if(driver.switchTo().window(target)!=null) {
            log.info("New window is opened");
            return true;
        }


    }catch(Exception e) {
        log.debug(e);
        return false;
    }
    return true;
}

But here, I don't want to use thread.sleep(time). The waiting time needs to be specified as below:

WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);

Moreover, in the above code, the control is switching to the new window, which is not expected. Can someone please provide your answers on how to implement my requirement?

Upvotes: 0

Views: 329

Answers (3)

Sree
Sree

Reputation: 15

Finally got the implementation of waitForNewWindow method, using the WebDriverWait object as below:

   try {
    ExpectedCondition<Boolean> e = new ExpectedCondition<Boolean>() {
      public Boolean apply(WebDriver wd) {
        if (wd.switchTo().window(newTarget) != null) {
            log.info("New window is opened with the window id : "
                            + newTarget);
            driver.switchTo().window(parentHandle);
            return true;
        } else {
            return false;
        }

      }
    };
    WebDriverWait wait = new WebDriverWait(driver, TIMEOUT);

       if (wait.until(e)) {
        log.info("the wait for the expected condition is successful");
                    return true;
       }

   } catch (Exception e1) {
    log.debug(e1);
    return false;
   }

Tested the same and its working fine.

Upvotes: 0

pavanraju
pavanraju

Reputation: 673

the below mentioned code checks for the number of windows to appear with time out

public void waitForNumberOfWindows(final int length){
    new WebDriverWait(driver, 30) {
    }.until(new ExpectedCondition<Boolean>() {
        public Boolean apply(WebDriver driver) {
            return driver.getWindowHandle().length()==length;
        }
    });
}

it will check for the expected number of windows to be present at that instance and will return true if the count matches with in the specified timeout(30 in above code)

Upvotes: 1

A Paul
A Paul

Reputation: 8271

You can not specify a timeout like you want. You have to use Thread.sleep().

Regarding your control moving to new window because of your below line the control is moving to new tab

driver.switchTo().window(target)

If you want to simply check if there is two windows open or not, you can write something like below

while( driver.getWindowHandle().length() != 2){
    Thread.sleep(2000);
}

Upvotes: 0

Related Questions