Reputation: 103
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;
}
Upvotes: 3
Views: 25095
Reputation: 193308
Page Title is the <title>
tag and appears at the top of a browser window which is part of the HTML DOM within the <header>
section of the <html>
.
So Selenium driven WebDriver needs to have the focus on the specific Browsing Context to extract the Page Title.
Where as Window Handle is a unique identifier that holds the address of all the windows and can return the string value. All the browser will have a unique window handle. This getWindowHandles()
function helps to retrieve the handles of all windows.
So Selenium driven WebDriver can collect the Window Handles from the Browsing Context even without having individual focus on them.
So it is not possible to get the title of window/tab without switching to the specific Window / TAB.
Upvotes: 0
Reputation: 1
ArrayList<String> tabs = new ArrayList<String> driver.getWindowHandles());
driver.switchTo().window(tabs.get(1));
String parentWindow=driver.getWindowHandle();
Set<String> windows= driver.getWindowHandles();
for(String child:windows){
try{
if(!child.equalsIgnoreCase(parentWindow)){
driver.switchTo().window(child);
String windowTitle=driver.getTitle();
if(windowTitle.equals("book My Show")){
System.out.println("Window found");
}
else{
System.out.println("no windows found");
}
}
}catch(Exception e){
e.printStackTrace();
System.out.println("");
}
}
driver.switchTo().window(parentWindow);
} }
Upvotes: -3
Reputation: 17
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;
}
Upvotes: -3