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?

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

2 Answers 2


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
Set<?> popupHandles = driver.getWindowHandles();
//SOP *popupHandles* 
Iterator<?> iterator = popupHandles.iterator();
    String popupHandle = iterator.next().toString();
    if(!popupHandle.contains(parentWinHandle)) {
        //Perform the operation you want to do

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

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

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
  • 1
    Why do you initialize thirdWindow? You never use it.
    – Embedded
    May 10, 2016 at 10:20
  • Sorry my mistake. Removed it. 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.