DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Getting Started With WebdriverIO Typescript Jasmine
  • Cypress Web Automation
  • AI-Driven Test Automation Techniques for Multimodal Systems

Trending

  • How Trustworthy Is Big Data?
  • Unit Testing Large Codebases: Principles, Practices, and C++ Examples
  • Integrating Model Context Protocol (MCP) With Microsoft Copilot Studio AI Agents
  • The Cypress Edge: Next-Level Testing Strategies for React Developers
  1. DZone
  2. Testing, Deployment, and Maintenance
  3. Testing, Tools, and Frameworks
  4. Selenium C# Tutorial: Handling Multiple Browser Windows

Selenium C# Tutorial: Handling Multiple Browser Windows

Learn how to handle multiple windows in Selenium C# along with some Selenium test automation examples.

By 
Himanshu Sheth user avatar
Himanshu Sheth
DZone Core CORE ·
Jun. 03, 20 · Tutorial
Likes (14)
Comment
Save
Tweet
Share
17.0K Views

Join the DZone community and get the full member experience.

Join For Free

A common scenario in a website (or web application) is opening up a new browser (or tab) on the click of a button. With these multiple browsers, windows can be automated using Selenium test automation.

Once the Selenium WebDriver instance is instantiated, a unique alphanumeric id is assigned to the window. This is called window handle and is used to identify browser windows. Since the id is unique, it is used by the Selenium WebDriver to switch between different windows (or tabs).

The id is retained till the closure of the Selenium WebDriver session via WebDriver.Quit or manual killing of the process. The SwitchTo() command is used to do a context switch to the intended browser window.

In my previous Selenium C# tutorial, I've covered how to Here in this part of Selenium C# tutorial, I’ll guide you on window handling in Selenium C#. 

Commands Used For Window Handling In Selenium C#

These commands are vital for performing Selenium Test Automation as they allow help in switching to a new window or a tab, knowing the info about the current window and of all the windows open. Here are some of the widely used commands that are used for window handling in Selenium C#. 

SwitchTo Window

This command is used to switch the focus to a new browser window (or tab) by supplying the Window Name or Window Handle as an argument to the command.

C#
 




x


 
1
driver.SwitchTo().Window(WindowHandle);
2
driver.SwitchTo().Window(WindowName);



CurrentWindowHandle

This command returns the window handle (as a String) of the current window.

C#
 




xxxxxxxxxx
1


 
1
String currentWindowHandle = driver.CurrentWindowHandle;



WindowHandles

The WindowHandles command gets the handles of all the open instances of the browser under test. The return type is a String ReadOnlyCollection.

The syntax of WindowHandles is:

C#
 




xxxxxxxxxx
1


 
1
ReadIOnlyCollection<string> IWebDriver.WindowHandles { get;};



Example usage of WindowHandles: 

C#
 




xxxxxxxxxx
1


 
1
IList<string> totWindowHandles = new List<string> (WebDriver.WindowHandles);



Now in the next section this Selenium C# tutorial, we answer, how to handle multiple browser windows in Selenium C#.

Handling Multiple Browser Windows In Selenium C#

The fundamental principles of Window Handles are used for window handling in Selenium C#. By default, the Parent Window is the one that has the focus. To switch the context from the Parent Window to a Child Window, the command WebDriver.SwitchTo(WindowHandle) is used. Instead of Window Handle, Window Id can also be used as both these identifiers are unique to every browser window (or tab). 

To demonstrate window handling of multiple browsers in Selenium C#. A Chrome WebDriver instance is initiated with the URL under test as https://www.lambdatest.com. A unique Window handle of the typed string is used to identify the window.

C#
 




xxxxxxxxxx
1
71


 
1
/* Using Chrome Webdriver Instance for window handling in selenium C#*/
2
using NUnit.Framework;
3
using System;
4
using System.Collections.ObjectModel;
5
using OpenQA.Selenium;
6
using OpenQA.Selenium.Chrome;
7
using OpenQA.Selenium.Support.UI;
8
using SeleniumExtras.WaitHelpers;
9
 
