This is a follow-up to a previous question that I asked here.
I previously encountered an issue with switching windows in Internet Explorer 10 using Selenium 2.37.0. My C# program would navigate to a page, click a button that opens a link, and attempt to navigate to the new window to perform additional tasks. My program kept failing, and I determined that this was because of Selenium's window handles. After opening a new window, the number of window handles (driver.WindowHandles.Count
) increases from 1 to 2, as expected, but after some amount of time, the number of window handles drops back down to 1.
I have created a minimal sample webpage that reproduces this issue. Simply save the following code into a file called test.aspx
on your desktop:
<html xmlns="http://www.w3.org/1999/xhtml" >
<body>
<input id="btn" type="button" value="Link" lang="javascript" onclick="window.open('test.aspx')">
</body>
</html>
Here is my C# code (a Console project in Visual Studio 2010 called TestWindowSwitching
) that opens this page, clicks the button, and prints some output:
using System;
using System.Threading; // Needed for Sleep
using System.Diagnostics; // Needed for Stopwatch
using OpenQA.Selenium;
using OpenQA.Selenium.IE;
namespace TestWindowSwitching
{
class Program
{
static void Main()
{
IWebDriver driver = new InternetExplorerDriver();
driver.Navigate().GoToUrl("C:\Users\yourNameHere\Desktop\test.aspx");
try { driver.SwitchTo().DefaultContent(); }
catch { Thread.Sleep(10); }
Console.WriteLine("Initial number of window handles: " + driver.WindowHandles.Count);
Stopwatch sw = new Stopwatch();
try { driver.FindElement(By.Id("btn")).Click(); }
catch { Thread.Sleep(10); }
// Wait until number of window handles becomes 2
while (driver.WindowHandles.Count != 2)
{
// Do nothing
}
sw.Start();
// Wait until number of window handles changes from 2
while (driver.WindowHandles.Count == 2)
{
// Do nothing
}
Console.WriteLine("Number of window handles has dropped to " + driver.WindowHandles.Count
+ " in " + sw.ElapsedMilliseconds + " ms");
sw.Stop();
Console.Write("Press Enter to close...");
Console.ReadLine();
driver.Quit();
}
}
}
Here's some sample output for that code:
Initial number of window handles: 1
Number of window handles dropped to 1 in 59 ms
Press Enter to close...
I previously created a workaround for this, so this actually isn't a problem for me anymore. I simply get the Javascript command (in this case, window.open('test.aspx')
) and use it directly to navigate to the page without opening a new window.
However, as I mentioned in my previous post, I feel that others may have encountered this issue (example 1, example 2), so if this is in fact a bug in Selenium, it is worth investigating. Or, if I am doing something wrong, suggestions are welcome.
See Question&Answers more detail:os