9

I used Firefox Driver to open two URL's. Whenever I invoke driver, new firefox window is opened. I have to switch between these two windows. How can I do this?

2 Answers 2

20

you can use following code to switch between windows based on the window title

 private void handleMultipleWindows(String windowTitle) {
            Set<String> windows = driver.getWindowHandles();

            for (String window : windows) {
                driver.switchTo().window(window);
                if (driver.getTitle().contains(windowTitle)) {
                    return;
                }
            }
        }

Similary you could use URL or some other criteria to switch windows.

Sign up to request clarification or add additional context in comments.

Comments

2

I have added scope of switching back to mainWindowHandle as well.

You may try using below function provided that you are handeling windows with different titles.

private String mainWindowsHandle; // Stores current window handle
 public static boolean swithToWindow(WebDriver driver,String title){
  mainWindowsHandle = driver.getWindowHandle();
  Set<String> handles = driver.getWindowHandles(); // Gets all the available windows
  for(String handle : handles)
  {
    driver.switchTo().window(handle); // switching back to each window in loop
    if(driver.getTitle().equals(title)) // Compare title and if title matches stop loop and return true
     return true; // We switched to window, so stop the loop and come out of funcation with positive response
  }
  driver.switchTo().window(mainWindowsHandle); // Switch back to original window handle
  return false; // Return false as failed to find window with given title.
 }

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.