5

I am stuck when trying to switch windows using the latest version of webdriver in C#.

I have a base window, when i click a button, it opens a new window.

The target code for this button is as below.

window.open(uri, "DisplayPage", " width=1200, scrollbars=yes , resizable = yes ,   toolbar =  no , menubar =  no");

I am using the below mentioned code to target the new window

   string BaseWindow = _driver.CurrentWindowHandle;

   ReadOnlyCollection<string> handles = _driver.WindowHandles;

    foreach (string handle in handles)
    {

        if (handle != BaseWindow)
        {
            _driver.SwitchTo().Window(handle).Title.Equals("DisplayPage");

        }
    }
}

As you can see from above, I am switching to the window using the Target Title from the base window. This does not seem to work.

I then noticed that the Title of the opened window was different, it was "Display - Transaction Page"

I then modified the code to this

 string BaseWindow = _driver.CurrentWindowHandle;

       ReadOnlyCollection<string> handles = _driver.WindowHandles;

        foreach (string handle in handles)
        {

            if (handle != BaseWindow)
            {
                _driver.SwitchTo().Window(handle).Title.Equals("Display - Transaction Page");

            }
        }
    }

Still no luck.

Interestingly, I do not get any errors saying "Window not found".

The problem is that When i try to click on elements on the newly opened page, i get a NoSuchElementException which means that the newly opened window has not been targeted.

Any ideas?

Regards,

Hasan

4

2 回答 2

2

一旦窗口更改为您的窗口,您应该打破循环,否则它将始终切换到最后打开的窗口:

foreach (string handle in handles) {
 if (handle != BaseWindow) {
  if(_driver.SwitchTo().Window(handle).Title.Equals("Display - Transaction Page")) 
    break;
  }
}

您可以尝试使用Contains而不是equal,它将简化窗口搜索:

_driver.SwitchTo().Window(handle).Title.Contains("Display"); 
于 2012-06-12T07:07:52.297 回答
1

尽管您自己破解了答案,但还有另一种方法可以在 C# 中处理窗口之间的切换。

// initiate webdriver
IWebDriver driver = new FirefoxDriver();

//perform some action to open a new window. Like clicking a link.
driver.FindElement(By.Id("btnId")).Click();

//switch to new window.
driver.SwitchTo().Window(driver.WindowHandles.Last());

//if you want to switch back to your first window
driver.SwitchTo().Window(driver.WindowHandles.First());
于 2016-02-19T11:57:53.500 回答