I am writing a selenium script to login and create new mail, send it and logout. But when I click on New mail button, it opens a new window. In selenium how I can handle this. I am new to selenium. Please explain in detail.
Use the below code, you have to use getWindowHandles- I hope it helps, Let me know in case you get stuck anywhere else -
@Test
public void multipleWindows() {
driver.get(URL+"/windows");
driver.findElement(By.cssSelector(".example a")).click();
Object[] allWindows = driver.getWindowHandles().toArray();
driver.switchTo().window(allWindows[0].toString());
Assert.assertNotEquals(driver.getTitle(), "New Window");
driver.switchTo().window(allWindows[1].toString());
Assert.assertEquals(driver.getTitle(), "New Window");
}
}
How to get Window Handle:
String handle = driver.getWindowHandle();
If there are multiple window gets opened when you click on any link,button etc... then to get "window Handle" of each window -
Set windowHandles = driver.getWindowHandles();
"getWindowHandles()" : method return window handle (unique id for each opened window) so that the return type is set. Because set will not contain duplicate elements so here getWindowHandles return unique id/window handles for each winodw and stored in Set.
How to switch to correct / appropriate window:
Basically there are two ways to switch to appropriate window.
To get current/parent/default window handle:
String handle = driver.getWindowHandle();
driver.switchTo().window( handle );
OR
Set < String > windowHandles = driver.getWindowHandles();
for(String handle : windowHandles )
{
driver.swicthTo().window( handle );
}
Example of Handling Multiple Windows In Selenium
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With