NEW TAB & NEW WINDOW HANDLING

  

PROBLEM:

By default webdriver does not understand the elements in the browser pop ups. The control of the webdriver will be in the parent window and when we say driver.findElement(), it tries to find the element in the parent window(). Webdriver does not transfer the control to the new browser automatically.

SOLUTION:

We have to transfer the control to the browser pop up using driver.switchTo().window(). Window() accepts a string argument which is the window handle of the browser to switch to. We can get the window handles of all the browsers that was opened during that execution by using the method driver.getWindowHandles(). getWindowHandles() returns a Set which contains all the window handles. We can use an iterator and get each window handle by using the next().

The first time next() is used it gets first element in the set, the second time the next method is used it gets second element in the set and so on. We can store this window handle in the String reference and pass it as an argument to driver.switchTo().window().

After performing action on the browser pop up, if we want to close the popup, we can use driver.close(). This method will close the current browser where control is present. If the browser is closed control does not transfer to the parent browser automatically. We have to use driver.switchTo().window() to transfer the control.

When we click on the link which opens in a new tab, webdriver will open it in a new window.

 

package mypackage;

 

import java.awt.AWTException;

import java.awt.Robot;

import java.awt.event.KeyEvent;

import java.util.Iterator;

import java.util.Set;

import java.util.concurrent.TimeUnit;

 

import org.openqa.selenium.By;

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

 

public class FileDownloadPopup {

 

public static void main(String[] args  {

System.setProperty("webdriver.gecko.driver","C:\\Browser\\geckodriver.exe");

WebDriver driver=new FirefoxDriver();

driver.manage().window().maximize();

driver.get("https://www.google.com/");

driver.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);

 

driver.navigate().to("https://www.air.irctc.co.in/");

                                       

driver.findElement(By.xpath("//a[text()='Packages']")).click();

                   

Set<String> allwindow=driver.getWindowHandles();

System.out.println(allwindow.size());

                   

Iterator<String>it=allwindow.iterator();

String irctc=it.next();

String pack=it.next();

                   

System.out.println(irctc);

System.out.println(pack);

                   

driver.switchTo().window(pack);

                   

driver.findElement(By.xpath("//a[text()='Login']")).click();

driver.close();


driver.switchTo().window(irctc);

                   

driver.findElement(By.id("stationFrom")).sendKeys("chennai");

}

}