17

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?

Ripon Al Wasim
  • 36,924
  • 42
  • 155
  • 176
Arun Kumar
  • 225
  • 2
  • 8
  • 20

6 Answers6

42

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
CODEBLACK
  • 1,239
  • 1
  • 15
  • 26
  • 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.findElement(By.id("chklstAllprocedure_0")).click(); The error i got is unable to find the textbox element in newly opened window.Can you help me out this? – Arun Kumar Oct 03 '13 at 03:56
  • 1
    @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 Oct 03 '13 at 08:54
  • WebDriverWait will wait until your specified element is visible... and once it becomes visible it will continue running your code... – CODEBLACK Oct 03 '13 at 08:55
  • 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" – CODEBLACK Oct 03 '13 at 09:00
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.

Abhishek Singh
  • 10,243
  • 22
  • 74
  • 108
  • There's no point in returning the `WebDriver` instance because it's the same one you are already using. – JeffC Mar 27 '17 at 01:42
2
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);
smac89
  • 39,374
  • 15
  • 132
  • 179
0

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

}

}

Sathish D
  • 4,854
  • 31
  • 44
0
                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);
                    }
                }
Kamil Budziewski
  • 22,699
  • 14
  • 85
  • 105
0

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); 
Golden Hash
  • 21
  • 1
  • 6