CRich CRich - 2 months ago 62
C# Question

C# Selenium No new Window Handles When Opening A New Tab In Chrome and Firefox

Selenium for Chrome and Firefox, coding in C#, will not handle switching over to the new tab that is opening during my automation test. I don't think it focuses on the new tab open because when I run my program completely, I receive this error: "out of range" exception and "Index was out of range. Must be non-negative and less than the size of the collection."

I've tried using:

driver.SwitchTo().Window(driver.WindowHandles.Last());


and

driver.SwitchTo().Window(driver.WindowHandles[1]);
driver.SwitchTo().Window(driver.WindowHandles[0]).Close(); // close the first tab
System.Threading.Thread.Sleep(5000); //Wait 5 seconds just in case
driver.SwitchTo().Window(driver.WindowHandles[1]); //Makes sure I'm on the correct tab


but there is no luck. If I don't close the first tab, I receive the error: "NoSuchElementException:Unable to locate element:{method...}" which I assume is correct because the focus is still on the first tab. Any help would be greatly appreciated. Thank you.

Answer

Once you've closed tab[0], the old tab[1] becomes the new tab[0], so you should be switching to tab[0].

Selenium operates in the background so the window does not need to be in focus while it is running. This also means that Selenium will never change the focus back to the browser window. If you are watching the window while your code runs however you should be able to see the browser changing tabs.

Comments