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

104,578

Solution 1

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);
    }
}

Solution 2

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()

Solution 3

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.

Solution 4

    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

Solution 5

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);
Share:
104,578
Ozone
Author by

Ozone

Updated on January 10, 2022

Comments

  • Ozone
    Ozone over 2 years

    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?

  • Mr. Blond
    Mr. Blond over 8 years
    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.
  • Mark Rotteveel
    Mark Rotteveel over 3 years
    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.