Reputation: 9080
I have a site that opens a new (smaller) browser window, which I'm trying to test in Selenium.
I am using the ChromeWebDriver (2.27).
I have the following code:
String parentHandle = Driver.Instance.WindowHandles[0].ToString();
String modalHandel = Driver.Instance.WindowHandles[1].ToString();
I've tried several different variations (i.e. using ReadOnlyCollections & for loops) with the same result.
When I look at Driver.Instace.WindowHandles I see 2 entries. The 1st one (I'm guessing) is my main window and the 2nd one is the modal.
However, about 50% of the time this code errors.
String modalHandel = Driver.Instance.WindowHandles[1].ToString();
Stating that:
Index was out of range. Must be non-negative and less than the size of the collection.
Maybe it is late in the day, but I really don't understand why this sometimes works and sometimes it doesn't. Can anyone please shed some light on this?
Upvotes: 0
Views: 149
Reputation: 50819
It might be timing issue, the smaller browser might open after you are looking for its WindowHandle
so Driver.Instance.WindowHandles
contains only the parent WindowHandle
. You can try to wait until there are two handles
ReadOnlyCollection<string> windowHandles;
while ((windowHandles = Driver.Instance.WindowHandles).Count < 2);
string parentHandle = windowHandles[0]; // its already string, no need to call ToString()
string modalHandel = windowHandles[1];
You can also limit the time
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
ReadOnlyCollection<string> windowHandles;
while ((windowHandles = driver.WindowHandles).Count < 2 && stopwatch.Elapsed.TotalSeconds < 10);
string parentHandle = windowHandles[0];
string modalHandel = windowHandles[1];
Upvotes: 1