You might have seen certain webpages where you click a link and it will take you to another window or new window, if you have tried automate your test on these sites then you will find your test cases failing with an error "Elementnotfound".
This is because your Webdriver searchers for the element in primary window or a parent window instead of the new or child window. We will see how to automate our test while on these sites.
Code
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import java.util.Iterator;
import java.util.Set;
public class Handling_multiple_window {
public static void main(String[] args) {
System.setProperty("webdriver.chrome.driver","src\\Geko_driver\\chromedriver.exe");
WebDriver driver = new ChromeDriver();
driver.get("https://accounts.google.com/signup");
driver.findElement(By.xpath("//a[contains(text(),'Privacy')]")).click();
System.out.println(driver.getTitle());
Set<String> ids = driver.getWindowHandles();
Iterator<String> it = ids.iterator();
String parentid = it.next();
String childid = it.next();
driver.switchTo().window(childid);
System.out.println(driver.getTitle());
}
}
Explanation
In above snippet we are getting the page title of both the child and parent windows. When the click operation is performed on the above link it will open a new window(child window). If you use getTitle() method without switching window you will get the title of parent window only.
In selenium there is a method call getWindowHandles() this will return the list of all window handler ids in random alphanumeric, we use this and collect it in a Set. Then we create a variables for both the parent and child to store its window handler ids on it.
Finally we use the switchTo().window() to the child window, this time after switching to child window on getting title you will see getting child window's title.