[selenium] How to deal with ModalDialog using selenium webdriver?

I am unable to switch to Modal Dialog of given example

http://samples.msdn.microsoft.com/workshop/samples/author/dhtml/refs/showModalDialog2.htm

I don't know how to get element on modal Dialog

enter image description here

This question is related to selenium modal-dialog selenium-webdriver

The answer is


Assuming the expectation is just going to be two windows popping up (one of the parent and one for the popup) then just wait for two windows to come up, find the other window handle and switch to it.

WebElement link = // element that will showModalDialog()

// Click on the link, but don't wait for the document to finish
final JavascriptExecutor executor = (JavascriptExecutor) driver;
executor.executeScript(
    "var el=arguments[0]; setTimeout(function() { el.click(); }, 100);",
  link);

// wait for there to be two windows and choose the one that is 
// not the original window
final String parentWindowHandle = driver.getWindowHandle();
new WebDriverWait(driver, 60, 1000)
    .until(new Function<WebDriver, Boolean>() {
    @Override
    public Boolean apply(final WebDriver driver) {
        final String[] windowHandles =
            driver.getWindowHandles().toArray(new String[0]);
        if (windowHandles.length != 2) {
            return false;
        }
        if (windowHandles[0].equals(parentWindowHandle)) {
            driver.switchTo().window(windowHandles[1]);
        } else {
            driver.switchTo().window(windowHandles[0]);
        }
        return true;
    }
});

Solution in R (RSelenium): I had a popup dialog (which is dynamically generated) and hence undetectable in the original page source code Here are methods which worked for me:

Method 1: Simulating Pressing keys for Tabs and switching to that modal dialog My current key is focussed on a dropdown button behind the modal dialog box
remDr$sendKeysToActiveElement(list(key = "tab"))
Sys.sleep(5)
remDr$sendKeysToActiveElement(list(key = "enter"))
Sys.sleep(15)
Method 2: Bring focus to the frame(or iframe) if you can locate it
date_filter_frame <- remDr$findElement(using = "tag name", 'iframe')
date_filter_frame$highlightElement()

Sys.sleep(5)

remDr$switchToFrame(date_filter_frame)

Sys.sleep(2)
Now you can search for elements in the frame. Remember to put adequate Sys.sleep in between commands for elements to load properly (just in case)
date_filter_element <- remDr$findElement(using = "xpath", paste0("//*[contains(text(), 'Week to Date')]"))
date_filter_element$highlightElement()

Try the below code. It is working in IE but not in FF22. If Modal dialog found is printed in Console, then Modal dialog is identified and switched.

 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;
                    }
                }
            }
        }

    }

What you are using is not a model dialog, it is a separate window.

Use this code:

private static Object firstHandle;
private static Object lastHandle;

public static void switchToWindowsPopup() {
    Set<String> handles = DriverManager.getCurrent().getWindowHandles();
    Iterator<String> itr = handles.iterator();
    firstHandle = itr.next();
    lastHandle = firstHandle;
    while (itr.hasNext()) {
        lastHandle = itr.next();
    }
    DriverManager.getCurrent().switchTo().window(lastHandle.toString());
}

public static void switchToMainWindow() {
    DriverManager.getCurrent().switchTo().window(firstHandle.toString());

Try this code, include your object names & variable to work.

Set<String> windowids = driver.getWindowHandles();
Iterator<String> iter= windowids.iterator();
for (int i = 1; i < sh.getRows(); i++)
{   
while(iter.hasNext())
{
System.out.println("Main Window ID :"+iter.next());
}
driver.findElement(By.id("lgnLogin_UserName")).clear();
driver.findElement(By.id("lgnLogin_UserName")).sendKeys(sh.getCell(0, 
i).getContents());
driver.findElement(By.id("lgnLogin_Password")).clear();
driver.findElement(By.id("lgnLogin_Password")).sendKeys(sh.getCell(1, 
i).getContents());
driver.findElement(By.id("lgnLogin_LoginButton")).click();
Thread.sleep(5000L);
            windowids = driver.getWindowHandles();
    iter= windowids.iterator();
    String main_windowID=iter.next();
    String tabbed_windowID=iter.next();
    System.out.println("Main Window ID :"+main_windowID);
    //switch over to pop-up window
    Thread.sleep(1000);
    driver.switchTo().window(tabbed_windowID);
    System.out.println("Pop-up window Title : "+driver.getTitle());

I have tried it, it works for you.

String mainWinHander = webDriver.getWindowHandle();

// code for clicking button to open new window is ommited

//Now the window opened. So here reture the handle with size = 2
Set<String> handles = webDriver.getWindowHandles();

for(String handle : handles)
{
    if(!mainWinHander.equals(handle))
    {
        // Here will block for ever. No exception and timeout!
        WebDriver popup = webDriver.switchTo().window(handle);
        // do something with popup
        popup.close();
    }
}

Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.

have to import javascriptexector

like below,

Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);

Examples related to selenium

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser Class has been compiled by a more recent version of the Java Environment How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? element not interactable exception in selenium web automation Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Read input from a JOptionPane.showInputDialog box Disable click outside of angular material dialog area to close the dialog (With Angular Version 4.0+) How can I display a modal dialog in Redux that performs asynchronous actions? Angular 2.0 and Modal Dialog How to use Bootstrap modal using the anchor tag for Register? Bootstrap modal opening on page load Trying to make bootstrap modal wider How to present a modal atop the current view in Swift Send parameter to Bootstrap modal window? Set bootstrap modal body height by percentage

Examples related to selenium-webdriver

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to configure ChromeDriver to initiate Chrome browser in Headless mode through Selenium? How to make Firefox headless programmatically in Selenium with Python? Selenium Web Driver & Java. Element is not clickable at point (x, y). Other element would receive the click How do you fix the "element not interactable" exception? Scrolling to element using webdriver? Only local connections are allowed Chrome and Selenium webdriver Check if element is clickable in Selenium Java