自动窗口关闭并切换回selenium中的父窗口

时间:2016-01-19 17:43:23

标签: java selenium selenium-webdriver

基本我正在使用maven和POM,我在第二个窗口中执行操作并单击发送窗口自动关闭后无法将焦点切换回父窗口,之后我的Firefox驱动程序无效。

**我使用了下面提到的三个不起作用的选项**

    public void switchWindow() {
        String handle = driver.getWindowHandle();
        Set<String> set = driver.getWindowHandles();
        set.remove(handle);
        if (set.size() >= 1) {
          driver.switchTo().window((String) set.toArray()[0]);
        }


  public WebDriver switchWindowByTitle(String title)
  {
      WebDriver popup = null;
      Set<String> windowIterator = driver.getWindowHandles();
      System.err.println("No of windows :  " + windowIterator.size());
      for (String s : windowIterator) {
          String windowHandle = s;
          popup = driver.switchTo().window(windowHandle);
          System.out.println("Window Title : " + popup.getTitle());
          System.out.println("Window Url : " + popup.getCurrentUrl());
          if (popup.getTitle().equals(title) ){
              System.out.println("Selected Window Title : " + popup.getTitle());
              return popup;
          }

      }
      System.out.println("Window Title :" + popup.getTitle());
      System.out.println();
      return popup;


 public WebDriver switchWindowByTitle(String title)
  {

 String currentWindow = driver.getWindowHandle();
    List<String> availableWindows = new ArrayList<String>(driver.getWindowHandles());

    for(String w : availableWindows)
    {
      if (w != currentWindow)
      {
        driver.switchTo().window(w);
        if (driver.getTitle().equalsIgnoreCase(title))
          return true;
        else
        {
          driver.switchTo().window(currentWindow);
        }
      }
    }
    return false;
  }

2 个答案:

答案 0 :(得分:3)

您需要在打开新窗口之前获取父窗口句柄,并在完成新窗口后再回到它。

// before opening the new window
String parentWindow = driver.getWindowHandle();

// after the new window was closed
driver.switchTo().window(parentWindow);

答案 1 :(得分:0)

我在C#中使用以下代码 它还支持打开的多个选项卡。 Thread.Sleep只是为了测试稳定性

    public static bool CloseCurrentTab(this IWebDriver driver)
    {
        var windowHandles = driver.WindowHandles;
        if (windowHandles.Count > 1)
        {
            driver.Close();
            driver.SwitchTo().Window(windowHandles[windowHandles.Count - 2]);
            Thread.Sleep(500);
            return true;
        }

        return false;

    }