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

185,991

Solution 1

It seems like you are not actually switching to any new window. You are supposed get the window handle of your original window, save that, then get the window handle of the new window and switch to that. Once you are done with the new window you need to close it, then switch back to the original window handle. See my sample below:

i.e.

String parentHandle = driver.getWindowHandle(); // get the current window handle
driver.findElement(By.xpath("//*[@id='someXpath']")).click(); // click some link that opens a new window

for (String winHandle : driver.getWindowHandles()) {
    driver.switchTo().window(winHandle); // switch focus of WebDriver to the next found window handle (that's your newly opened window)
}

//code to do something on new window

driver.close(); // close newly opened window when done with it
driver.switchTo().window(parentHandle); // switch back to the original window

Solution 2

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.

Solution 3

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);
Share:
185,991

Related videos on Youtube

Arun Kumar
Author by

Arun Kumar

Updated on July 09, 2022

Comments

  • Arun Kumar
    Arun Kumar almost 2 years

    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?

  • Arun Kumar
    Arun Kumar over 10 years
    Now I cant enter the values in the textbox of new window through my code.String parentHandle = driver.getWindowHandle(); driver.findElement(By.id("ImageButton5")).click(); for (String winHandle : driver.getWindowHandles()) { driver.switchTo().window(winHandle); Thread.sleep(3000); driver.findElement(By.id("txtEnterCptCode")).sendKeys("99219‌​");driver.findElemen‌​t(By.id("chklstAllpr‌​ocedure_0")).click()‌​; The error i got is unable to find the textbox element in newly opened window.Can you help me out this?
  • CODEBLACK
    CODEBLACK over 10 years
    @Arun Kumar: perhaps webDriver is trying to find the element before the page is fully loaded? Thead.sleep is not effective because all it does is wait for a few secs before running the next lines of code. Try the WebDriverWait class. :::: WebDriverWait wait = new WebDriverWait(driver, 1000); WebElement element = wait.until(Expected Conditions.visibilityOfElementLocated(By.id("txtEnterCptCode‌​"))); element.sendKeys("99219");
  • CODEBLACK
    CODEBLACK over 10 years
    WebDriverWait will wait until your specified element is visible... and once it becomes visible it will continue running your code...
  • CODEBLACK
    CODEBLACK over 10 years
    NOTE i have a typo in my wait.until part of the code. There should be no space in "Expected Conditions". it should be "ExpectedConditions"
  • Niels van Reijmersdal
    Niels van Reijmersdal about 10 years
    Why the long sleeps? That is really bad practise.
  • Sathish D
    Sathish D almost 10 years
    That is just an example.
  • JeffC
    JeffC over 7 years
    There's no point in returning the WebDriver instance because it's the same one you are already using.