Friday, 21 February 2014

How to handle multiple browser windows in Selenium Webdriver in Java?

Below code will show you how we can handle pop up windows in selenium in Java.
Selenium webdriver API provides a method called getWindowHandles() which can be used to get the handles of open browser windows.

We can switch to the desired window using below syntax.
driver.switchTo().window(handle);

Sample Java program to handle multiple browser windows is given below

package temp;
import java.io.File;
import java.util.Set;
import java.util.concurrent.TimeUnit;

import org.apache.commons.io.FileUtils;
import org.openqa.selenium.By;
import org.openqa.selenium.Keys;
import org.openqa.selenium.OutputType;
import org.openqa.selenium.TakesScreenshot;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Action;
import org.openqa.selenium.interactions.Actions;

//import com.sun.jna.platform.FileUtils;


@SuppressWarnings("unused")
public class OpenGoogle {
   
public static void main(String [] arg)
{

System.setProperty("webdriver.chrome.driver", "C:\\SelenuimProject\\chromedriver2.8.exe");
WebDriver driver =  new ChromeDriver();



try{
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
driver.manage().timeouts().pageLoadTimeout(50,TimeUnit.SECONDS);
//driver.navigate().to("http://www.google.com");

//Please enter your web url here
driver.get("http://www.xyz.com/");

String mainHandle = driver.getWindowHandle();

driver.findElement(By.linkText("Open New Window")).click();

//wait while ( driver.getWindowHandles().size() == 1 );


Set<String> HandleSet = driver.getWindowHandles();
//Switching to the popup window.

for ( String handle : HandleSet )
{
    if(!handle.equals(mainHandle))
    {
       //Switch to newly created window
         driver.switchTo().window(handle);
    }
}



}

catch(Exception e){
       System.out.println("Exception - > " + e.toString());
       }
       finally{
              driver.close();
              driver.quit();
       }
}      //main function ends
      

}//class ends


What do you think on above selenium topic. Please provide your inputs and comments. You can write to me at reply2sagar@gmail.com

No comments:

Post a Comment

Buy Best Selenium Books

About Me

My photo

Self-motivated software professional