How can selenium web driver get to know when the new window has opened and then resume its execution

Ozone picture Ozone · Feb 8, 2012 · Viewed 97.6k times · Source

I am facing an issue in automating a web application using selenium web driver.

The webpage has a button which when clicked opens a new window. When I use the following code, it throws OpenQA.Selenium.NoSuchWindowException: No window found

WebDriver.FindElement(By.Id("id of the button that opens new window")).Click();
//Switch to new window
_WebDriver.SwitchTo().Window("new window name");
//Click on button present on the newly opened window
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click();

To solve the above issue I add Thread.Sleep(50000); between the button click and SwitchTo statements.

WebDriver.FindElement(By.Id("id of the button that opens new window")).Click();
Thread.Sleep(50000); //wait
//Switch to new window
_WebDriver.SwitchTo().Window("new window name");
//Click on button present on the newly opened window
_WebDriver.FindElement(By.Id("id of button present on newly opened window")).Click();

It solved the issue, but I do not want to use the Thread.Sleep(50000); statement because if the window takes more time to open, code can fail and if window opens quickly then it makes the test slow unnecessarily.

Is there any way to know when the window has opened and then the test can resume its execution?

Answer

Santoshsarma picture Santoshsarma · Feb 8, 2012

You need to switch the control to pop-up window before doing any operations in it. By using this you can solve your problem.

Before opening the popup window get the handle of main window and save it.

String mwh=driver.getWindowHandle();

Now try to open the popup window by performing some action:

driver.findElement(By.xpath("")).click();

Set s=driver.getWindowHandles(); //this method will gives you the handles of all opened windows

Iterator ite=s.iterator();

while(ite.hasNext())
{
    String popupHandle=ite.next().toString();
    if(!popupHandle.contains(mwh))
    {
        driver.switchTo().window(popupHandle);
        /**/here you can perform operation in pop-up window**
        //After finished your operation in pop-up just select the main window again
        driver.switchTo().window(mwh);
    }
}