I have a code that you might like. The quickest solution is to use the Popup Finder, but I also made my own method. I will never rely on the order that Window Handles processes to select the appropriate window. Popup window search:
PopupWindowFinder finder = new PopupWindowFinder(driver); driver.SwitchTo().Window(newWin);
My custom method. Basically, you give it the element you want to click, your webdriver and, if necessary, the time to wait before searching after clicking on the element.
It takes all of your current descriptors and makes a list. It uses this list to eliminate pre-existing windows from being accidentally switched. Then he clicks on the item that launches a new window. There should always be some kind of delay after the click, since nothing happens instantly. And then he creates a new list and compares it with the old one, until he finds a new window or the loop expires. If it cannot find a new window, it returns null, so if you have an iffy web element that does not always work, you can perform a null check to see if the switch is working.
public static string ClickAndSwitchWindow(IWebElement elementToBeClicked, IWebDriver driver, int timer = 2000) { System.Collections.Generic.List<string> previousHandles = new System.Collections.Generic.List<string>(); System.Collections.Generic.List<string> currentHandles = new System.Collections.Generic.List<string>(); previousHandles.AddRange(driver.WindowHandles); elementToBeClicked.Click(); Thread.Sleep(timer); for (int i = 0; i < 20; i++) { currentHandles.Clear(); currentHandles.AddRange(driver.WindowHandles); foreach (string s in previousHandles) { currentHandles.RemoveAll(p => p == s); } if (currentHandles.Count == 1) { driver.SwitchTo().Window(currentHandles[0]); Thread.Sleep(100); return currentHandles[0]; } else { Thread.Sleep(500); } } return null; }
source share