How to switch between two windows in browser using

2020-02-06 07:50发布

I'm working with Selenium Automation. In this, When i click a link in a current window, a new window opens. I just want to switch the control to the new window. But i can't do this.Actually the new window is an auto-generated one. That is, link will be generated dynamically. Help me friends...

8条回答
贪生不怕死
2楼-- · 2020-02-06 08:22
//to get the current/parent window

String parentWindowContact = driver.getWindowHandle();

//to switch to the new window from current/parent window

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

for(String windowHandle : handleswindow)

{

   driver .switch To().window(windowHandle);

}

//to close the new window

driver.close();

//to switch back to the parent window

driver.switchTo().window(parentWindowContact);
          o switch back to the parent window

driver.switchTo().window(parentWindowContact);
查看更多
劳资没心,怎么记你
3楼-- · 2020-02-06 08:26

Here is the best methods to switch in window using index and title. you can add in base class and use it frequently.

public  void switchToWindow(String windowTitle) {
    Set<String> windows = driver.getWindowHandles();
    for (String window : windows) {
        driver.switchTo().window(window);
        if (driver.getTitle().contains(windowTitle)) {
            return;
        }
    }
}




  public void switchToWindow(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();
    }
    }
    driver.switchTo().window(winTitle);
    System.out.println(winTitle);
}
查看更多
登录 后发表回答