s.k
s.k

Reputation: 3

Why Driver.SwitchTo not always works in selenium?

I use the code

windowHandles = SeleniumHelper.WindowHandles(); 

// click...

if (SeleniumHelper.WindowHandles().Count > windowHandles.Count)
{
    windowHandles = SeleniumHelper.WindowHandles();    
    while (pageTitle == SeleniumHelper.Driver.Title)
    {   
       SeleniumHelper.Driver.SwitchTo().Window(windowHandles[windowHandles.Count - 1]);
       Thread.Sleep(2000);                                                                         
    } 

    // do something...  

    SeleniumHelper.Driver.Close();
    SeleniumHelper.BackToMainWindow();
}

The problem is that the driver finds the window, but does not switch to it. Maybe there is a different way to switch to another window, like switch by javascript?

Upvotes: 0

Views: 594

Answers (1)

Guy
Guy

Reputation: 51009

The problem is in

SeleniumHelper.Driver.SwitchTo().Window(windowHandles[windowHandles.Count - 1]);

You always switch to the last window regardless the while loop condition. Try this

string currentWindoe = SeleniumHelper.Driver.CurrentWindowHandle();
while (pageTitle != SeleniumHelper.Driver.Title)
{   
    SeleniumHelper.Driver.SwitchTo().Window(SeleniumHelper.Driver.CurrentWindowHandle());
    Thread.Sleep(2000);                                                                         
}

Or

string currentWindow = SeleniumHelper.Driver.CurrentWindowHandle();
foreach (string window in SeleniumHelper.Driver.WindowHandles())
{
    if (!window.equals(currentWindow))
    {
        SeleniumHelper.Driver.SwitchTo().Window(window));
    }
}

Upvotes: 1

Related Questions