user3789019
user3789019

Reputation: 1

Selenium Webdriver cannot click on modal dialog when the window is not in focus

I have 2 browsers open and Selenium Webdriver can switch between these two. One window is in foreground and other is in background. And in the workflow, a modal dialog opens up in the background window and thus webdriver cannot perform any actions on it. Is there any possible solution apart from getting the background window into foreground? I am using C#.

Upvotes: 0

Views: 2081

Answers (2)

Jlearner
Jlearner

Reputation: 613

I am using below code

try{

//your code which will generate Modal Dialog     

} catch (Exception e) {

            if (e.getMessage().contains("Modal dialog present")) {//For Handling modal dialog in firefox
                (new Robot()).keyPress(java.awt.event.KeyEvent.VK_ESCAPE);
                (new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ESCAPE);

            }else if(e.getMessage().contains("unexpected alert open")){//For Handling modal dialog in chrome

                driver.switchTo().alert().accept();

            }

        }

Upvotes: 0

mutt
mutt

Reputation: 793

Loop through your window handles and check for you modal dialog to appear.

string current_window = driver.CurrentWindowHandle;
foreach (string window in driver.WindowHandles)
{
    driver.SwitchTo().Window(window);

    if (GetModal())
    {
         //do actions here
         break;
    }
}
driver.SwitchTo().Window(current_window); //To put you back where you started.

private bool GetModal()
{
    Try
    {
        IWebElement modal = driver.FindElementByXPath("");
        return true;
    }
    catch
    {
        return false;
    }
}

Based on what you put this should work. If you can't find the modal then there is probably a different issue than just the window not being in focus. If you are worried about other errors then I would say catch only the specific error in the catch and let everything else float up ElementNotFound exception.

Upvotes: 1

Related Questions