Popular Searches
Popular Course Categories
Popular Courses

Window Handles

Handling Browser Components

Window Handles in Selenium WebDriver

Window Handles are one of the most important concepts for handling multiple browser tabs and windows in Selenium WebDriver. When a web application opens a new tab or browser window, Selenium identifies each browser context using a unique window handle.

Selenium WebDriver does not make a functional distinction between a browser tab and a browser window for window-handle operations. Each browser context has a unique identifier that can be retrieved and used to switch Selenium's focus from one context to another.

For complete Selenium WebDriver learning, Java, TestNG, automation frameworks, real-time projects, and advanced browser automation concepts, visit JustAcademy Selenium Training and Register for Selenium Course Demo.


1. What Is a Window Handle?

A window handle is a unique identifier assigned to a browser window or tab within a Selenium WebDriver session. Selenium uses this identifier to determine which browser context should receive commands.

The current window handle can be retrieved using:

String windowHandle = driver.getWindowHandle();

The handle is specific to the current WebDriver session and is used when switching between browser contexts. A window handle should be treated as an opaque identifier rather than something whose actual value has business meaning.


2. Why Are Window Handles Required?

When a user clicks a link that opens another tab or window, Selenium must switch to the corresponding browser context before interacting with elements inside it.

Main Window

     |

     | Click link

     v

New Window / Tab Opens

     |

     v

Get Window Handles

     |

     v

Identify Required Handle

     |

     v

Switch to Window

     |

     v

Interact with Elements


3. Basic Window Handle Concept

Suppose a test starts with one browser window and then opens two additional tabs.

Browser Session

|

|-- Main Window

|     Handle A

|

|-- New Tab

|     Handle B

|

|-- New Tab

      Handle C

Selenium can retrieve all available handles and switch between them as required.


4. getWindowHandle()

The getWindowHandle() method returns the handle of the currently active browser window or tab.

String currentWindow = driver.getWindowHandle();

 

System.out.println(

    "Current Window Handle: " + currentWindow);

This method is particularly useful when you want to remember the original browser context before opening another window.


5. Storing the Parent Window Handle

A common Selenium pattern is to store the original window handle before performing an action that opens another browser context.

String parentWindow = driver.getWindowHandle();

Later, the same handle can be used to return to the original page:

driver.switchTo().window(parentWindow);


6. getWindowHandles()

The getWindowHandles() method returns a collection containing the handles of all browser windows or tabs currently available in the WebDriver session. In Java, its return type is Set<String>.

Set<String> allWindows =

    driver.getWindowHandles();

This method is used when an application has multiple tabs or windows and the test needs to identify a particular browser context.


7. getWindowHandle() vs getWindowHandles()

MethodPurposeReturn Type in Java
getWindowHandle()Returns the handle of the current browser contextString
getWindowHandles()Returns handles of all browser contexts in the sessionSet<String>


8. Window Handle and Window Handles

ConceptMeaning
Window HandleIdentifier of one browser window or tab
Window HandlesCollection of identifiers for all available browser windows or tabs
Current HandleIdentifier of the browser context currently controlled by WebDriver


9. Switching Using a Window Handle

After obtaining a handle, Selenium can switch to the corresponding browser context using:

driver.switchTo().window(windowHandle);

For example:

String parentWindow =

    driver.getWindowHandle();

 

Set<String> windows =

    driver.getWindowHandles();

 

for (String window : windows) {

    if (!window.equals(parentWindow)) {

        driver.switchTo().window(window);

        break;

    }

}


10. Basic Window Handle Workflow

Start Test

    |

    v

Open Main Page

    |

    v

Store Current Window Handle

    |

    v

Click Link / Button

    |

    v

New Window Opens

    |

    v

Get All Window Handles

    |

    v

Find Required Handle

    |

    v

Switch to Required Window

    |

    v

Perform Test Actions

    |

    v

Switch Back to Parent

    |

    v

