Total Pageviews

Tuesday 12 November 2013

Selenium WebDriver: Handling multiple windows

When testing web applications you may come across a few situations when you will need to handle multiple windows.

A common example of this could be clicking on a hyper-link which subsequently opens a new web-page in another window.

In some cases this may be a problem because Selenium WebDriver does not automatically switch to the new window.

Link
Visit my blog testautomationengineer.blogspot.co.uk

Below you will find an example detailing how to handle multiple windows:

[C#]

        [Test]
        public void OpenLinkInANewWindowThenSwitchToNewWindow()
        {
         driver.Navigate().GoToUrl("http://testautomationengineer.blogspot.com/2013/11/webdriver-handling-multiple-windows.html");
         
         // get the current windows handle
         string oldWindow = driver.CurrentWindowHandle;
         string newWindow = null;
         
         // open a link in a new window
         IWebElement element = driver.FindElement(By.Id("visitMyBlog"));
         element.SendKeys(Keys.Shift + Keys.Return);
         
         // wait for the new window
         WebDriverWait wait = new WebDriverWait(driver, new TimeSpan(0,0,5));
         wait.Until((d) => driver.WindowHandles.Count==2);
            
   // get the new window handle         
         var windowHandles = driver.WindowHandles;
         ReadOnlyCollection<string> windows = new ReadOnlyCollection<string>(windowHandles);
         foreach (string window in windows)
         {
          if(window != oldWindow)
          {
           newWindow = window;
          }
         }
         
         // switch to the new window
         driver.SwitchTo().Window(newWindow);
        }
Tips:

  • It is just as useful to keep track of your original window, as it is to keep track of your new window.
  • Each window in Selenium WebDriver has a unique handle identifier; this allows you to differentiate windows.
  • There may be a delay opening the new window, to avoid problems in this area wait for the count of window handles to increase.

Reference:

Gets the current window handle, which is an opaque handle to this window that uniquely identifies it within this driver instance.

Gets the window handles of open browser windows.

No comments:

Post a Comment