Switch between two browser windows using Selenium WebDriver

后端 未结 2 488
暗喜
暗喜 2020-12-03 12:10

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条回答
  •  余生分开走
    2020-12-03 12:53

    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 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.
     }
    

提交回复
热议问题