Continue Test


11. Complete Basic Example

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

 

public class WindowHandleExample {

 

    public static void main(String[] args) {

 

        WebDriver driver = new ChromeDriver();

 

        driver.get("https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        driver.findElement(

            By.id("openWindow")).click();

 

        Set<String> allWindows =

            driver.getWindowHandles();

 

        for (String window : allWindows) {

 

            if (!window.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(window);

 

                System.out.println(

                    "Child Title: " +

                    driver.getTitle());

 

                break;

            }

        }

 

        driver.switchTo()

              .window(parentWindow);

 

        driver.quit();

    }

}


12. How Window Handles Work

The overall process can be represented as:

Browser Context 1

      |

      | getWindowHandle()

      v

Parent Handle

      |

      | Open New Tab

      v

Browser Context 2

      |

      | getWindowHandles()

      v

Set of Handles

      |

      | Identify Child Handle

      v

Child Handle

      |

      | switchTo().window()

      v

Child Browser Context


13. Handling Two Windows

A very common automation scenario consists of one parent window and one newly opened child window.

Parent Window

    |

    |-- Handle A

    |

    +----> Child Window

             Handle B

Example:

String parent =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("openChild")).click();

 

for (String handle :

        driver.getWindowHandles()) {

 

    if (!handle.equals(parent)) {

 

        driver.switchTo()

              .window(handle);

 

        break;

    }

}


14. Handling Multiple Windows

If an application opens several windows or tabs, Selenium can retrieve all available handles and iterate through them.

Set<String> handles =

    driver.getWindowHandles();

 

for (String handle : handles) {

 

    driver.switchTo()

          .window(handle);

 

    System.out.println(

        "Handle: " + handle);

 

    System.out.println(

        "Title: " + driver.getTitle());

 

    System.out.println(

        "URL: " + driver.getCurrentUrl());

}


15. Identifying a Window by Title

Window handles themselves are normally opaque identifiers. A practical approach is to switch through the handles and identify the required window using its title.

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getTitle()

            .contains("Reports")) {

 

        System.out.println(

            "Reports Window Found");

 

        break;

    }

}


16. Identifying a Window by URL

The current URL can also be used to identify the required browser context.

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getCurrentUrl()

            .contains("checkout")) {

 

        System.out.println(

            "Checkout Window Found");

 

        break;

    }

}


17. Identifying a Window by a Unique Element

Sometimes multiple windows have similar titles or URLs. In that situation, a unique element can be used to identify the required page.

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (!driver.findElements(

            By.id("reportTable")).isEmpty()) {

 

        System.out.println(

            "Report Window Found");

 

        break;

    }

}


18. Using Iterator with Window Handles

An Iterator can be used to access window handles one by one.

Set<String> handles =

    driver.getWindowHandles();

 

Iterator<String> iterator =

    handles.iterator();

 

String parentWindow =

    iterator.next();

 

String childWindow =

    iterator.next();

 

driver.switchTo()

      .window(childWindow);

This can be convenient for a simple two-window example. For more robust automation, identifying the required window using title, URL, or page-specific information is generally clearer.


19. Using Java Stream with Window Handles

Java Streams provide another way to find a handle that is different from the parent handle.

String parentWindow =

    driver.getWindowHandle();

 

String childWindow =

    driver.getWindowHandles()

          .stream()

          .filter(handle ->

              !handle.equals(parentWindow))

          .findFirst()

          .orElseThrow();

 

driver.switchTo()

      .window(childWindow);


20. Finding a Newly Opened Window

When an application opens a new window, a useful approach is to remember the existing set of handles before the action and compare it with the handles after the new context appears.

Set<String> oldWindows =

    driver.getWindowHandles();

 

driver.findElement(

    By.id("openWindow")).click();

 

Set<String> newWindows =

    driver.getWindowHandles();

 

newWindows.removeAll(oldWindows);

 

String newWindow =

    newWindows.iterator().next();

 

