[java] How to handle the new window in Selenium WebDriver using Java?

This is my code:

driver.findElement(By.id("ImageButton5")).click();
//Thread.sleep(3000);
String winHandleBefore = driver.getWindowHandle();
driver.switchTo().window(winHandleBefore);
driver.findElement(By.id("txtEnterCptCode")).sendKeys("99219");

Now I have the next error:

Exception in thread "main" org.openqa.selenium.NoSuchElementException: Unable to find element with id == txtEnterCptCode (WARNING: The server did not provide any stacktrace information) Command duration or timeout: 404 milliseconds.

Any ideas?

This question is related to java selenium-webdriver new-window

The answer is


I have an utility method to switch to the required window as shown below

public class Utility 
{
    public static WebDriver getHandleToWindow(String title){

        //parentWindowHandle = WebDriverInitialize.getDriver().getWindowHandle(); // save the current window handle.
        WebDriver popup = null;
        Set<String> windowIterator = WebDriverInitialize.getDriver().getWindowHandles();
        System.err.println("No of windows :  " + windowIterator.size());
        for (String s : windowIterator) {
          String windowHandle = s; 
          popup = WebDriverInitialize.getDriver().switchTo().window(windowHandle);
          System.out.println("Window Title : " + popup.getTitle());
          System.out.println("Window Url : " + popup.getCurrentUrl());
          if (popup.getTitle().equals(title) ){
              System.out.println("Selected Window Title : " + popup.getTitle());
              return popup;
          }

        }
                System.out.println("Window Title :" + popup.getTitle());
                System.out.println();
            return popup;
        }
}

It will take you to desired window once title of the window is passed as parameter. In your case you can do.

Webdriver childDriver = Utility.getHandleToWindow("titleOfChildWindow");

and then again switch to parent window using the same method

Webdriver parentDriver = Utility.getHandleToWindow("titleOfParentWindow");

This method works effectively when dealing with multiple windows.


I have a sample program for this:

public class BrowserBackForward {

/**
 * @param args
 * @throws InterruptedException 
 */
public static void main(String[] args) throws InterruptedException {
    WebDriver driver = new FirefoxDriver();
    driver.get("http://seleniumhq.org/");
    driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
    //maximize the window
    driver.manage().window().maximize();

    driver.findElement(By.linkText("Documentation")).click();
    System.out.println(driver.getCurrentUrl());
    driver.navigate().back();
    System.out.println(driver.getCurrentUrl());
    Thread.sleep(30000);
    driver.navigate().forward();
    System.out.println("Forward");
    Thread.sleep(30000);
    driver.navigate().refresh();

}

}


                string BaseWindow = driver.CurrentWindowHandle;
                ReadOnlyCollection<string> handles = driver.WindowHandles;
                foreach (string handle in handles)
                {
                    if (handle != BaseWindow)
                    {
                        string title = driver.SwitchTo().Window(handle).Title;
                        Thread.Sleep(3000);
                        driver.SwitchTo().Window(handle).Title.Equals(title);
                        Thread.Sleep(3000);
                    }
                }

i was having some issues with windowhandle and tried this one. this one works good for me.

String parentWindowHandler = driver.getWindowHandle(); 
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles();
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
    driver.switchTo().window(subWindowHandler);

    System.out.println(subWindowHandler);
}


driver.switchTo().window(parentWindowHandler); 

Set<String> windows = driver.getWindowHandles();
Iterator<String> itr = windows.iterator();

//patName will provide you parent window
String patName = itr.next();

//chldName will provide you child window
String chldName = itr.next();

//Switch to child window
driver.switchto().window(chldName);

//Do normal selenium code for performing action in child window

//To come back to parent window
driver.switchto().window(patName);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java

Examples related to new-window

Javascript window.print() in chrome, closing new window or tab instead of cancelling print leaves javascript blocked in parent window How to handle the new window in Selenium WebDriver using Java? Open URL in new window with JavaScript How to switch to the new browser window, which opens after click on the button? Can I create links with 'target="_blank"' in Markdown?