Handling pop up windows in Webdriver

In WebDriver, testing popup windows involve switching the driver to the popup window and then running the corresponding actions. Steps involved are:

  1. Identify the popup or new windows
  2. Switch to the new window
  3. Carry out some tasks
  4. Switch back to parent window

You can use the “WebDriver.SwitchTo().Window()” method to switch to a window with a known name. If the name is not known, you can use “WebDriver.WindowHandles()” to obtain a list of known windows. You may pass the handle to “SwitchTo().Window()”

You can usually get the window name by looking at the page source and checking for the value of the <title> tag. This name can then be passed to “SwitchTo().Window()”. For example:

// This method take in a name of a window as a parameter, and then switches to that window.
 
public void SwitchToWindow(string windowName)
{
 
_driver.SwitchTo().Window(windowName);
 
}

If you do not know the name of the window, you can use a different approach. For example.

 ReadOnlyCollection&lt;string&gt; handles = _driver.WindowHandles;
 
            foreach (string windowHandle in handles)
            {
               string newWindowName = _driver.SwitchTo().Window(windowHandle).Title;
               Console.WriteLine("Window Hadle is: " + windowHandle + " and Window Name is:
               " + newWindowName);
}

The above will print out the window handles and window titles of all open windows. You can then use the newly discovered window name in the SwitchToWindow function described above or use a new function like below:

 public void SwitchToWindow(string windowName)
        {
           string parentWindowHandle = _driver.CurrentWindowHandle;
 
            IWebDriver newWindow = null;
 
            ReadOnlyCollection&lt;string&gt; handles = _driver.WindowHandles;
 
            foreach (string windowHandle in handles)
            {
                newWindow = _driver.SwitchTo().Window(windowHandle);
 
                if (newWindow.Title.Equals(windowName))
                {
                    Console.WriteLine("Switching to window with handle " + windowHandle +
                    " and window name" + windowName );
                    break;
 
                }
            }
        }

See the first line of code in the above function. It captures the current window handle. In case you want to switch to the parent window, you can simply do this:

 _driver.SwitchTo().Window(parentWindowHandle);

Leave a Reply

Your email address will not be published.