Java modal dialog box with Selenium WebDriver

During my form testing, I encountered a javascript alert in my web app notifying users to fill in missing data if needed data is not typed. The problem arises when using selenium to handle this alert, as an exception occurs when trying to submit the partially filled form.

org.openqa.selenium.UnhandledAlertException: Modal dialog present

Attempting to catch this exception results in the webdriver alert not being displayed. Is there any solution to overcome this issue? I want to be able to submit the form and capture the alert. My setup includes Linux Mint, Firefox 18, and selenium 2.28.0 with Java. Best regards UPDATE My code contains the following:

somePage.fillName(sth); // Only one of two required fields are filled
somgePage.submit(); // JS alert appears after clicking submit
somePage.getCurrentAlert();
// Code snippets
public Alert getCurrentAlert(){
    return driver.switchTo().alert();
}
public AdminHome submit(){
        saveUrl();
        WebElement submit = driver.findElement(By.id("add_quiz_submit_button"));
        try{
            submit.click();
            if(urlChanged()){
                return new AdminHome(driver);
            }
        }
        catch(Exception e){
            e.printStackTrace();// Exception 1
            return null;
        }
        return null;
    }
//Exception 1
org.openqa.selenium.UnhandledAlertException: Modal dialog present
//The test fails because of:
org.openqa.selenium.NoAlertPresentException: No alert is present (WARNING: The server did not provide any stacktrace information)

However, manually clicking on submit works as expected for the test. Thank you in advance

Answer №1

It is important to address the alert immediately after completing the action, without any other actions preceding it.

For example, your code should look like this:

 try{
        submit.click();
        if (alertPresent())
            getCurrentAlert();
        if(urlChanged()){
            return new AdminHome(driver);
        }
    }

This approach ensures that the alert is checked and accepted promptly. The way webdriver interacts is similar to how we manually interact with a browser. Therefore, once the 'submit' button is clicked, an alert may appear and no further actions can be taken until it is accepted or dismissed.

Vishal

Answer №2

When faced with an UnhandledAlertException, the driver automatically accepts the alert, leading to a situation where it is difficult to submit a partially filled form.

If there is a need to proceed with submitting the form despite this issue, one possible solution would be to catch the exception and include code in the catch block that triggers a click on the submit button.

Answer №3

To close a modal dialog box, you can use the Robot class in Java to simulate pressing the Enter key.

 try {
        (new Robot()).keyPress(java.awt.event.KeyEvent.VK_ENTER);

         (new Robot()).keyRelease(java.awt.event.KeyEvent.VK_ENTER);
         } catch (AWTException e) {
                // Handle any potential exceptions here
                e.printStackTrace();
            }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Moving pictures using css3 transitions

