How to deal with ModalDialog using selenium webdriver?
Asked Answered
S

9

14

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

Staal answered 18/12, 2012 at 15:26 Comment(3)
Check the below link for better understanding of how to handle the modal dialogs or pop ups using selenium2.0 thoughtworks-studios.com/twist/2.3/help/…Stable
@Hemanth I realise this is an old question, but that link no longer works; it takes me to a page saying that support for Twist ended in December 2015.Yod
@Yod yes, its been 6 years i wrote the above comment. Can you let me know if the accepted answer to this question helped you? If not, let me know, i can give you alternative approaches.Stable
N
22

Use

following methods to switch to modelframe

driver.switchTo().frame("ModelFrameTitle");

or

driver.switchTo().activeElement()

Hope this will work

Navy answered 18/12, 2012 at 15:35 Comment(6)
I have tried both but none of this working. Can you please try it out and let me knowStaal
@Jasmine.Olivra, you've accepted the answer, however at the same time said that "none of this working". So is it working for you or not?Lenrow
I am doing the same in python, but my statement is : driver.switch_to_window(activeElement()).... However I am getting the error:driver.switch_to_window(activeElement()). Can you provide any hints?Pellmell
@Staal If it's not working then why did you accept the answer?Arrange
@Pellmell if you want to send "keys" to an active element in python driver.switch_to.active_element.send_keys("keys") unfortunately if this is a client side os file dialog this is the only way I have found to interact with the dialog.Hawker
driver.switchTo().activeElement() :+1Cowled
K
1

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());
Kidwell answered 20/5, 2013 at 8:51 Comment(0)
A
1

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

    }
Arrange answered 31/7, 2013 at 14:22 Comment(0)
F
1

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()
Fable answered 15/10, 2018 at 15:46 Comment(0)
H
0

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());
Heroin answered 19/12, 2012 at 9:21 Comment(0)
C
0

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();
    }
}
Color answered 28/5, 2013 at 2:37 Comment(0)
R
0

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;
    }
});
Redcap answered 19/3, 2014 at 17:52 Comment(0)
L
0

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>**);
Leeuwarden answered 11/4, 2020 at 15:45 Comment(0)
P
0

P.S. 1 adding my 2 cents even though the question is too old

    public void PressEnterKey()
    {
        var simulator = new InputSimulator();
        simulator.Keyboard.KeyPress(VirtualKeyCode.RETURN);
    }

you can create a method like the above and call it where it is required.

P.S. 2 - you can change the keyboard inputs as well (like up arrow, down arrow, page down etc)

Ploy answered 9/2, 2023 at 8:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.