driver.switchTo()

      .window(newWindow);


21. Waiting for a New Window Handle

Modern applications may create a new browser context asynchronously. Therefore, the test should wait for the expected number of windows before attempting to switch.

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > 1);

Condition-based synchronization helps ensure that the test does not attempt to switch before the additional browser context has appeared.


22. Complete Example with Explicit Wait

import java.time.Duration;

import java.util.Set;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WindowHandleWaitExample {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new ChromeDriver();

 

        driver.get("https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        driver.findElement(

            By.id("openWindow")).click();

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size() > 1);

 

        Set<String> windows =

            driver.getWindowHandles();

 

        for (String window :

                windows) {

 

            if (!window.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(window);

 

                System.out.println(

                    driver.getTitle());

 

                break;

            }

        }

 

        driver.switchTo()

              .window(parentWindow);

 

        driver.quit();

    }

}


23. Why Explicit Wait Is Useful

Without synchronization, the test may try to retrieve the new window handle before the browser has created the new context.

Instead of using an arbitrary delay:

Thread.sleep(5000);

Use a condition-based wait:

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > 1);

This allows the test to wait for the actual browser condition instead of always waiting for a fixed duration.


24. Window Handle with Selenium 4

Selenium 4 provides APIs for creating a new tab or window directly. When the new context is created using the Selenium API, WebDriver switches to it automatically.

Create a new tab:

driver.switchTo()

      .newWindow(WindowType.TAB);

Create a new browser window:

driver.switchTo()

      .newWindow(WindowType.WINDOW);


25. Creating a New Tab

import org.openqa.selenium.WindowType;

 

driver.get("https://example.com");

 

String parentWindow =

    driver.getWindowHandle();

 

driver.switchTo()

      .newWindow(WindowType.TAB);

 

driver.get("https://www.selenium.dev");

 

System.out.println(

    "New Tab: " +

    driver.getTitle());

 

driver.switchTo()

      .window(parentWindow);


26. Creating a New Window

driver.get("https://example.com");

 

String parentWindow =

    driver.getWindowHandle();

 

driver.switchTo()

      .newWindow(WindowType.WINDOW);

 

driver.get("https://www.selenium.dev");

 

System.out.println(

    "New Window: " +

    driver.getTitle());

 

driver.switchTo()

      .window(parentWindow);


27. Window Handles with Tabs

Even when the browser opens a new tab rather than a separate browser window, Selenium uses the same window-handle mechanism.

String current =

    driver.getWindowHandle();

 

Set<String> handles =

    driver.getWindowHandles();

This means the same switching technique can be used for tabs and windows.


28. Parent Handle and Child Handle

HandleMeaningExample Usage
Parent HandleOriginal browser contextReturn to main application
Child HandleNewly opened browser contextValidate child page
Other HandleAny additional browser contextSwitch to another tab/window


29. Switching Back to the Parent Window

After completing the actions in the child window, Selenium should switch back to the previously stored parent handle.

driver.switchTo()

      .window(parentWindow);

Example:

String parentWindow =

    driver.getWindowHandle();

 

// Open child and switch to child

 

// Perform child window actions

 

driver.switchTo()

      .window(parentWindow);

 

// Continue parent window test


30. Closing a Window

The close() method closes the currently selected browser tab or window.

driver.close();

After closing a child window, switch back to a valid remaining window handle before continuing.

driver.close();

 

driver.switchTo()

      .window(parentWindow);


31. close() vs quit()

MethodPurpose
close()Closes the currently selected tab or window
quit()Closes all browser windows and ends the WebDriver session

close()

driver.close();

quit()

driver.quit();


32. What Happens If You Do Not Switch After close()?

If the currently selected window is closed and the test attempts to continue using that closed context, Selenium can raise a NoSuchWindowException.

driver.switchTo()

      .window(childWindow);

 

driver.close();

 

// Do not continue using the closed window

 

