Some Web application allows to login to their system using Gmail, Facebook, Twitter etc account. When click on Gmail, Facebook, Twitter, its icon button, new window open with a login page. Selenium webdriver provide opportunity to handle new opened window and back to original window after completing an operation on new window. In this tutorial I will show how to operate new window.
Switch between new opened windows and original window as below:
// Store the current window on String variable
String parentwindow = driver.getWindowHandle();
// Do the click operation that opens new window
// Switch to window that's your newly opened window
for(String winHandle : driver.getWindowHandles()){
driver.switchTo().window(winHandle);
}
// code to do something on new window
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (parent window)
driver.switchTo().window(parentwindow);
// Continue with original browser (parent window)
Java demo source code:
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
public class Operatenewwindow {
public static void main(String[] arg) {
WebDriver driver = new FirefoxDriver();
driver.manage().window().maximize();
driver.get("http://localhost:8080/idea/a/community/login");
// Store the current window on String variable
String parentwindow = driver.getWindowHandle();
// Do the click operation that opens new window
driver.findElement(By.className("icon-facebook")).click();
// Switch to window that's your newly opened window
for (String winHandle : driver.getWindowHandles()) {
driver.switchTo().window(winHandle);
}
// code to do something on new window
driver.findElement(By.id("email")).sendKeys("hiro@gmail.com");
driver.findElement(By.id("pass")).sendKeys("123456789");
driver.findElement(By.id("loginbutton")).click();
// Close the new window, if that window no more required
driver.close();
// Switch back to original browser (parent window)
driver.switchTo().window(parentwindow);
// Continue with original browser (parent window)
driver.close();
}
}
No comments:
Post a Comment