1

As selenium don't provide method to switch into windows( Multiple window) but I want to make customize method to switch into different windows using index. But below code is not working as per expectations. Please suggest best implementation of below method.

    public void switchToWindowIndex(int index) {
    Set<String> windows = driver.getWindowHandles();
    int totalWin = windows.size();
    String winTitle = null;
    for (int i =0; i<= totalWin; i++) {
        if (i == index) {
            winTitle = windows.toArray()[i].toString();
            return;
        }
        System.out.println(windows.toArray()[i].toString());

    }
    driver.switchTo().window(winTitle);
    logger.info("Switched to " + driver.getTitle());
}

Thanks in advance.

Ajeet Yadawa
  • 135
  • 3
  • 16
  • just remember that the array will be in different orders depending on the browser. There is no guarantee that the recently opened tab window will be the last index, or the first index. You have to track the handles yourself. (record the current, and compare getWindowHandles to see which is the new...) – pcalkins Dec 11 '19 at 20:01

4 Answers4

2

While using Selenium you shouldn't switchTo() between window handles using index because, though it appears that WindowHandles would be sorted like the oldest windows first and the newest windows last. But this is not the case: It is totaly random!!!

In a discussion, Simon clearly mentioned that:

While the datatype used for storing the list of handles may be ordered by insertion, the order in which the WebDriver implementation iterates over the window handles to insert them has no requirement to be stable. The ordering is arbitrary.

So, to switch between window handles you have to use either of the following:

undetected Selenium
  • 183,867
  • 41
  • 278
  • 352
1

If you have to switch to a window based on index then there is no need to iterate over all of the window handles. You could do something like this:

public void switchToWindowIndex(int index) {
    Set<String> windowHandles = driver.getWindowHandles();
    List<String> windowStrings = new ArrayList<>(windowHandles);
    String reqWindow = windowStrings.get(index);
    driver.switchTo().window(reqWindow);
    logger.info("Switched to " + driver.getTitle());
}

Code explanation: get window handles

Set<String> windowHandles = driver.getWindowHandles();

convert window handles set to arraylist so that we can get string based on index

List<String> windowStrings = new ArrayList<>(windowHandles);

get window handle string based on the index

String reqWindow = windowStrings.get(index);

switch to required window

driver.switchTo().window(reqWindow);
Ayaz
  • 249
  • 1
  • 2
  • 11
0

You can do this shortened as such:

driver.switchTo().window(driver.getWindowHandles().toArray()[index]);

But, if you want to iterate the window handles for some reason, you can take this approach instead:

public void switchToWindowIndex(int index) {

    // get list of window handles - use iterator instead of set
    Iterator<String> windows = driver.getWindowHandles();

    // if index > windows.size()-1 then we will get out of bounds exception
    if (index => windows.size()-1)
    {
        System.out.println("Invalid index passed.");
        return;
    }

    // declare starting index as 0 to begin iteration
    int startIndex = 0;

    while (windows.hasNext())
    {
        // if startIndex == index then iterator is pointing to desired window handle
        if (startIndex == index) {
            driver.switchTo().window(window);
            break; // we are finished now, so break out of loop
        }
        // if we are not pointing to correct window handle then go to next one
        else {
            startIndex++;
            window = windows.next();

        } // end if else

    } // end while
}

A few things have changed here:

  • Added a check for index against windows.size() to ensure index is within bounds of windows
  • Changed Set<string> to Iterator<string> to make iteration straightforward
  • Introduce startIndex to keep track of window handle that Iterator is pointing to
  • Use if / else comparison with startIndex and index to determine whether we should 1. Switch to the window handle iterator points to or 2. Move on to next window handle by calling hasNext() and index++.
CEH
  • 5,701
  • 2
  • 16
  • 40
0

To get the last window opened:

driver.switchTo().window(new ArrayList<>(driver.getWindowHandles()).get(driver.getWindowHandles().size() - 1));

To get specific Index:

int idx = 1;
driver.switchTo().window(new ArrayList<>(driver.getWindowHandles()).get(index);
Procrastinator
  • 2,526
  • 30
  • 27
  • 36