Get title of window without switching in selenium webdriver

Jitendra Jangid picture Jitendra Jangid · Sep 10, 2014 · Viewed 18k times · Source

Is there any way to get window title without making any switch in selenium?

presently I'm using below code:

public boolean switchToWindowByTitle(String title){
    String currentWindow = driver.getWindowHandle(); 
    Set<String> availableWindows = driver.getWindowHandles(); 
    if (!availableWindows.isEmpty()) { 
         for (String windowId : availableWindows) {
              String switchedWindowTitle=driver.switchTo().window(windowId).getTitle();
              if ((switchedWindowTitle.equals(title))||(switchedWindowTitle.contains(title))){ 
                  return true; 
              } else { 
                driver.switchTo().window(currentWindow); 
              } 
          } 
     } 
     return false;
}

Answer

Ramesh picture Ramesh · Jul 11, 2018

This Code will do the purpose. Call this function as follows swithToWindow("window Name");

public static Boolean switchToWindow(String title) {
    String Parent_window = driver.getWindowHandle();
    Set<String> handles = driver.getWindowHandles();
    for(String handle : handles) {
        driver.switchTo().window(handle);
        if (driver.getTitle().equalsIgnoreCase(title)) {
            return true;
        }
    }
    driver.switchTo().window(Parent_window);
    return false;
}