Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 680
Arun Kumar Avatar asked Oct 01 '13 09:10

Arun Kumar


People also ask

How does Selenium handle open a new window?

Open a New Tab await driver. get('https://selenium.dev'); // A new tab is opened and switches to it await driver. switchTo(). newWindow('tab'); // Loads Sauce Labs open source website in the newly opened window await driver.

How do you handle windows in Selenium?

The window handle is a unique identifier that stores the values of windows opened on a webpage and helps in window handling in Selenium. getWindowHandles( ) and getWindowHandles( ) handle windows in Selenium. The user has to switch from the parent window to the child window to work on them using switchTo( ) method.

Which of the following methods is used to handle a window in Webdriver?

Webdriver provides us below methods to manage windows. We can control the size and position of the current window with the following methods. – . maximize() – It maximizes the current window.


1 Answers

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
like image 151
CODEBLACK Avatar answered Sep 28 '22 12:09

CODEBLACK