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

Arun Kumar picture Arun Kumar · Oct 1, 2013 · Viewed 183.8k times · Source

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?

Answer

CODEBLACK picture CODEBLACK · Oct 1, 2013

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