public static void SwitchToTab(this IWebDriver webDriver, string urlSegment) { if (string.IsNullOrWhiteSpace(urlSegment)) { throw new ArgumentNullException(); } AsyncWebDriverCalls asyncCalls = new AsyncWebDriverCalls(); Task <ReadOnlyCollection <string> > getWindowHandlesTask = asyncCalls.GetWindowHandlesAsync(webDriver); getWindowHandlesTask.Wait(); ReadOnlyCollection <string> windowHandles = getWindowHandlesTask.Result; if (windowHandles.Count <= 1) { TestLog.Add("Only one Tab recognized. Cancelling tabswitch => unnecessary."); return; } TestLog.Add("Try switching to tab with url containing '" + urlSegment + "'. tabcount: " + windowHandles.Count); bool tabFound = false; int currentTabWindowIndex = windowHandles.IndexOf(webDriver.CurrentWindowHandle); for (int index = currentTabWindowIndex; index <= windowHandles.Count; index++) { int realIndex = (index + currentTabWindowIndex + 1) % windowHandles.Count; if (DoTabSwitchWithIndex(realIndex, webDriver, urlSegment, asyncCalls, windowHandles)) { tabFound = true; break; } } if (tabFound) { return; } TestLog.Add("No window with url containing: " + urlSegment); TestLog.Add("Current WindowHandle-Url: " + webDriver.Url); throw new Exception("No window with url-segment: '" + urlSegment + "'"); }
private static bool DoTabSwitchWithIndex(int index, IWebDriver webDriver, string urlSegment, AsyncWebDriverCalls asyncCalls, ReadOnlyCollection <string> windowHandles) { string windowHandle = windowHandles[index]; Task <string> getCurrentUrlTask = asyncCalls.GetCurrentUrlTask(webDriver); getCurrentUrlTask.Wait(); webDriver.SwitchTo().Window(windowHandle); Task <bool> nextUrlTask = asyncCalls.TabActuallySwitched(webDriver, urlSegment, getCurrentUrlTask.Result); nextUrlTask.Wait(); if (!nextUrlTask.Result) { return(false); } Task <string> task = asyncCalls.GetCurrentUrlTask(webDriver); task.Wait(); string urlAfterSwitch = task.Result; TestLog.Add("Switched to tab with url-segment " + urlSegment + ". Full url = " + urlAfterSwitch); asyncCalls.WaitWindowMaximize(webDriver); return(true); }