31

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?

Thomasleveil
  • 95,867
  • 15
  • 119
  • 113
Ozone
  • 357
  • 1
  • 3
  • 13

9 Answers9

30

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);
    }
}
Pseudo Sudo
  • 1,402
  • 3
  • 16
  • 34
Santoshsarma
  • 5,627
  • 1
  • 24
  • 39
  • 4
    There can be case when the new tab is opened but handle not yet added to drive instance. My solution is before click get current handle count and then inside while loop check if count changed. Only then switch to newly opened tab like this `driver.switchTo().window(handles[handles.count() - 1]);` where `handles` are updated on each iteration. – Mr. Blond Dec 17 '15 at 11:56
  • @Mr.Blond I agree. That is a core issue that causes selenium to fail randomly. The solution is to diff counts, but more preferably inside `WebDriverWait.until()` – Marinos An Jan 18 '23 at 11:07
13

You could wait until the operation succeeds e.g., in Python:

from selenium.common.exceptions    import NoSuchWindowException
from selenium.webdriver.support.ui import WebDriverWait

def found_window(name):
    def predicate(driver):
        try: driver.switch_to_window(name)
        except NoSuchWindowException:
             return False
        else:
             return True # found window
    return predicate

driver.find_element_by_id("id of the button that opens new window").click()        
WebDriverWait(driver, timeout=50).until(found_window("new window name"))
WebDriverWait(driver, timeout=10).until( # wait until the button is available
    lambda x: x.find_element_by_id("id of button present on newly opened window"))\
    .click()
jfs
  • 399,953
  • 195
  • 994
  • 1,670
2

I finally found the answer, I used the below method to switch to the new window,

public String switchwindow(String object, String data){
        try {

        String winHandleBefore = driver.getWindowHandle();

        for(String winHandle : driver.getWindowHandles()){
            driver.switchTo().window(winHandle);
        }
        }catch(Exception e){
        return Constants.KEYWORD_FAIL+ "Unable to Switch Window" + e.getMessage();
        }
        return Constants.KEYWORD_PASS;
        }

To move to parent window, i used the following code,

 public String switchwindowback(String object, String data){
            try {
                String winHandleBefore = driver.getWindowHandle();
                driver.close(); 
                //Switch back to original browser (first window)
                driver.switchTo().window(winHandleBefore);
                //continue with original browser (first window)
            }catch(Exception e){
            return Constants.KEYWORD_FAIL+ "Unable to Switch to main window" + e.getMessage();
            }
            return Constants.KEYWORD_PASS;
            }

I think this will help u to switch between the windows.

Prasanna
  • 468
  • 3
  • 11
  • 26
1

I use this to wait for window to be opened and it works for me.

C# code:

public static void WaitUntilNewWindowIsOpened(this RemoteWebDriver driver, int expectedNumberOfWindows, int maxRetryCount = 100)
    {
        int returnValue;
        bool boolReturnValue;
        for (var i = 0; i < maxRetryCount; Thread.Sleep(100), i++)
        {
            returnValue = driver.WindowHandles.Count;
            boolReturnValue = (returnValue == expectedNumberOfWindows ? true : false);
            if (boolReturnValue)
            {
                return;
            }
        }
        //try one last time to check for window
        returnValue = driver.WindowHandles.Count;
        boolReturnValue = (returnValue == expectedNumberOfWindows ? true : false);
        if (!boolReturnValue)
        {
            throw new ApplicationException("New window did not open.");
        }
    }

And then i call this method in the code

Extensions.WaitUntilNewWindowIsOpened(driver, 2);
DadoH
  • 46
  • 4
1

You can wait for another window to pop using WebDriverWait. First you have to save current handles of all opened windows:

private Set<String> windowHandlersSet = driver.getWindowHandles();

Then you click a button to open a new window and wait for it to pop with:

WebDriverWait wait = new WebDriverWait(driver, 10);
wait.until(driver -> !driver.getWindowHandles().equals(windowHandlersSet));

Which checks if there is a change to current window handles set comparing to saved one. I used this solutnion writing tests under Internet Explorer where it always takes few seconds to open new window.

zjadarka
  • 93
  • 5
1
    WebDriverWait wait = new WebDriverWait(driver,Duration.ofSeconds(max duration you want it to check for new window));
    wait.until(ExpectedConditions.numberOfWindowsToBe(2));//here 2 represents the current window and the new window to be opened
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • 2
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel Feb 14 '21 at 17:25
0

Although this question already has answers, none of them was useful to me really since I can't rely on getting any new window, I needed to filter even more, so I started using Dadoh's solution but tweaked it until I came up with this solution, hope it will be of some use to someone.

public async Task<string> WaitUntilNewWindowIsOpen(string expectedWindowTitle, bool switchToWindow, int maxRetryCount = 100)
{
    string newWindowHandle = await Task.Run(() =>
    {
        string previousWindowHandle = _driver.CurrentWindowHandle;
        int retries = 0;
        while (retries < maxRetryCount)
        {
            foreach (string handle in _driver.WindowHandles)
            {
                _driver.SwitchTo().Window(handle);
                string title = _driver.Title;
                if (title.Equals(expectedWindowTitle))
                {
                    if(!switchToWindow)
                        _driver.SwitchTo().Window(previousWindowHandle);
                    return handle;
                }
            }
            retries++;
            Thread.Sleep(100);
        }
        return string.Empty;
    });
    return newWindowHandle;
}

So in this solution I opted to pass the expected window title as an argument for the function to loop all windows and compare the new window title, this way, it's guaranteed to return the correct window. Here is an example call to this method:

await WaitUntilNewWindowIsOpen("newWindowTitle", true);
HeD_pE
  • 11
  • 1
  • 4
0

Below function can wait for given max time until your new window is open

public static void waitForWindow(int max_sec_toWait, int noOfExpectedWindow) {
    FluentWait<WebDriver> wait = new FluentWait<WebDriver>(driver);
    wait.pollingEvery(Duration.ofMillis(200));
    wait.withTimeout(Duration.ofSeconds(max_sec_toWait));
    wait.ignoring(NoSuchWindowException.class);
    Function<WebDriver, Boolean> function = new Function<WebDriver, Boolean>(){
        @Override
        public Boolean apply(WebDriver driver) {
            Set<String> handel = driver.getWindowHandles();
            if(handel.size() == noOfExpectedWindow) 
                return true;
            else 
                return false;
            }
    };      
    wait.until(function);
}
joy87
  • 25
  • 4
0

Js code

     await firstPage.clickOnLink();
        let tabs = await driver.getAllWindowHandles();
        await driver.switchTo().window(tabs[1]);
        await driver.wait(await until.titleContains('myString'), 2000);
Dotista
  • 404
  • 3
  • 12