Enroll in Selenium Training

On an HTML page, a link can open up in a new window. This is quite common and can be found on our Test Practice Page here. Click on the very first button and it will launch another window and load http://toolsqa.com in the new window. In this chapter, we will see How to Handle Multiple Windows using Selenium WebDriver. For this tutorial, we will use our test page https://demoqa.com/browser-windows .

Basics of Multiple Window

There is only one way you can get multiple windows via Selenium web driver, that is by clicking on a link which opens the page in a new browser window. Selenium web driver keeps a track of how many windows it opened during a session. Which means that it will not keep track of any browser window which is - Opened manually - Opened by a previous session of Selenium Webdriver By session of selenium WebDriver we mean the duration from the time we instantiate a WebDriver instance to the time we kill it via WebDriver.Quit or by manually killing the process. With this understanding lets first open some windows using Selenium WebDriver. To achieve this all we have to do is to click on the button on our practice page.

Here is the code for that

namespace ToolsQA.Selenium_Basics
{
    class MultipleWindow
    {
        [Test]
        public void Test()
        { 
			IWebDriver driver = new FirefoxDriver();

			driver.Url = "https://demoqa.com/browser-windows";

			// Store the parent window of teh driver
			String parentWindowHandle = driver.CurrentWindowHandle;
			Console.WriteLine("Parent window's handle -> " + parentWindowHandle);

			IWebElement clickElement = driver.FindElement(By.Id("button1"));

			// Multiple click to open multiple window
			for (var i = 0; i < 3; i++)
			{
				clickElement.Click();
				Thread.Sleep(3000);
			}
        }
    }
}

This will click on the "New Browser Window" button three times. As a result there will be 4 windows that will come into existence. Keep in mind that the window opened during driver initialization is the Parent window.

This is how the windows will look like

AllWindowOpen

Note: Pay attention to the markings which I have provided for each window.

How to Handle Window in Selenium CSharp?

To uniquely identify an opened browser Selenium WebDriver keeps a map of Opened windows VS Window Handle. Window handle is a unique string value that uniquely identifies a Browser window on desktop. It is guaranteed that each browser will have a unique window handle. To get Window handle WebDriver interface provides two methods CurrentWindowHandle - WindowHandles

CurrentWindowHandle

CurrentWindowHandle

CurrentWindowHandle method return a string value and it returns the Window handle of current focused browser window. WindowHandles. This method returns a ReadOnlyCollection (You need to typecast this collection to List Collection by using ToList()) of all Window handles of all the browsers that were opened in the session.

CurrentWindowHandle 3

In this case it will return 4 windows handles because we have 4 windows open. Here is the code to print out window handles on console of eclipse.

namespace ToolsQA.Selenium_Basics
{
    class PrintOutWindowHandles
    {
        [Test]
        public void Test()
        { 
			IWebDriver driver = new FirefoxDriver();
			driver.Url = "https://demoqa.com/browser-windows";

			// Store the parent window of the driver
			String parentWindowHandle = driver.CurrentWindowHandle;
			Console.WriteLine("Parent window's handle -> " + parentWindowHandle);

			IWebElement clickElement = driver.FindElement(By.Id("button1"));

			// Multiple click to open multiple window
			for (var i = 0; i < 3; i++)
			{
				clickElement.Click();
				Thread.Sleep(3000);
			}

			// Store all the opened window into the list 
			// Print each and every items of the list
			List<string> lstWindow = driver.WindowHandles.ToList();
			foreach (var handle in lstWindow)
			{
				Console.WriteLine(handle);
			}
			
        }
    }
}

Console Output : This is the output that you will get on console. Pay attention to the Window handle values, they are unique to each other

CurrentWindowHandle

How to Handle Multiple Windows in Selenium CSharp?

There is a concept of current focused window which means that all selenium webdriver commands will go to the focused window. By default the focus is always on the Parent window, please see the screenshot above. In order to shift focus from Parent Window to any child window we have to use the following command on WebDriver – driver.SwitchTo().Window(String WindowHandle); This command takes in a window handle and switches the driver context on that window. Once the Switch happens all the driver commands will go to the newly focused window. This is very important to understand, without switching to the desired window we will not be able to perform any action on that window. Now let's see some code which iteratively moves across all the open windows and navigates to a particular page in all the open windows one by one.