10
namespace Selenium_Window_Demo_2
11
{
12
    class Selenium_Window_Demo_2
13
    {
14
        IWebDriver driver;
15
 
16
        [SetUp]
17
        public void start_Browser()
18
        {
19
            /* Local Selenium WebDriver */
20
            driver = new ChromeDriver();
21
            driver.Manage().Window.Maximize();
22
        }
23
 
24
        [Test, Order(1)]
25
        public void test_window_ops()
26
        {
27
            String test_url_1 = "https://www.lambdatest.com";
28
            String test_url_2 = "https://www.lambdatest.com/blog/";
29
            String test_url_2_title = "LambdaTest | A Cross Browser Testing Blog";
30
            IJavaScriptExecutor js = (IJavaScriptExecutor)driver;
31
 
32
            driver.Url = test_url_1;
33
 
34
            /* Not a good practice to use Thread.Sleep as it is a blocking call */
35
            /* Used here for demonstration */
36
            System.Threading.Thread.Sleep(4000);
37
 
38
            /* Different ways in which ExecuteScript can be used */
39
            /* js.ExecuteScript("window.open(test_url_2)"); */
40
            /* js.ExecuteScript("window.open(arguments[0])", test_url_2); */
41
 
42
            /* Reference - https://www.w3schools.com/jsref/met_win_open.asp */
43
            js.ExecuteScript("window.open('" + test_url_2 + "', '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800')");
44
 
45
            System.Threading.Thread.Sleep(6000);
46
            Assert.AreEqual(2, driver.WindowHandles.Count);
47
 
48
            var newWindowHandle = driver.WindowHandles[1];
49
            Assert.IsTrue(!string.IsNullOrEmpty(newWindowHandle));
50
 
51
            /* Assert.AreEqual(driver.SwitchTo().Window(newWindowHandle).Url, "https://www.lambdatest.com/blog/"); */
52
            string expectedNewWindowTitle = test_url_2_title;
53
            Assert.AreEqual(driver.SwitchTo().Window(newWindowHandle).Title, expectedNewWindowTitle);
54
 
55
            /* Close the newly opened Window and return to the old window */
56
            driver.SwitchTo().Window(driver.WindowHandles[1]).Close();
57
            System.Threading.Thread.Sleep(2000);
58
 
59
            /* Return to the window with handle = 0 */
60
            driver.SwitchTo().Window(driver.WindowHandles[0]);
61
            System.Threading.Thread.Sleep(2000);
62
        }
63
 
64
        [TearDown]
65
        public void close_Browser()
66
        {
67
            driver.Quit();
68
        }
69
    }
70
}



The window.open() method with relevant parameters such as URL, _blank, window size, etc. is used to open the URL  https://www.lambdatest.com/blog . This would be a child window to the parent window which is already open.

C#
 




xxxxxxxxxx
1


 
1
/*window.open() method for window handling in Selenium C# */
2
js.ExecuteScript("window.open('" + test_url_2 + "', '_blank', 'toolbar=yes,scrollbars=yes,resizable=yes,width=800,height=800')");
3
 
4
System.Threading.Thread.Sleep(6000);
5
Assert.AreEqual(2, driver.WindowHandles.Count);
6

          



The WindowHandle count now becomes two (0 and 1). The SwitchTo().Window() command with Window Handle of the second window (i.e. child window) is used to switch to that browser window.

C#
 




xxxxxxxxxx
1


 
1
/*WindowHandle count and SwitchTo().Window() for  window handling in Selenium C# window handling in Selenium C# */
2
var newWindowHandle = driver.WindowHandles[1];
3
Assert.IsTrue(!string.IsNullOrEmpty(newWindowHandle));
4
 
5
/* Assert.AreEqual(driver.SwitchTo().Window(newWindowHandle).Url, "https://www.lambdatest.com/blog/"); */
6
string expectedNewWindowTitle = test_url_2_title;
7
Assert.AreEqual(driver.SwitchTo().Window(newWindowHandle).Title, expectedNewWindowTitle);



The Child Window is closed and the window count becomes one. The context is switched to the parent window using the command driver.SwitchTo().Window(driver.WindowHandles[0])

C#
 




xxxxxxxxxx
1


 
1
/* Close the newly opened Window and return to the old window for window handling in Selenium C#*/
2
driver.SwitchTo().Window(driver.WindowHandles[1]).Close();
3
System.Threading.Thread.Sleep(2000);
4
 
5
/* Return to the window with handle = 0 */
6
driver.SwitchTo().Window(driver.WindowHandles[0]);



As seen in the output snapshot, the two browser windows are open with URL 1 - https://www.lambdatest.com and URL 2 — https://www.lambdatest.com/blog. The WindowHandle of the second browser window is used with the SwitchTo() command to switch the context to that window. Once that child window is closed, the same approach is used to switch to the parent window (driver.WindowHandles[0]).

lambdatest

