Is there a way to get a list of opened browser windows using Selenium? I want to use this to count the number of open browsers within a test.
5 Answers
IWebDriver
has the method WindowHandles
. The method returns a collection. So you can use the size of the collection to get the number of open windows.
I am not so familiar with C#, but in Java this works:
driver.getWindowHandles().size();
In C# this should work:
Driver.WindowHandles.Count;
-
The Java example is missing an s. It should be
driver.getWindowHandles().size();
Oct 24, 2018 at 20:26 -
Simple example to count the number of opened windows is go to www.rediff.com you will get atleat 2-opened windows. 1 - rediff.com Home Page. 2 - Ad window.
below is the simple code to count the no of opened wind and get windowhandle code.
IWebDriver driver = new ChromeDriver("G:\\Selenium_Csharp\\Jar\\chromedriver_win32");
driver.Navigate().GoToUrl("http://www.rediff.com");
String originalWindowHandle = driver.CurrentWindowHandle;
Console.WriteLine("original Window handles are: " + originalWindowHandle);
Console.WriteLine("Title of original Page:" + driver.Title);
Thread.Sleep(3000);
System.Collections.ObjectModel.ReadOnlyCollection<string> windowHandles = driver.WindowHandles;
Console.WriteLine("Count the no. of opened windows: "+windowHandles.Count);
foreach (String window in windowHandles)
{
Console.WriteLine(window);
}
For C# - Driver.WindowHandles.Count;
count starts with 1.
You can use condition Driver.WindowHandles.Count=0
to handle any exception related to Browser operation if none of the browser is opened.
Use this below code to find the number of windows gets opened
int i=1;
for (string eachwindow : allwindow)
{
driver.switchTo().window(eachwindow);
System.out.println(eachwindow);
i++;
}
System.out.println(i); //displays the count of windows gets opened
Use getWindowHandles()
method. For example:
Set<String> winHandles = driver.getWindowHandles();
int numberOfWindows = windowHandles.size();