如何使用selenium webdriver从父窗口切换到子窗口

时间:2017-04-03 11:19:31

标签: java selenium

我需要关闭子窗口并切换回父窗口以执行某些操作。

public static void nextTab() throws InterruptedException { 
    Set winSet = UIPage.getBaseWindow().getWindowHandles(); 
    List winList = new ArrayList(winSet); 
    String newTab = winList.get(winList.size() - 1); UIPage.getBaseWindow().switchTo().window(newTab);
    Thread.sleep(Constant.LONG_TIMEOUT_500); 
}

public static void prevTab() { 
    Set winSet = UIPage.getBaseWindow().getWindowHandles(); 
    List winList = new ArrayList(winSet); 
    UIPage.getBaseWindow().close(); 
    String oldTab = winList.get(winList.size() - 2); //System.out.println(oldTab);
    UIPage.getBaseWindow().switchTo().window(oldTab);    
}

1 个答案:

答案 0 :(得分:0)

//Get the main window handle

String mainWindowHandle = driver.getWindowHandle();

现在执行打开子窗口的操作,如点击链接或按钮。

//Switch to child window and close it

for (String childWindowHandle : driver.getWindowHandles()) {
  //If window handle is not main window handle then close it 
  if(!childWindowHandle.equals(mainWindowHandle)){
  driver.switchTo().window(childWindowHandle);
  // Close child windows
  driver.close(); 
  }
} 

//switch back to main window
driver.switchTo().window(mainWindowHandle);