Search code examples
javaseleniumselenium-webdriverwindowhandle

How to switch to child window of a child window in Selenium(Window handles and titles are dynamic)?


In one application, there is a child window, which opens another window. In total there are three windows. The window handles and the titles of each window are dynamic, they change every session.

So I stored the handles of the parent window and the first child window, then I called getWindowHandles method, stored all handles in a set, removed parent window and first child window. The remaining window handle in the set will be the third window handle.

Set<String> windowHandles = uiDriver().getDriver().getWindowHandles();
windowHandles.remove(parentHandle);
windowHandles.remove(firstChildHanlde);
String thirdChildHandle = windowHandles.toString();

It would be of great help if you can help me on how to get the child window handle in a more convenient way.


Solution

  • For a more generic method of handling windows handles you can get the Set of windows handles before you perform some action that opens more windows, perform the action, then get the Set of window handles afterwards, and then remove the "before" Set from the "after" Set. What remains are the windows that were opened during the action.

    Set<String> beforeWindowHandles = uiDriver().getDriver().getWindowHandles();
    // do something that opens a window
    Set<String> afterWindowHandles = uiDriver().getDriver().getWindowHandles();
    afterWindowHandles.removeAll(beforeWindowHandles);
    

    Now afterWindowHandles contains only the newly opened windows.