driver.switchTo()

      .window(parentWindow);


33. Complete Parent-Child Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class ParentChildWindow {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new ChromeDriver();

 

        driver.get("https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        driver.findElement(

            By.id("openChild")).click();

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size() > 1);

 

        for (String handle :

                driver.getWindowHandles()) {

 

            if (!handle.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(handle);

 

                System.out.println(

                    "Child URL: " +

                    driver.getCurrentUrl());

 

                System.out.println(

                    "Child Title: " +

                    driver.getTitle());

 

                break;

            }

        }

 

        driver.switchTo()

              .window(parentWindow);

 

        System.out.println(

            "Returned to Parent");

 

        driver.quit();

    }

}


34. Handling Three or More Windows

Suppose the application has one main window and three additional tabs.

Main Window

    |

    |-- Handle A

    |

    |-- Handle B

    |

    |-- Handle C

    |

    |-- Handle D

The test can iterate through all handles:

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    System.out.println(

        "Title: " +

        driver.getTitle());

}


35. Finding a Specific Window Among Multiple Windows

String requiredTitle =

    "Selenium Documentation";

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getTitle()

            .equals(requiredTitle)) {

 

        System.out.println(

            "Required Window Found");

 

        break;

    }

}


36. Window Handle Based on URL

String requiredUrl =

    "selenium.dev";

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getCurrentUrl()

            .contains(requiredUrl)) {

 

        System.out.println(

            "Required Window Found");

 

        break;

    }

}


37. Window Handle Based on Page Element

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (!driver.findElements(

            By.id("uniqueElement"))

            .isEmpty()) {

 

        System.out.println(

            "Required Page Found");

 

        break;

    }

}


38. Counting Window Handles

The number of active browser contexts can be checked using the size of the returned collection.

int count =

    driver.getWindowHandles().size();

 

System.out.println(

    "Window Count: " + count);

This can be useful for synchronization and validation.


39. Verifying a New Window

int initialCount =

    driver.getWindowHandles().size();

 

driver.findElement(

    By.id("openWindow")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size()

        > initialCount);

 

System.out.println(

    "New Browser Context Opened");


40. Capturing All Window Handles

Set<String> handles =

    driver.getWindowHandles();

 

for (String handle : handles) {

 

    System.out.println(

        "Window Handle: " + handle);

}

The returned set can be iterated and an individual handle can then be passed to switchTo().window().


41. Printing Window Information

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    System.out.println(

        "Handle: " + handle);

 

    System.out.println(

        "Title: " +

        driver.getTitle());

 

    System.out.println(

        "URL: " +

        driver.getCurrentUrl());

 

    System.out.println(

        "-----------------------");

}


42. Window Handles in an E-Commerce Application

Suppose an e-commerce application opens a product comparison page in a new tab.

String productWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("compareProduct")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    if (!handle.equals(productWindow)) {

 

        driver.switchTo()

              .window(handle);

 

        System.out.println(

            "Comparison Page: " +

            driver.getTitle());

 

        break;

    }

}

 

driver.close();

 

driver.switchTo()

      .window(productWindow);


43. Window Handles in a Reporting Application

String mainWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("generateReport")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getCurrentUrl()

            .contains("report")) {

 

        System.out.println(

            "Report Window Found");

 

        break;

    }

}

 

driver.switchTo()

      .window(mainWindow);


44. Window Handles in a Support Portal

String mainWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("support")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getTitle()

            .contains("Support")) {

 

        System.out.println(

            "Support Window Found");

 

        break;

    }

}

 

driver.switchTo()

      .window(mainWindow);


45. Window Handles in External Test Services

Some test environments open an external service in another browser context. The automation can identify the context using a known test URL or page title.

String mainWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("externalService")).click();

 

new WebDriverWait(

    driver,

    Duration.ofSeconds(10))

    .until(d ->

        d.getWindowHandles().size() > 1);

 

