Tuesday, November 4, 2014


Web page may have multiple windows. Multiple windows means a link on a web page of another web page. Current web page is called main window and other windows called child window.

Each window has its own unique alphanumeric id. Selenium WebDriver uses this unique id to switch control between multiple windows.





How To Switch Between Multiple Windows



import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Training {

 public static void main(String[] args) throws InterruptedException {

  WebDriver driver = new FirefoxDriver();
  driver.get("http://reditblog.blogspot.in/p/selenium.html");
  driver.manage().window().maximize();
  Thread.sleep(5000);
  String mainWindow = driver.getWindowHandle();

  WebElement element = driver
    .findElement(By
      .linkText("Org.Openqa.Selenium.Firefox. NotConnectedException"));

  element.click();

  Thread.sleep(5000);
  for (String windowHandle : driver.getWindowHandles()) {
   if(windowHandle.equals(mainWindow)){
    System.out.println("Main Window - " + " "+ windowHandle);
    driver.switchTo().window(windowHandle);    
    System.out.println(driver.getTitle());
    
   }else{
    System.out.println("Child Window - " + " "+ windowHandle);
    Thread.sleep(5000);
    driver.switchTo().window(windowHandle);
    Thread.sleep(5000);
    System.out.println(driver.getTitle());
    driver.switchTo().defaultContent();   
    
   }
   
  }

 }

}