namespace ToolsQA.Selenium_Basics
{
    class HandleMultipleWindows
    {
        [Test]
        public void Test()
        { 
			IWebDriver driver = new FirefoxDriver();
			driver.Url = "https://demoqa.com/browser-windows";

			// Store the parent window of the driver
			String parentWindowHandle = driver.CurrentWindowHandle;
			Console.WriteLine("Parent window's handle -> " + parentWindowHandle);

			IWebElement clickElement = driver.FindElement(By.Id("button1"));

			// Multiple click to open multiple window
			for (var i = 0; i < 3; i++)
			{
				clickElement.Click();
				Thread.Sleep(3000);
			}

			// Store all the opened window into the 'list' 
			List<string> lstWindow = driver.WindowHandles.ToList();

			// Traverse each and every window 
			foreach (var handle in lstWindow)
			{
				Console.WriteLine("Switching to window - > " + handle);
				Console.WriteLine("Navigating to google.com");

				//Switch to the desired window first and then execute commands using driver
				driver.SwitchTo().Window(handle); 
				driver.Navigate().GoToUrl("https://google.com");
			}
			
        }
    }
}

Closing all the Windows

There are basically two commands that we can use to close the opened browser windows WebDriver.close() and  WebDriver.Quit().

WebDriver.Close() command will close the current window on which the focus is present. This can be used to close windows selectively. Just switch to the window that you want to close by using the correct Window handle and the call the WebDriver.Close command. That will close the current browser window.

Note: After closing a window you have to explicity switch to another valid window before sending in any WebDriver commands. if you fail to do this you wil get following exception. org.openqa.selenium.NoSuchWindowException: Window not found. The browser window may have been closed.

CurrentWindowHandle 5

In the code below we will close the parent window and then explicitly move focus to the last window in the list.

namespace ToolsQA.Selenium_Basics
{
    class ClosingAllWindows
    {
        [Test]
        public void Test()
        { 
			IWebDriver driver = new FirefoxDriver();
			driver.Url = "https://demoqa.com/browser-windows";

			// Store the parent window into a variable for further use 
			String parentWindowHandle = driver.CurrentWindowHandle;
			Console.WriteLine("Parent window's handle -> " + parentWindowHandle);

			IWebElement clickElement = driver.FindElement(By.Id("button1"));
			//I am using 'for' loop to get multiple windows by clicking the element
			for (var i = 0; i < 3; i++)
			{
				clickElement.Click();
				Thread.Sleep(3000);
			}

			/*
			* driver.WindowHandles is a ReadOnlycollection So i am using '.ToList()' and store into the 'List<string>'
			* Again using 'for loop' to traverse all window which are opened by the above loop 
			* then i use '.SwitchTo().Window'. Basically this is use to switch your control from parent window to current window
			**/
			
			List<string> lstWindow = driver.WindowHandles.ToList();
			String lastWindowHandle = "";
			foreach (var handle in lstWindow)
			{
				Console.WriteLine("Switching to window - > " + handle);
				Console.WriteLine("Navigating to google.com");

				//Switch to the desired window first and then execute commands using driver
				driver.SwitchTo().Window(handle); 

				driver.Navigate().GoToUrl("https://google.com");
				lastWindowHandle = handle;
			}

			//Switch to the parent window
			driver.SwitchTo().Window(parentWindowHandle);

			//close the parent window
			driver.Close();

			//at this point there is no focused window, we have to explicitly switch back to some window.
			driver.SwitchTo().Window(lastWindowHandle);

			driver.Url = "https://toolsqa.com";
			
        }
    }
}

WebDriver.Quit() will close all the windows opened in the session. This command basically shuts down the driver instance and any further commands to WebDriver results in exception.   That's pretty much it that we have on handling multiple windows. Do let your comments flow in.

How to Handle Alert And Popup Box in Selenium CSharp
How to Handle Alert And Popup Box in Selenium CSharp
Previous Article
Implicit Wait Commands in Selenium WebDriver C#
Implicit Wait Commands in Selenium WebDriver C#
Next Article

Similar Articles

Feedback