for (String handle :

        driver.getWindowHandles()) {

 

    driver.switchTo()

          .window(handle);

 

    if (driver.getCurrentUrl()

            .contains("test-service")) {

 

        System.out.println(

            "Test Service Found");

 

        break;

    }

}

 

driver.switchTo()

      .window(mainWindow);


46. Window Handle Utility Class

In a professional automation framework, repeated window-handling operations can be placed in a reusable utility class.

import java.time.Duration;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class WindowHandleUtils {

 

    public static void waitForWindowCount(

            WebDriver driver,

            int expectedCount) {

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size()

            >= expectedCount);

    }

 

    public static void switchToWindowByTitle(

            WebDriver driver,

            String expectedTitle) {

 

        for (String handle :

                driver.getWindowHandles()) {

 

            driver.switchTo()

                  .window(handle);

 

            if (driver.getTitle()

                    .contains(expectedTitle)) {

 

                return;

            }

        }

 

        throw new RuntimeException(

            "Window not found: " +

            expectedTitle);

    }

 

    public static void switchToWindowByUrl(

            WebDriver driver,

            String expectedUrl) {

 

        for (String handle :

                driver.getWindowHandles()) {

 

            driver.switchTo()

                  .window(handle);

 

            if (driver.getCurrentUrl()

                    .contains(expectedUrl)) {

 

                return;

            }

        }

 

        throw new RuntimeException(

            "Window not found: " +

            expectedUrl);

    }

}


47. Using the Window Handle Utility

String parentWindow =

    driver.getWindowHandle();

 

driver.findElement(

    By.id("openReport")).click();

 

WindowHandleUtils.waitForWindowCount(

    driver, 2);

 

WindowHandleUtils.switchToWindowByTitle(

    driver,

    "Report");

 

System.out.println(

    driver.getTitle());

 

driver.switchTo()

      .window(parentWindow);


48. Window Handles with Page Object Model

In a Page Object Model framework, application actions can be kept in page classes while generic window operations can be placed in utility classes.

public class HomePage {

 

    private WebDriver driver;

 

    public HomePage(WebDriver driver) {

        this.driver = driver;

    }

 

    public void openHelpPage() {

 

        driver.findElement(

            By.id("help")).click();

    }

 

    public String getCurrentWindowHandle() {

 

        return driver.getWindowHandle();

    }

}


49. TestNG Window Handle Example

import java.time.Duration;

 

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

import org.testng.annotations.AfterMethod;

import org.testng.annotations.BeforeMethod;

import org.testng.annotations.Test;

 

public class WindowHandleTest {

 

    WebDriver driver;

 

    @BeforeMethod

    public void setup() {

 

        driver = new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

    }

 

    @Test

    public void verifyWindowHandle() {

 

        driver.get(

            "https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        Assert.assertNotNull(

            parentWindow);

 

        // Action that opens another tab/window

 

        new WebDriverWait(

            driver,

            Duration.ofSeconds(10))

            .until(d ->

                d.getWindowHandles().size()

                > 1);

 

        for (String handle :

                driver.getWindowHandles()) {

 

            if (!handle.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(handle);

 

                Assert.assertFalse(

                    driver.getTitle()

                          .isEmpty());

 

                break;

            }

        }

 

        driver.switchTo()

              .window(parentWindow);

    }

 

    @AfterMethod

    public void tearDown() {

 

        if (driver != null) {

            driver.quit();

        }

    }

}


50. Common Mistakes with Window Handles

Mistake 1: Not Storing the Parent Handle

String parentWindow =

    driver.getWindowHandle();

Store the original handle before opening a new browser context.

Mistake 2: Not Switching to the Child Window

After a new tab opens, Selenium must switch to the required handle before interacting with elements in that tab.

Mistake 3: Using Hard-Coded Handles

Window handles are dynamically generated. Retrieve them during the test instead of assuming a fixed value.

Mistake 4: Not Waiting for a New Handle

