3

Suppose there are five Browser windows opened, how to find the third one and close it through web driver? Please I'm request you to all of you don't consider this question as a opinion based. I have this situation while working with my current project. There are number of windows gets opened while performing purchase section activity.

I have to close selected number of windows. What should I do using WebDriver?

3
  • Do they have different titles?
    – Embedded
    Commented May 10, 2016 at 7:47
  • yes, most of the windows have different Titles.
    – Bharat Mane
    Commented May 10, 2016 at 8:54
  • 2
    The select that window by title and close it.
    – Embedded
    Commented May 10, 2016 at 10:21

2 Answers 2

1

I have a solution which I had used on IE(never tried on other browser). Suppose you have 5 IE windows opened, perform the iterator on all the windows and save the window iterators in a variable which will be an Array:

String parentWinHandle = driver.getWindowHandle();
//Click the button or link which populates the window
driver.findElement(By.id(actionBtn)).click();
Thread.sleep(5000);
Set<?> popupHandles = driver.getWindowHandles();
//SOP *popupHandles* 
Iterator<?> iterator = popupHandles.iterator();
while(iterator.hasNext())
    {
    String popupHandle = iterator.next().toString();
    if(!popupHandle.contains(parentWinHandle)) {
        driver.switchTo().window(popupHandle);
        Thread.sleep(3000);
        //Perform the operation you want to do
        driver.switchTo().window(parentWinHandle);
    }
}

Now pass the array index value to perform the close operation.

1
  • Good one...will try in my project..
    – Bharat Mane
    Commented Jan 11, 2017 at 6:30
2

You can use the below code:

List<String> handles = (List<String>) driver.getWindowHandles();
// Switch to the third window.
driver.switchTo().window(handles .get(2));
// Close this window
driver.close()
2
  • 1
    Why do you initialize thirdWindow? You never use it.
    – Embedded
    Commented May 10, 2016 at 10:20
  • Sorry my mistake. Removed it. Commented May 10, 2016 at 10:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.