test detail summary

Now that you know how to open multiple windows in Selenium C#, let’s move on to learn how to handle multiple browser tabs for windows handling in this  Selenium C# tutorial.

Handling Multiple Browser Tabs In Selenium C#

The concept of Window Handle remains the same whether a URL is opened in a new window or a new tab. For demonstrating how to handle multiple browser tabs in Selenium C#, we use the test URL as http://the-internet.herokuapp.com/windows The Click Here link on the test page is located using the XPath property. In our earlier articles, we covered XPath in Selenium in greater detail.

herokuapp

Once the button is clicked, the internet herokuapp URL opens up in a new browser tab. The window handle count becomes two with the driver.WindowHandles[0] representing the window handle of ‘parent window’ and driver.WindowHandles[1]  representing window handle of ‘child window’.

C#
 




xxxxxxxxxx
1
71


 
1
using NUnit.Framework;
2
using OpenQA.Selenium;
3
using OpenQA.Selenium.Chrome;
4
using OpenQA.Selenium.Firefox;
5
using OpenQA.Selenium.Support.UI;
6
using SeleniumExtras.WaitHelpers;
7
using System;
8
using System.Collections.ObjectModel;
9
 
10
namespace Selenium_Window_Demo_1
11
{
12
    class Selenium_Window_Demo_1
13
    {
14
        IWebDriver driver;
15
 
16
        [SetUp]
17
        public void start_Browser()
18
        {
19
            // Local Selenium WebDriver
20
            driver = new ChromeDriver();
21
            driver.Manage().Window.Maximize();
22
        }
23
 
24
        [Test, Order(1)]
25
        public void test_window_ops()
26
        {
27
            String test_url = "http://the-internet.herokuapp.com/windows";
28
 
29
            WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(10));
30
 
31
            driver.Url = test_url;
32
 
33
            var browser_button = driver.FindElement(By.XPath("//a[.='Click Here']"));
34
            Assert.AreEqual(1, driver.WindowHandles.Count);
35
 
36
            string WindowTitle = "The Internet";
37
            Assert.AreEqual(WindowTitle, driver.Title);
38
 
39
            browser_button.Click();
40
            Assert.AreEqual(2, driver.WindowHandles.Count);
41
 
42
            Console.WriteLine("Window Handle[0] - " + driver.WindowHandles[0]);
43
 
44
            var newTabHandle = driver.WindowHandles[1];
45
            Assert.IsTrue(!string.IsNullOrEmpty(newTabHandle));
46
 
47
            Console.WriteLine("Window Handle[1] - " + driver.WindowHandles[1]);
48
 
49
            Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Url, "http://the-internet.herokuapp.com/windows/new");
50
 
51
            string expectedNewWindowTitle = "New Window";
52
            Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Title, expectedNewWindowTitle);
53
 
54
            /* Thread Sleep is not a good practice since it is a blocking call */
55
            /* Only used for demonstration */
56
            System.Threading.Thread.Sleep(2000);
57
 
58
            driver.SwitchTo().Window(driver.WindowHandles[1]).Close();
59
            driver.SwitchTo().Window(driver.WindowHandles[0]);
60
 
61
            System.Threading.Thread.Sleep(2000);
62
        }
63
 
64
        [TearDown]
65
        public void close_Browser()
66
        {
67
            driver.Quit();
68
        }
69
    }
70
}



The SwitchTo().Window(driver.WindowHandles[0]) is used to switch back to the parent window after closing the child window.

C#
 




xxxxxxxxxx
1
16


 
1
var newTabHandle = driver.WindowHandles[1];
2
Assert.IsTrue(!string.IsNullOrEmpty(newTabHandle));
3
 
4
Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Url, "http://the-internet.herokuapp.com/windows/new");
5
 
6
 
7
string expectedNewWindowTitle = "New Window";
8
Assert.AreEqual(driver.SwitchTo().Window(newTabHandle).Title, expectedNewWindowTitle);
9
 
10
/* Thread Sleep is not a good practice since it is a blocking call */
11
/* Only used for demonstration */
12
System.Threading.Thread.Sleep(2000);
13
 
14
driver.SwitchTo().Window(driver.WindowHandles[1]).Close();
15
driver.SwitchTo().Window(driver.WindowHandles[0]);
16

          



Here are the Window Handles of the two browser windows that were instantiated during automated browser testing:

test outcome


The output snapshot from Visual Studio is below:

visual studio

Now, let’s move on to handling browser pop-up windows in this selenium C# tutorial.

