Selenium C# Tutorial: Identifying and handling a pop-up window

Updated: Jan 18

A window in any browser is considered the main webpage on which the user is landed after hitting a link/URL. In Selenium, this window is referred to as the parent window (AKA: Main Window), which opens when the Selenium WebDriver session is created and has all the focus of the Web Driver.


In Selenium WebDriver, testing the Pop-up window involves a few basic steps that you must follow to reduce errors related t the loss of focus in the window under test. Working with a pop-up window will include a few basic steps:

  1. Identifying the original window (Parent).

  2. Identifying a new pop-up window.

  3. Switching the Driver instance to the new pop-up window.

  4. Running the relevant tests.

  5. Switching back to the parent window.

The Selenium WebDriver allows us to identify and access a pop-up window by using core attributes (Title, name, etc.) or by using the window handle approach and switching between the pop-up window and the browser window using the Webdriver.switchTo().window() method.


Working with Browser Window Handles In Selenium

Before starting with code examples, we need to know how to identify different browser windows and tabs. The good news is that it's pretty straightforward; this is because every browser or tab instance has a Global Unique Identifier (GUID), which makes it ready easy to access them. Using GUID's identifiers, we can handle multiple windows in Selenium mainly by using two methods:


getWindowHandle() - This method will return a string value for the window handle of the current window in focus (GUID for the current active window in the browser). I


getWindowHandles() - This method will return a Set <String> for all the windows and tabs handles (GUID's) of windows that are opened in that session.


How does the "Switch" mechanism work?

As you will see in the following code examples, using the "SwitchTo" method is relatively simple. When using this method, we can notify the driver that we want to focus on a specific window different from the parent window (Opened initially at the start of the testing flow).


Syntax:

Driver.SwitchTo().Window("SwitchByName");

NoSuchWindowException Error

The driver.switchTo().window() method throws the NoSuchWindowException exception in any scenario that fails to identify the desired pop-up window. So, we must handle it with Try/Catch blocks to improve the test execution flow.



Code Examples

Identifying and handling a pop-up window by its name

In this example, we will identify and address a pop-up window by using its name attribute that may be different from its title in many scenarios.


Note!

We will only use the name attribute if the HTML code that triggered the new window contains the "window.open" function.


HTML

Code

[TestMethod]
        public void HandlingWindowName()
        {
            //Step 1: Get the Current Window Handle
            string Parent_Web_Page = driver.CurrentWindowHandle;           
            
            //Step 2: Trigger a new pop-up window
            tmpElement =  driver.FindElement(By.Id("helpbutton"));
            tmpElement.Click();

            try
            {
                //Phase 3: Switch to the new pop-up window by name
                driver.SwitchTo().Window("HelpWindow");
                Console.WriteLine(driver.Title);
                Assert.AreEqual(driver.Title, "file:///C:/Users/home-pc3/Desktop/help.html");               
            }
            catch (NoSuchWindowException ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

Output



Identifying and handling a pop-up window by its title

Many times the name attribute will not be assigned to a pop-up window. In such cases, we can always use its window handle attribute. However, the handle attribute is less reliable. It changes each time we run the test, making it impossible to identify the pop-up window, especially when more than one pop-up window is open. To overcome this issue, we can use both the handle and title attributes of the page displayed in a pop-up window to ensure the reliability of the test execution and reduce failures related to NoSuchWindowException Errors.


In this recipe, we will create a test that retrieves the handles of all open windows in the current driver context.


Code

[TestMethod]
public void HandlingWindowTitle()
{            driver.Navigate().GoToUrl("https://www.agilequalitymadeeasy.com/blog");
//Save the WindowHandle of Parent Browser window            
string ParentBrowserWindow = driver.CurrentWindowHandle;

//Open a new TAB
IWebElement LinkedIn = driver.FindElement(By.CssSelector("#img_2_comp-khbyvzck4 > img:nth-child(1)"));
LinkedIn.Click();
System.Threading.Thread.Sleep(5000);

//returns the handles of all the open pop-up windows in a list as follows
IList<string> ListOfWindowHandles = driver.WindowHandles;

//Verify Handles count )
Assert.AreEqual(2,ListOfWindowHandles.Count);

//We can then iterate through this list and find out the matching pop-up window by checking the title of each window
foreach (var title in ListOfWindowHandles)
{
try
{
if (driver.SwitchTo().Window(title).Title == "Sign Up | LinkedIn")
{
//Validating That the driver focus is on the second tab
Console.WriteLine(driver.Title);
                        
//Closing TAB
driver.Close();                        
}                    
}
catch (Exception ex)
{                    
Console.WriteLine(ex.Message);
}
//Move and verify that the driver focus is on the parent tab
driver.SwitchTo().Window(ParentBrowserWindow);
Console.WriteLine(driver.Title);
Assert.IsTrue(driver.Title.Contains("Agile"));
}
}

Output

Identifying and handling a pop-up window by its content

We will have to work with a pop-up window that has neither the 'name' attribute nor a title in certain situations. To handle it, we have a workaround; as we saw in previous examples, we can check the contents of each window returned by the driver.getWindowHandles() method to identify the desired pop-up window.


In the following test, we will retrieve the handles of all the open windows in the current driver Context, switching to the window and then checking for the content, which will ensure we identify the correct window as follows:


Code

[TestMethod]
public void HandlingWindowContent()
{
            driver.Navigate().GoToUrl("https://www.agilequalitymadeeasy.com/blog");
//Save the WindowHandle of Parent Browser window            
string ParentBrowserWindow = driver.CurrentWindowHandle;

//Open a new TAB
IWebElement LinkedIn = driver.FindElement(By.CssSelector("#img_2_comp-khbyvzck4 > img:nth-child(1)"));
LinkedIn.Click();
System.Threading.Thread.Sleep(5000);

//returns the handles of all the open pop-up windows in a list as follows
IList<string> ListOfWindowHandles = driver.WindowHandles;

//Verify Handles count )
Assert.AreEqual(2, ListOfWindowHandles.Count);

//We can then iterate through this list and find out the matching pop-up window by checking for a specific string in the PageSource
foreach (var window in ListOfWindowHandles)
{
try
{
if (driver.SwitchTo().Window(window).PageSource.Contains("Sign Up | LinkedIn"))
{
//Validating That the driver focus is on the second tab
Console.WriteLine(driver.Title);

//Closing TAB
driver.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}                              
}
}

Output



156 views0 comments