Wait until the expected number of browser contexts is available.

Mistake 5: Closing a Window and Continuing Without Switching

After closing the current context, switch to another valid handle.

Mistake 6: Assuming a Particular Handle Order

For maintainable automation, identify the required context using meaningful information rather than relying blindly on an assumed position.


51. Common Exceptions

ExceptionPossible CausePossible Solution
NoSuchWindowExceptionSelected window no longer existsSwitch to a valid window handle
TimeoutExceptionNew window did not appear in timeReview synchronization and wait condition
NoSuchElementExceptionElement not found in current contextVerify that Selenium is switched to the correct window
StaleElementReferenceExceptionPreviously located element became invalidLocate the element again after the context or page change


52. NoSuchWindowException

NoSuchWindowException may occur when Selenium attempts to interact with a browser window that has been closed or is no longer available.

Example:

driver.switchTo()

      .window(childWindow);

 

driver.close();

 

// The child window is closed.

// Switch to a valid remaining handle.

driver.switchTo()

      .window(parentWindow);


53. TimeoutException

If the application does not create the expected new browser context within the configured timeout, an explicit wait can time out.

WebDriverWait wait =

    new WebDriverWait(

        driver,

        Duration.ofSeconds(10));

 

wait.until(d ->

    d.getWindowHandles().size() > 1);

When this happens, investigate whether the triggering action worked, whether the application requires more time, and whether the expected window-count condition is correct.


54. Window Handles vs Frames

Window HandlesFrames
Used for browser tabs/windowsUsed for embedded frames/iFrames
Use getWindowHandle()Locate the frame
Use getWindowHandles()Use switchTo().frame()
Switch using switchTo().window()Switch using switchTo().frame()
Return using another window handleReturn using parentFrame() or defaultContent()


55. Window Handles vs Alerts

Window HandlesAlerts
Identify browser contextsIdentify JavaScript/browser alerts
Use getWindowHandle()Use switchTo().alert()
Use switchTo().window()Use Alert methods
Contain normal web pagesDisplay dialog messages


56. Window Handle Workflow for Multiple Tabs

Main Browser Context

        |

        v

Store Parent Handle

        |

        v

Click Link

        |

        v

New Tab Opens

        |

        v

Wait for Window Count

        |

        v

Get All Window Handles

        |

        v

Compare / Identify Handle

        |

        v

Switch to Child

        |

        v

Perform Actions

        |

        v

Close Child

        |

        v

Switch to Parent

        |

        v

Continue Test


57. Best Practices for Window Handles

  • Always store the current window handle before opening another browser context.
  • Use getWindowHandles() to discover available browser contexts.
  • Use switchTo().window() to change the active context.
  • Use explicit waits when a new tab or window appears asynchronously.
  • Identify the required window using title, URL, or a unique page element when possible.
  • Avoid hard-coding window handles.
  • Do not depend unnecessarily on the assumed ordering of handles.
  • After closing a child window, switch to a valid remaining window.
  • Use reusable utility methods in framework-level automation.
  • Use Selenium 4's newWindow() API when the test itself needs to create a new tab or window.
  • Call driver.quit() during test cleanup to end the WebDriver session.


58. Real-World Applications

ApplicationWindow Handle Use
Online ShoppingProduct comparison or external product information
ReportsReport may open in a separate tab
SupportSupport portal may open in another context
DocumentationDocumentation can open in a new tab
AuthenticationTest authentication service may use another browser context
Terms and ConditionsLegal information may open in another tab
PreviewDocument or product preview may open separately


59. Mini Project: Multiple Window Validation

Create a Selenium project with a main application and multiple links that open separate tabs.

Requirements

  1. Open the main application.
  2. Capture the main window handle.
  3. Click the Documentation link.
  4. Wait for the new window handle.
  5. Switch to the Documentation window.
  6. Validate its title.
  7. Close the Documentation window.
  8. Return to the main application.
  9. Open the Support page.
  10. Switch to the Support window.
  11. Validate its URL.
  12. Close the Support window.
  13. Return to the main window.
  14. Quit the browser.