Trying to create a straightforward image slider. Below is the provided JavaScript code: $(document).ready(function() { $('#slide1_images').on('click', 'img', function(){ $("#slide1_images").css("transform","translateX ...

extract information from a document and store it in an array

As I delve into the realm of programming, I find myself grappling with the best approach to extract data from a file and store it in an array. My ultimate aim is to establish a dictionary for a game that can verify words provided by players. Despite my no ...

Where is the nearest span located?

Consider the following HTML structure: <div data-theme="a" class="ui-btn ui-btn-icon-right ui-btn-corner-all ui-shadow ui-btn-up-a"> <span class="ui-btn-inner ui-btn-corner-all"> <span class="ui-btn-text">Select One</span& ...

How can I extract an array from a string using JSON parsing?

Currently, I am initiating a GET request through HTTP to a specific file in php that responds with a JSON encoded array. The returned Array is structured as a 2x2 Array. My goal is to handle the output of the HTTP request and construct a similar 2x2 Array ...

Using Ajax and jQuery to dynamically insert an option into a datalist

I'm in the process of building a search box using Flask, MySQL, and ajax. I've managed to retrieve the search results in JSON format within the console, but now I want to dynamically add them to the options in my datalist element in the HTML. He ...

Encountered ImportError with Seleniumwire

I am struggling to identify the source of this error message in Python 3.9 and 3.10. Traceback (most recent call last): File "C:\Users\User\Desktop\S\SS\test.py", line 1, in <module> from seleniumwire imp ...

When the nesting in AngularJS ui-router becomes overwhelming

I've been in the process of refactoring a large application at work, and I've noticed significant similarities between different parts of the app that make me think nesting routes could be beneficial. However, as I continue to nest more and more, ...

curved edges and accentuate the chosen one

I've been working on an angularJS application that includes a webpage with multiple tabs created using angularJS. Check out this example of the working tabs: http://plnkr.co/edit/jHsdUtw6IttYQ24A7SG1?p=preview My goal is to display all the tabs with ...

Java services causing JDE BSFN to throw errors

, I am facing a challenging situation where I am attempting to invoke a JDE BSFN using a Java servlet. The peculiar issue arises when the business function encounters numeric or date input parameters, resulting in an exception being thrown. Surprisingly, t ...

log4j has detected a problem: there are no appenders available for the logger. Please make sure to initialize the log4j system correctly

Could someone assist me with this issue? I keep receiving the following warning message: log4j:WARN No appenders could be found for logger (com.akak.book.shop.listener.LogContextListener). log4j:WARN Please initialize the log4j system properly. The code ...

Steps to update the background color of a highlighted ItemList component in Material-Ui

I recently implemented a selectable component using Material-UI let SelectableInfiniteList = makeSelectable(Infinite); and added ListItems inside. Now, I am trying to customize the default gray color of a selected item. I attempted to do this using a cla ...

Input user information into the Action URL

After the user clicks submit, the goal is to open . However, the giveme() function is currently returning "?keyword=UserInput" instead of just "UserInput". How can I ensure that the URL is correct? <form id="myform" class=" ...

How can a Java application access the original SOAP request of a SOAP-based Web Service?

In my current project, I am developing an application that utilizes web services to transmit client input to a vendor. The first phase of the project involved receiving XSD's and WSDL information from the vendor, which allowed me to create a client ja ...

Angular and RxJS work together to repeat actions even when an HTTP request is only partially successful

I am currently attempting to achieve the following: Initiate a stop request using a stored ID in the URL. Send a request with a new ID in the URL and save this new ID. If the response code is 200, proceed as normal. If it is 204, repeat steps 1 and 2 with ...

Executing a quick shallow copy of an object in a single ReactJS operation

I have an object in a component that I need to copy to a property. Currently, I am achieving this as follows: onSubmit: values => { data.label = values.label; data.userName = values.userName; data.recipientUserName = values.recipient ...

Issue with locating element in Selenium using C#

I encountered an issue with my Selenium project. My goal is to navigate to Google, search for Selenium, and then click on the first search result that appears. Here is the code I am using: driver.FindElement(By.XPath("//*@id=\"rso\"]/div/div/div ...

Is it advisable to combine ng-change with ng-blur in AngularJS?

Seeking clarification on the correct usage of AngularJS's ng-change and ng-blur from an expert. Specifically, when updating a form value. In the code snippet below, I have a dropdown where I would like to trigger overrideBusinessDec() when the user ...

There is no way to change the type from 'openqa.selenium.by' to 'openqa.selenium.iwebelement'

I'm currently attempting to execute a mousehover action followed by a click on a submenu that was not initially available This is the code I have written: private By RMenu = By.LinkText("Reports"); public HomePage SetMenu(string menu) { Actions ...

Time stamp in a *.mov/*.avi file

I am encountering issues with playing .mov/.avi files. Currently, I have a script that embeds the movie and provides JavaScript shortcuts to control its playback. Now, I would like to allow my members to add annotations to specific parts of the film, sim ...

What could be causing the undefined properties of my input variables in Angular?

Currently, I am fetching data from a service within the app component and passing it down to a child component using @Input. Oddly enough, when I log the data in ngOnInit, it appears correctly in the child component. However, when I try to assign it to a v ...