JumpIntoTheWater
JumpIntoTheWater

Reputation: 1336

Error when trying to switch window in Selenium

I have a scenario which I'm clicking on a button and then a new window pops up. Now, I can't find elements on the pop up window, so I'm trying to switch to the new window\pop up.

I have tried doing that but getting an error:

_webdriver.SwitchTo().Window("0bd0568d-df1f-4472-b20b-842e03d412bd");

the error I'm getting is :

NoSuchWindowException : No Window Found

I have found the window id by running the following:

foreach (string handle in _webdriver.WindowHandles)
{
    string popup = _webdriver.SwitchTo().Window(handle).ToString();
}  

Upvotes: 1

Views: 1323

Answers (2)

Guy
Guy

Reputation: 50819

The WindowHandle changes every time you open window, so you can't specifie it like that. Use the loop each time you want to switch.

In addition, SwitchTo().Window(handle) returns IWebDriver instance, not window id. Use driver.CurrentWindowHandle for this.

// get the current active window
string parentHandle = driver.CurrentWindowHandle;

// open new window

// switch to the new window
foreach (string handle in driver.WindowHandles)
{
    if (!handle.Equals(parentHandle))
    {
        driver.SwitchTo().Window(handle);
    }
}

Upvotes: 1

Kim Homann
Kim Homann

Reputation: 3229

The window handle's string value is generated dynamically at runtime and thus different every time you run your test.

You should look for driver.CurrentWindowHandle in driver.WindowHandles and then switch to the next one. Although this might cause problems when testing on Opera or Android.

bool bFound = false;
foreach (string windowHandle in driver.WindowHandles)
{
    if (bFound)
    {
        driver.SwitchTo().Window(windowHandle);
        break;
    }
    bFound = windowHandle == driver.CurrentWindowHandle;
}

Upvotes: 0

Related Questions