Handling Browser Pop-up Windows In Selenium C#

There are many types of websites (e.g. job sites) that throw a couple of pop-up windows. Selenium test automation can be used to automate the handling of these pop-ups. It does not depend on the number of pop-ups being shown as each new window will be assigned a unique window handle. The window handle can be used with the SwitchTo() command to switch between different windows.

To demonstrate the handling of browser pop-ups, we use the popup test URL. Pop-ups for Chrome can be enabled by going to Privacy and Security — Site Settings — Pop-ups and redirects and disabling Block option for http://www.popuptest.com:80

privacy and settings

Alternatively, you can open the test URL in the Chrome browser and enable pop-ups for that particular site.

popup test

The site opens up 6 pop-up windows. In this Selenium test Automation scenario, we close pop-up windows, one at a time in reverse chronological order i.e. http://www.popuptest.com/popup6.html will be closed first, http://www.popuptest.com/popup5.html  will be closed next and so on.

Window Handles of these pop-ups are used to perform the following operation:

Plain Text
 




xxxxxxxxxx
1


 
1
Switch to a window (or pop-up)
2

          
3
driver.SwitchTo().Window(WindowHandle)
4

          
5
Close the browser  window
6

          
7
driver.SwitchTo().Window(driver.WindowHandles[window-number]).Close() or
8

          
9
driver.Close() (if the window to be closed is in focus)



Once all the pop-windows are closed, the Window Count becomes 1. The Window Title is then matched with the expected title to make sure that the parent window is in focus. On confirmation, the parent window is also closed and the resources used by Chrome WebDriver instance are freed using a driver.Quit().

C#
 




xxxxxxxxxx
1
89


 
1
using NUnit.Framework;
2
using System;
3
using System.Collections.ObjectModel;
4
using OpenQA.Selenium;
5
using OpenQA.Selenium.Chrome;
6
using OpenQA.Selenium.Support.UI;
7
using SeleniumExtras.WaitHelpers;
8
using System.Collections.Generic;
9
 
10
namespace selenium_pop_up_windows
11
{
12
    class selenium_pop_up_windows
13
    {
14
        IWebDriver driver;
15
 
16
        /******* Helper functions ********/
17
 
18
        /* API - Get Window Title */
19
        public String getCurrWindowTitle()
20
        {
21
            String windowTitle = driver.Title;
22
            return windowTitle;
23
        }
24
 
25
        /* API - Get Window Handle */
26
        public String getMainWinHandle(IWebDriver driver)
27
        {
28
            return driver.CurrentWindowHandle;
29
        }
30
 
31
        /* The test website open-ups number of pop-ups */
32
        /* API - Close all the pop-ups and return to the primary window */
33
        public Boolean closeAllWindows(String currWindowHandle)
34
        {
35
            IList<string> totWindowHandles = new List<string>(driver.WindowHandles);
36
 
37
            foreach (String WindowHandle in totWindowHandles)
38
            {
39
                Console.WriteLine(WindowHandle);
40
                if (!WindowHandle.Equals(currWindowHandle))
41
                {
42
                    driver.SwitchTo().Window(WindowHandle);
43
                    driver.Close();
44
                }
45
            }
46
 
47
            driver.SwitchTo().Window(currWindowHandle);
48
            if (driver.WindowHandles.Count == 1)
49
                return true;
50
            else
51
                return false;
52
        }
53
 
54
        [SetUp]
55
        public void start_Browser()
56
        {
57
            /* Local Selenium WebDriver */
58
            driver = new ChromeDriver();
59
            driver.Manage().Window.Maximize();
60
        }
61
 
62
        [Test]
63
        public void test_window_ops()
64
        {
65
            String test_url = "http://www.popuptest.com/popuptest1.html";
66
            String expected_win_title = "PopupTest 1 - test your popup killer software";
67
 
68
            driver.Url = test_url;
69
 
70
            /* Not a good practice to use Thread.Sleep as it is a blocking call */
71
            /* Used here for demonstration */
72
            System.Threading.Thread.Sleep(8000);
73
 
74
            String windowTitle = getCurrWindowTitle();
75
            String mainWindow = getMainWinHandle(driver);
76
            Assert.IsTrue(closeAllWindows(mainWindow));
77
 
78
            /* Addition of delay for checking the output */
79
            System.Threading.Thread.Sleep(4000);
80
            Assert.IsTrue(windowTitle.Contains(expected_win_title), "Title does not match - Test Failed");
81
        }
82
 
83
        [TearDown]
84
        public void close_Browser()
85
        {
86
            driver.Quit();
87
        }
88
    }
89
}