60. Mini Project Flow

Main Application

      |

      +---- Documentation

      |          |

      |          +-- New Handle

      |          +-- Switch

      |          +-- Validate

      |          +-- Close

      |          +-- Parent

      |

      +---- Support

                 |

                 +-- New Handle

                 +-- Switch

                 +-- Validate

                 +-- Close

                 +-- Parent

                         |

                         v

                    Quit Driver


61. Complete Mini Project Example

import java.time.Duration;

 

import org.openqa.selenium.By;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.chrome.ChromeDriver;

import org.openqa.selenium.support.ui.WebDriverWait;

 

public class MultipleWindowTest {

 

    public static void main(String[] args) {

 

        WebDriver driver =

            new ChromeDriver();

 

        driver.manage()

              .window()

              .maximize();

 

        driver.get(

            "https://example.com");

 

        String parentWindow =

            driver.getWindowHandle();

 

        driver.findElement(

            By.id("documentation")).click();

 

        WebDriverWait wait =

            new WebDriverWait(

                driver,

                Duration.ofSeconds(10));

 

        wait.until(d ->

            d.getWindowHandles().size() > 1);

 

        for (String handle :

                driver.getWindowHandles()) {

 

            if (!handle.equals(parentWindow)) {

 

                driver.switchTo()

                      .window(handle);

 

                System.out.println(

                    "Documentation: " +

                    driver.getTitle());

 

                driver.close();

 

                break;

            }

        }

 

        driver.switchTo()

              .window(parentWindow);

 

        System.out.println(

            "Back to Main Page");

 

        driver.quit();

    }

}


62. Interview Questions on Window Handles

Q1. What is a window handle in Selenium?

A window handle is a unique identifier used by Selenium WebDriver to identify a browser window or tab within a WebDriver session.

Q2. Which method returns the current window handle?

driver.getWindowHandle();

Q3. Which method returns all window handles?

driver.getWindowHandles();

Q4. What is the return type of getWindowHandles() in Java?

The Java WebDriver API returns a Set<String>.

Q5. How do you switch to another window?

driver.switchTo()

      .window(windowHandle);

Q6. How do you return to the parent window?

driver.switchTo()

      .window(parentWindow);

Q7. How do you create a new tab in Selenium 4?

driver.switchTo()

      .newWindow(WindowType.TAB);

Q8. How do you create a new window in Selenium 4?

driver.switchTo()

      .newWindow(WindowType.WINDOW);

Q9. What is the difference between close() and quit()?

close() closes the currently selected browser context, whereas quit() ends the WebDriver session and closes all browser contexts.

Q10. Why should the parent handle be stored?

It provides a known identifier that can be used to return to the original browser context after working in another tab or window.


63. Advanced Interview Questions

Q1. How do you handle multiple windows in Selenium?

First retrieve all handles using getWindowHandles(), iterate through them, identify the required context using title, URL, or page-specific information, and switch using switchTo().window().

Q2. How do you find a newly opened window?

Store the existing handles before the action, wait until the window count increases, obtain the new set of handles, identify the handle that was not present before, and switch to it.

Q3. Why should window handles not be hard-coded?

Window handles are generated dynamically within the current WebDriver session.

Q4. What happens if you close the current window and do not switch back?

WebDriver remains associated with the closed context, and subsequent commands can result in a NoSuchWindowException.

Q5. How do you identify a specific window among many?

Switch through the available handles and use a reliable identifying property such as title, URL, or a unique element on the target page.


64. Quick Cheat Sheet

