2

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 5

3

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;

2
  • The Java example is missing an s. It should be driver.getWindowHandles().size();
    – Dustin N.
    Oct 24, 2018 at 20:26
  • @DustinN. Thank you for pointing this out. I updated my answer.
    – Twaldigas
    Oct 26, 2018 at 12:09
0

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);
        }
0

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.

0

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
-1

Use getWindowHandles() method. For example:

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

int numberOfWindows = windowHandles.size();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.