How to get handlers for all open windows and brows

2019-07-10 05:58发布

I am searching for a method that will return the urls and handlers across all open windows, tabs, and browsers, not just the one that is currently being run in selenium. My code below only returns the current window that was instantiated by running the current test.

String originalWindowHandle = driver.getWindowHandle();
System.out.println("original Window handles are: " + originalWindowHandle);
System.out.println("Title of original Page:" + driver.getTitle());  
java.util.Set<java.lang.String> windowHandles = driver.getWindowHandles();
System.out.println(windowHandles);
int count = windowHandles.size();
//if (count > 1) {
for (String window: windowHandles) {
        String url = driver.getCurrentUrl();
        System.out.println("current url is: " + url);
    }       
//}

any ideas or leads would be helpful, thanks.

1条回答
冷血范
2楼-- · 2019-07-10 06:30

You are getting correct counts. But never switched to newly opened windows. In enhanced for loop you want to switch to each window and then check url

String originalWindowHandle = driver.getWindowHandle();
System.out.println("original Window handles are: " + originalWindowHandle);
System.out.println("Title of original Page:" + driver.getTitle());  
java.util.Set<java.lang.String> windowHandles = driver.getWindowHandles();
System.out.println(windowHandles);
int count = windowHandles.size();
//if (count > 1) {
for (String window: windowHandles) {
    if(!window.equals(originalWindowHandle)){
        driver.switchTo().window(window);
        String url = driver.getCurrentUrl();
        System.out.println("current url is: " + url);        
    }  
    //to go back to original    
    driver.switchTo().window(originalWindowHandle); 

}   
//}
查看更多
登录 后发表回答