How to Switch to Popup Window using Selenium WebDriver?

package pkg_selenium;

import java.util.concurrent.TimeUnit;

import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedConditions;
import org.openqa.selenium.support.ui.WebDriverWait;
import org.testng.Assert;

public class SwitchToWindow {

public static WebDriver driver;
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
// Initialize WebDriver

driver = new FirefoxDriver();

// Wait For Page To Load

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

// Go to URL

driver.get("https://developer.paypal.com/");

// Maximize Window
driver.manage().window().maximize();

// Click on 'Login' button
driver.findElement(By.xpath("//a[contains(text(),'Log In')]")).click();

Thread.sleep(5000L);

// Store the CurrentWindow for future reference

String currentWindow = driver.getWindowHandle();
String popupWindowHandle = null;

// Switch To Popup Window

for(String handle : driver.getWindowHandles()){
if(!handle.equals(currentWindow)){

popupWindowHandle = handle;

}
}

driver.switchTo().window(popupWindowHandle);

// Wait For EmailId text Field To appear

WebDriverWait wait = new WebDriverWait(driver,30);
WebElement element = wait.until(ExpectedConditions.visibilityOfElementLocated(By.id("email")));
Assert.assertNotNull(element);


// Get the Window Title

String windowTitle = driver.getTitle();
System.out.println("Pop Window Title :"+windowTitle);

// Close Popup Window

driver.close();
// Switch To Default Window

driver.switchTo().window(currentWindow);

// Close Driver

driver.quit();


}

}

Comments

Popular posts from this blog

Encoding and Decoding in Selenium using Base64 Class of Java

Parallel Execution In TestNG Framework Using ThreadLocal Concept

How to handle calendar or date picker using dynamic XPATH?