Arun Kumar Arun Kumar - 5 months ago 10
Java Question

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

This is my code:

String winHandleBefore = driver.getWindowHandle();

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?


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:


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