Handling Modal Window in Selenium WebDriver

This would work for all browsers (FF, Chrome, IE).

 public class ModalDialog { public static void main(String[] args) throws InterruptedException { // TODO Auto-generated method stub WebDriver driver = new InternetExplorerDriver(); //WebDriver driver = new FirefoxDriver(); driver.get("http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm"); String parent = driver.getWindowHandle(); WebDriverWait wait = new WebDriverWait(driver, 10); WebElement push_to_create = wait.until(ExpectedConditions .elementToBeClickable(By .cssSelector("input[value='Push To Create']"))); push_to_create.click(); waitForWindow(driver); switchToModalDialog(driver, parent); } public static void waitForWindow(WebDriver driver) throws InterruptedException { //wait until number of window handles become 2 or until 6 seconds are completed. int timecount = 1; do { driver.getWindowHandles(); Thread.sleep(200); timecount++; if (timecount > 30) { break; } } while (driver.getWindowHandles().size() != 2); } public static void switchToModalDialog(WebDriver driver, String parent) { //Switch to Modal dialog if (driver.getWindowHandles().size() == 2) { for (String window : driver.getWindowHandles()) { if (!window.equals(parent)) { driver.switchTo().window(window); System.out.println("Modal dialog found"); break; } } } } } 

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s