For modularity, we have created a few Helper Functions:

getCurrWindowTitle() 

Get the Window title of the currently focused window.

C#
 




xxxxxxxxxx
1


 
1
public String getCurrWindowTitle()
2
{
3
    String windowTitle = driver.Title;
4
    return windowTitle;
5
}



getMainWinHandle(IWebDriver driver) 

It returns the handle of the window under focus. This API is called after switching to the intended window hence, driver.CurrentWindowHandle is sufficient to return the window handle.

C#
 




xxxxxxxxxx
1


 
1
public String getMainWinHandle(IWebDriver driver)
2
{
3
    return driver.CurrentWindowHandle;
4
}



closeAllWindows(String currWindowHandle) 

 This API closes all the pop-up windows one by one till the Window Handle count becomes 1 (driver.WindowHandles.Count == 1) i.e. only the parent window is open.

C#
 




xxxxxxxxxx
1
20


 
1
public Boolean closeAllWindows(String currWindowHandle)
2
{
3
    IList<string> totWindowHandles = new List<string>(driver.WindowHandles);
4
 
5
      foreach (String WindowHandle in totWindowHandles)
6
      {
7
            if (!WindowHandle.Equals(currWindowHandle))
8
            {
9
                   driver.SwitchTo().Window(WindowHandle);
10
                driver.Close();
11
            }
12
      }
13
 
14
      driver.SwitchTo().Window(currWindowHandle);
15
      if (driver.WindowHandles.Count == 1)
16
           return true;
17
    else
18
         return false;
19
}



The Window handles are stored in a Collection of type String.

C#
 




xxxxxxxxxx
1


 
1
IList<string> totWindowHandles = new List<string>(driver.WindowHandles);



The currently focused pop-window is closed and a SwitchTo() command is used to switch to the other pop-up window shown on the screen. The API will close pop-up windows in the order popup6.html — popup5.html — popup4.html — popup3.html — popup2.html — popup1.html. The API returns true when all pop-ups are closed and the Parent window is the currently focused window.

C#
 




xxxxxxxxxx
1
14


 
1
foreach (String WindowHandle in totWindowHandles)
2
{
3
    if (!WindowHandle.Equals(currWindowHandle))
4
      {
5
         driver.SwitchTo().Window(WindowHandle);
6
         driver.Close();
7
      }
8
}
9
 
10
if (driver.WindowHandles.Count == 1)
11
           return true;
12
....................................
13
....................................
14

          



The implementation under [Test] annotation uses these helper functions to perform Selenium test automation. The Window Title of the parent window is compared to verify the closure of all the pop-up windows.

C#
 




xxxxxxxxxx
1


 
1
String windowTitle = getCurrWindowTitle();
2
String mainWindow = getMainWinHandle(driver);
3
Assert.IsTrue(closeAllWindows(mainWindow));
4
 
5
/* Addition of delay for checking the output */
6
System.Threading.Thread.Sleep(4000);
7
Assert.IsTrue(windowTitle.Contains(expected_win_title), "Title does not match - Test Failed");
8

          



The Window handles of the pop-up windows and parent window are below:

standard output

Below is the execution snapshot from Visual Studio which indicates that our Selenium Automation tests have passed

NUnit

As the implementation is written generically, the same implementation can be used for verifying pop-up window handling with any other website.

This article was a part Selenium C# tutorial series, where I've explained how to set up visual studio, handle the implicit wait, handle explicit and fluent waits, and handling alert windows. If you haven’t gone through them, I'd encourage you to go through them!

All in All

Browser windows, including tabs, are identified using Window Handles. These handles are used in conjunction with SwitchTo.Window() Selenium API to handle browser windows, tabs, and pop-up windows. In this Selenium C# tutorial, we had a deep-dive look into all the available scenarios with web browsers.

It’s a wrap! This was all I had to share in this Selenium C# tutorial. If you liked this article feel free to share it with your friends, you can retweet it on twitter or your favorite social media account to help us reach out to more people.

Happy Testing ☺

csharp Command (computing) Testing Test automation

Published at DZone with permission of Himanshu Sheth. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Selenium vs Cypress: Does Cypress Replace Selenium?
  • Getting Started With WebdriverIO Typescript Jasmine
  • Cypress Web Automation
  • AI-Driven Test Automation Techniques for Multimodal Systems

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!