In your tests you might encounter specialized popups, which are generated via Javascript, and which are called âuser promptsâ. These are very basic in functionality, and they come in three variants: an âalertâ which only displays an informational message and an âOKâ button; a âconfirmâ which displays an informational message, together with an âOKâ and âCancelâ button; a âpromptâ which displays an informational message, possibly an input field for typing into, and an âOKâ and âCancelâ button.
Such a user prompt will be displayed usually when a user clicks a button, which triggers the prompt to be displayed. Understanding what type of user prompt will be displayed when a user clicks a button can be done by inspecting the HTML code of the button. It will have an attribute called âonclickâ, whose value is the name of a Javascript function that will execute when the button is clicked. The location of the function can be either in the HTML file itself, or in a different file which is imported in the HTML file. You will find this information in the <script> section of your HTML file. If you find the function with the name equal to the âonclickâ attribute value, there you have it. If not, you will find an âimportâ declaration, such as: <script src=âsomeExternalJsFileâ>, where âsomeExternalJsFileâ is the name of the file where the function which triggers a user prompt is defined.
The function you are looking for is of the following format:
<script> function nameOfFunction() { Â Â ... } </script>
Of course, a script which triggers a user prompt to be displayed might do more than just show you the prompt. Based on what you click, some additional code might be executed in the script. That will depend on what product you are working on. However, the code which simply displays the user prompts is as follows:
- Alert: this is a simple prompt with a text displayed (âtheAlertMessageâ in this example) and an OK button:
alert("theAlertMessage");
- Confirm: this is a prompt with a text displayed (âtheConfirmMessageâ in this example) and an OK and Cancel buttons
confirm("theConfirmMessage");
- Prompt:Â
- this is a prompt with a text displayed (âthePromptMessageâ in this example), an empty input field in which the user can type, and an OK and Cancel buttons:
prompt("thePromptMessage");
-
- this is a prompt with a text displayed (âthePromptMessageâ in this example), a pre-filled input field (with the text âthePromptInputFieldâ) in which the user can type, and an OK and Cancel buttons:
prompt("thePromptMessage", âthePromptInputFieldâ);
Examples Setup
The HTML page that will be used in this post for showing how to work with prompts contains three buttons. Clicking on each of them will trigger a different type of user prompt to be displayed.Â
âŚâŚâŚ <button id="alertButton" onclick="alertFunction()">Alert button</button> <button id="confirmButton" onclick="confirmFunction()">Confirm button</button> <button id="promptButton" onclick="promptFunction()">Prompt button</button> <p id="userClicked"></p> <script> function alertFunction() {  alert("This is the alert box"); } function confirmFunction() {  var confirmBoolean = confirm("Confirm modal");  if (confirmBoolean == true) {    document.getElementById("userClicked").innerHTML = "OK";  } else {    document.getElementById("userClicked").innerHTML = "Cancel";  }   txt; } function promptFunction() {  var promptOption = prompt("Type something");  if (promptOption != null) {    document.getElementById("userClicked").innerHTML =    "OK";  }  else {  document.getElementById("userClicked").innerHTML =    "Cancel";  } } </script> âŚâŚâŚâŚâŚ...
After this page is opened in the browser, when the button with id âalertButtonâ is clicked, the âalertFunction()â function from the <script> section of this page is executed. It triggers an âalertâ to be displayed. This alert displays the âThis is the alert boxâ text, and it also has an âOKâ button.
When the button with id âconfirmButtonâ is clicked, the âconfirmFunction()â function from the <script> section of this page is executed. It triggers a âconfirmâ to be displayed. This confirm displays the âConfirm modalâ text, and it also has an âOKâ and a âCancelâ buttons. When the user clicks on any of the two buttons, in the <p> tag with id âuserClickedâ a text is displayed: âOKâ if the user clicked âOKâ and âCancelâ if the user clicked the other button.
When the button with id âpromptButtonâ is clicked, the âpromptFunction()â function from the <script> section of this page is executed. It triggers a âpromptâ to be displayed. This prompt displays the âType somethingâ text, has a typeable input field, and it also has an âOKâ and a âCancelâ buttons. When the user clicks on any of the two buttons, in the <p> tag with id âuserClickedâ a text is displayed: âOKâ if the user clicked âOKâ and âCancelâ if the user clicked the other button.
Note: the paragraph which displays what the user clicked is created in this example only for demonstration purposes. It is up to the application you are developing to add some specific behavior based on what the user clicks on inside the âpromptâ or âconfirmâ.
The import section of the test (https://github.com/iamalittletester/selenium-tutorial/blob/master/src/test/java/tutorialsolution/userprompts/UserPromptsTest.java ) will contain the following entries:
import browser.BrowserGetter; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.TestInstance; import org.openqa.selenium.Alert; import org.openqa.selenium.WebDriver; import org.openqa.selenium.support.PageFactory; import tutorialsolution.pages.UserPromptsPage; import java.io.File; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.TestInstance.Lifecycle.PER_CLASS;
Because the examples in this post use JUnit 5, the junit jupiter related imports are used for the setup methods, for the test methods and for the assertion parts. The BrowserGetter, WebDriver and PageFactory imports are used for starting the browser, storing the driver instance and initializing the PageObject class elements. The UserPromptsPage is imported because that is the PageObject class where the WebElements for this test are created. The relevant import for demonstrating user prompts is the Alert class.
The @BeforeAll method contains the browser and PageObject class initialization, and the code which opens the âuserPrompts.htmlâ page, where the code for the user prompt demo is stored. The browser will be closed in the @AfterAll class.
@BeforeAll    public void beforeAll() {        //initialize the Chrome browser here        driver = browserGetter.getChromeDriver();        //initialize page object class        page = PageFactory.initElements(driver, UserPromptsPage.class);        driver.get(new File("src/main/resources/userPrompts.html").getAbsolutePath());    } @AfterAll    public void afterAll() {        driver.quit();    }
The PageObject class (https://github.com/iamalittletester/selenium-tutorial/blob/master/src/main/java/tutorialsolution/pages/UserPromptsPage.java) contains the WebElements corresponding to the buttons which, when clicked, trigger the alert/confirm/prompts. It also contains the WebElement of the paragraph in which, when the user clicks a button on confirm/prompt, a text corresponding to which button was clicked is displayed:
@FindBy(css = "#alertButton") public WebElement alertButton; @FindBy(css = "#confirmButton") public WebElement confirmButton; @FindBy(css = "#promptButton") public WebElement promptButton; @FindBy(css = "#userClicked") public WebElement userClicked;
 1. Alert
The alert type of user prompt:
- Displays:
- A text
- An OK button
- Has the following JS code: alert(“theAlertMessage”);
- Can be interacted with from Selenium by:
- Clicking the OK button
- Reading its text
In case more than one interaction with the alert is made in a test, it is worth storing a handle to the alert by creating an âAlertâ object variable. Getting the handle to it is easily done in the following code:
Alert alert = driver.switchTo().alert();
Now, in order to read the text of the alert or to click the OK button, while the alert is displayed, you can call the relevant methods for these actions directly on the âalertâ variable. Reading the label of the alert is done by using the âgetText()â method :
alert.getText()
Clicking on the OK button of this alert is easily done by using the âaccept()â method on the âalertâ variable:
alert.accept()
Once you defined the variable, you donât need to call the âdriver.switchTo()â method, if you closed the alert and opened it again. Once the variable is defined for an alert, you can use it across your test, but only for that particular alert, as it returns a handle to that alert.Â
If you only need to perform one action on the alert in your test (maybe just closing it), you donât need to create a separate variable for the alert. It is not worth creating a variable which will only be used once. Therefore, in such a case, you could easily close the alert by writting the following code in your test, where you are chaining the method calls (first you switch to the alert, then click on it):
driver.switchTo().alert().accept();
This approach also has the benefit of writing less lines of code.
Note: when using the alert related method, like âaccept()â or âgetText()â, you need to make sure you are doing this while the user prompt, which ever it is (alert,confirm or prompt) is displayed. If you try to use these methods when the alert is not displayed you will encounter the following âNoAlertPresentExceptionâ Exception:
org.openqa.selenium.NoAlertPresentException: no alert open
Example
Scenario 1. Click on the button which opens an alert. Check that the text of the alert is âThis is the alert boxâ. Then, close the alert.
Clicking on the button which will trigger the alert to be displayed is straightforward (see Example Setup section):
page.alertButton.click();
Now that the alert is displayed, create a new variable which will store a handle to the alert, so that you can interact with the alert in the tests:
Alert alert = driver.switchTo().alert();
This variable is of type âAlertâ. Now you can read the text of the alert using the âgetText()â method and compare it to the expected one.
assertEquals("This is the alert box", alert.getText());
The last step of this test requires closing the alert, by using the âaccept()â method:
alert.accept();
Scenario 2. Click on the button which opens an alert. Close the alert.
For this test, there is only one action that needs to be performed on the alert, namely closing it once it is open. Therefore, there is no need to store the handle to the alert into a new variable. Instead, the entire test will consist of two steps: clicking the button which triggers the alert, then closing the alert:
page.alertButton.click(); driver.switchTo().alert().accept();
2. Confirm
The confirm type of user prompt:
- Displays:
- A text
- An OK button
- A Cancel button
- Has the following JS code: confirm(“theConfirmMessage”);
- Can be interacted with from Selenium by:
- Clicking the OK button (accept)
- Clicking the Cancel button (dismiss)
- Reading its text
In case more than one interaction with the alert is made in a test, it is worth storing a handle to the confirm by creating an âAlertâ object variable. From a Selenium point view, whether the user prompt is an alert, a confirm or a prompt, the handle to a user prompt is stored in an âAlertâ object variable. There is no âConfirmâ or âPromptâ variable.Â
Getting the handle to it is easily done in the following code, which is also identical to the way you would get the handle to an alert or to a prompt:
Alert alert = driver.switchTo().alert();
Retrieving the text of the âconfirmâ is also done just as for the alert from the previous subchapter:
alert.getText()
It is the same with clicking on the âOKâ button of the prompt:
alert.accept()
Up to now, these methods could be used on an alert type of user prompt too. The difference between a âconfirmâ and an âalertâ si that the âconfirmâ user prompt also has a âCancelâ button, which can be clicked from a test. Doing so is done by calling the âdimiss()â method on the âalertâ variable:
alert.dismiss()
In case only one interaction with the âconfirmâ is required in the test, there is no need to create a new variable only for the one interaction. Instead, the desired methods for interactions can be called as follows (this is the example for clicking âOKâ):
driver.switchTo().alert().accept();
Similarly, closing the âconfirmâ by clicking the âCancelâ button in a one-liner can be done:
driver.switchTo().alert().dismiss();
Example
Scenario 1.1. Click the button which triggers a âconfirmâ to be displayed. Check that the text on the âconfirmâ is âConfirm modalâ. Click the âOKâ button on the âconfirmâ. Check that the field which displays what the user clicked now displays âOKâ.
The first step is to click the button which triggers the âconfirmâ to be displayed. Then, the handle to the newly opened âconfirmâ will be stored to a variable of type âAlertâ.
page.confirmButton.click(); Alert alert = driver.switchTo().alert();
Checking that the âconfirmâ text is the expected one is done via the âgetText()â method:
assertEquals("Confirm modal", alert.getText());
Now, the âconfirmâ can be closed, by clicking the âOKâ button.
alert.accept();
At this point, in this test, in the paragraph whose corresponding WebElement is named âuserClickedâ, the text âOKâ is displayed. To check this, the following assertion will be used:
assertEquals("OK", page.userClicked.getText());
Scenario 1.2. After scenario 1.1 is executed successfully, in the same test, open the âconfirmâ again. Close the âconfirmâ by clicking the âCancelâ button. Check that the field which displays what the user clicked now displays âCancelâ.
Opening the âconfirmâ again is done just as the first step of Scenario 1.1.:
page.confirmButton.click();
Close the âconfirmâ by clicking the âCancelâ button. This is done by using the âdismiss()â method from Selenium. Now, think about what happened previously: first you opened the âconfirmâ and you got a handle to it. Then you closed it. Now it opens again. Luckily there is no need to regenerate the handle to the âconfirmâ (like it is the case with switching to windows). Once you created the âalertâ variable for the âconfirmâ you can reuse that variable even if you closed, then reopened the âconfirmâ.
alert.dismiss();
Now, since the âCancelâ button was clicked, check that the field which displays what the user clicked now displays âCancelâ:
assertEquals("Cancel", page.userClicked.getText());
Scenario 2. Open a âconfirmâ type of user prompt. Close it by clicking the âCancelâ button. Check that the paragraph which displays what the user clicked shows the text âCancelâ.
This is a short test, since there is only one interaction with the âconfirmâ and there is no need to store the âconfirmâ handle to a variable:
page.confirmButton.click(); driver.switchTo().alert().dismiss(); assertEquals("Cancel", page.userClicked.getText());
3. Prompt
The prompt type of user prompt:
- Displays:
- A text
- An input field, with or without a predefined text
- An OK button
- A Cancel button
- Has the following JS code: prompt(“thePromptMessage”); or prompt(“thePromptMessage”, âthePromptInputFieldâ);
- Can be interacted with from Selenium as:
- Clicking the OK button (accept)
- Clicking the Cancel button (dismiss)
- Reading its text
- Typing in the input field
In case more than one interaction with the âpromptâ is made in a test, it is worth storing a handle to the âpromptâ by creating an âAlertâ object variable. As mentioned in the previous subchapter, no matter what type of user prompt appears in the test, the type of variable used for storing its handle will be âAlertâ. Storing the handle is done just as for the other types of user prompts:
Alert alert = driver.switchTo().alert();
Retrieving the text of the âpromptâ is also done just as for the âalertâ and âconfirmâ from the previous subchapter:
alert.getText()
It is the same with clicking on the âOKâ button of the prompt:
alert.accept()
Clicking the âCancelâ button of the âpromptâ is done by calling the âdimiss()â method on the âalertâ variable:
alert.dismiss()
Aditionally, the user can type in an input field displayed on the âpromptâ. This can be done using the âsendKeys()â method from Selenium. Note that at the time of writing this post, this functionality does not work on ChromeDriver(). Itsâ usage is:
alert.sendKeys(âtextToTypeâ)
Just as before, if there is no need to create a new variable in the test, the âpromptâ related methods can be called directly in the form:
driver.switchTo().alert().dismiss();
Example
Scenario 1. Open a new âpromptâ and check that the text displayed on it is âType somethingâ. Click the âOKâ button on the prompt, and check that the paragraph which displays what the user clicked now shows the text âOKâ. Open the âpromptâ again, then close it by clicking the âCancelâ button and check that the paragraph which dispays what the user clicked now shows âCancelâ.
Just as in the previous examples, for âalertsâ and âconfirmsâ, first a button is clicked which triggers the âpromptâ to be displayed. Then, the handle to the âpromptâ is stored in an âAlertâ variable.
page.promptButton.click(); Alert alert = driver.switchTo().alert();
Checking the text of the âpromptâ and closing it (via the âOkâ button) are covered by the following code:
assertEquals("Type something", alert.getText()); alert.accept();
Now the check that the paragraph displaying what the user clicked shows the text âOKâ is done through this assertion:
assertEquals("OK", page.userClicked.getText());
The next steps of this test are to reopen the prompt, then close it by clicking the âCancelâ button, and finally checking that the label displaying what button was clicked is correct:
age.promptButton.click(); alert.dismiss(); assertEquals("Cancel", page.userClicked.getText());
Scenario 2. Open a new âpromptâ and close it by clicking the âCancelâ button. Check that the paragraph which dispays what the user clicked now shows âCancelâ.
The code which covers this scenario is similar to previous subchapters:
page.promptButton.click(); Â driver.switchTo().alert().dismiss(); Â assertEquals("Cancel", page.userClicked.getText());
GitHub location of example code
PageObject class: https://github.com/iamalittletester/selenium-tutorial/blob/master/src/main/java/tutorialsolution/pages/UserPromptsPage.java Â
Test class: https://github.com/iamalittletester/selenium-tutorial/blob/master/src/test/java/tutorialsolution/userprompts/UserPromptsTest.javaÂ
Test methods: alertGetTextAndAccept, alertAccept, confirmGetTextAcceptAndDismiss, confirmAcceptAndDismiss, promptGetTextAcceptAndDismiss, promptAcceptAndDismiss
HTML code: https://github.com/iamalittletester/selenium-tutorial/blob/master/src/main/resources/userPrompts.html
Leave a comment