TaskCode
Get current window handledriver.getWindowHandle()
Get all window handlesdriver.getWindowHandles()
Switch windowdriver.switchTo().window(handle)
Create new tabdriver.switchTo().newWindow(WindowType.TAB)
Create new windowdriver.switchTo().newWindow(WindowType.WINDOW)
Close current contextdriver.close()
Close complete sessiondriver.quit()
Get current titledriver.getTitle()
Get current URLdriver.getCurrentUrl()
Count contextsdriver.getWindowHandles().size()
Wait for additional contextwait.until(d -> d.getWindowHandles().size() > 1)


65. Window Handle Checklist

  • Open the application.
  • Capture the current window handle.
  • Perform the action that opens another tab or window.
  • Wait for the additional browser context.
  • Retrieve all window handles.
  • Identify the required handle.
  • Switch to the required window.
  • Perform the required actions.
  • Validate title, URL, or page elements.
  • Close the child context when required.
  • Switch back to the parent handle.
  • Continue the test.
  • Quit the WebDriver session.


66. Learning Exercise

Create a Selenium automation test that performs the following:

  1. Open a test website.
  2. Print the current window handle.
  3. Store the current handle in a variable called parentWindow.
  4. Open a new tab.
  5. Print all available window handles.
  6. Switch to the new tab.
  7. Print its title and URL.
  8. Switch back to the parent.
  9. Create a new browser window.
  10. Print all handles again.
  11. Switch to the new window.
  12. Validate a unique element.
  13. Close the new window.
  14. Return to the parent.
  15. Quit the browser.


67. Important Points to Remember

  • A window handle identifies one browser tab or window within the current WebDriver session.
  • getWindowHandle() returns the current handle.
  • getWindowHandles() returns all available handles.
  • switchTo().window() changes the active browser context.
  • Window handles are dynamically generated.
  • The parent handle should usually be stored before opening a new context.
  • Use explicit waits when the new browser context is created asynchronously.
  • Title, URL, and unique elements can help identify a required window.
  • After closing a child window, switch to another valid handle.
  • Selenium 4 provides newWindow() for creating tabs and windows.
  • Window handling is different from frame and alert handling.


68. Final Interview Answer

Question: Explain Window Handles in Selenium.

Answer: Window handles are unique identifiers used by Selenium WebDriver to identify browser tabs and windows within a WebDriver session. I use driver.getWindowHandle() to obtain the handle of the current browser context and driver.getWindowHandles() to obtain all available window handles. When a new tab or window opens, I identify its handle and switch to it using driver.switchTo().window(handle). After completing the required actions, I can close the child context if necessary and switch back to the parent window using the stored parent handle. For synchronization, I use an explicit wait until the expected number of window handles is available. Selenium 4 also provides newWindow(WindowType.TAB) and newWindow(WindowType.WINDOW) for creating new browser contexts.


69. Summary

Window Handles provide Selenium WebDriver with a mechanism for identifying and controlling multiple browser tabs and windows within the same session. The most important methods are getWindowHandle(), getWindowHandles(), and switchTo().window().

A typical automation flow is to store the parent handle, trigger the action that opens a new browser context, wait for the new handle, retrieve all handles, identify the required handle, switch to it, perform the required validation, and finally return to the parent context.

Understanding window handles is essential for automating modern web applications that use multiple tabs, popup windows, reports, support pages, external services, documentation pages, and other separate browser contexts.


70. Selenium Course Resources

Learn Window Handles along with Selenium WebDriver, Java, TestNG, locators, waits, frames, alerts, Page Object Model, automation frameworks, and real-world testing projects:


71. Final Quick Revision

Current Window

      |

      v

driver.getWindowHandle()

      |

      v

Store Parent Handle

      |

      v

Open New Tab / Window

      |

      v

Wait for New Context

      |

      v

driver.getWindowHandles()

      |

      v

Identify Required Handle

      |

      v

driver.switchTo().window(handle)

      |

      v

Perform Actions

      |

      v

driver.close()

      |

      v

driver.switchTo().window(parentHandle)

      |

      v

Continue Test

      |

      v

driver.quit()

whatsapp