How To Switch To Modal Window In Selenium
Websites nowadays are frequently implementing the usage of pop-ups, alerts, or modal dialog boxes for various use cases like accepting cookies, request for permissions, inbound data, warning alerts, etc. Although there are a few valid apply cases for these, unnecessary popups might expect annoying and need to be handled.
You must have encountered these in your day-to-day web interactions on unlike websites similar Amazon or Walmart on the first visit prompting for SignUp, on various food websites like McD, Swiggy to provide the location, or a payment gateway modal to complete payment.
With this increased usage, it is now expected of an automation tester that they are aware of their handling via automation. The main reason is that most of these popups, which at times are multiple, appear on the homepage for the website under examination and need to exist handled/closed till the parent page is accessible to interact with and the bodily examination flow tin can begin.
So if you lot have not got a take a chance to work on these or automate them so far, this blog is the correct 1 for you. In this blog, we volition acquire how to handle modal dialog box in Selenium WebDriver Java with practical examples.
This blog would cover handling Bootstrap dialog boxes, pop-upwardly windows/tabs, and alerts. I will be starting with the basics of pop-ups, post which I will demonstrate how to handle modal dialog box in Selenium WebDriver Java. So let'southward get started.
Table OF CONTENTS
- How to handle Modal Dialog Box in Selenium WebDriver Java?
- What is a Modal Dialog Box?
- Demonstration: Handling Modal Dialog Box in Selenium Java
- Modal Dialog Box Automation Example
- How to handle Alerts using Selenium Java?
- What are Alerts?
- Demonstration: Handling Alerts Windows using Selenium Coffee
- How to handle Popups using Selenium Java?
- What are Popups?
- Demonstration: Treatment Popups using Selenium Coffee
- Frequently Asked Questions (FAQs)
How to handle Modal Dialog Box in Selenium WebDriver Coffee?
In this Selenium Java tutorial, we will learn what is a modal dialog box and demonstrate the handling of a modal dialog box in Selenium Java.
What is a Modal Dialog Box?
A Modal Dialog Box (too referred to as Bootstrap Modal Window) is built in Bootstrap Framework, due to which information technology gets displayed on summit of your current folio. Due to this, modal boxes need to be interacted with first before moving to the current webpage.
For starters, The Bootstrap Framework is a very popular, gratis, and open-source CSS framework that is highly used in spider web page evolution, peculiarly for responsive and mobile-get-go spider web pages. It contains HTML, CSS, and JavaScript. To learn more about the Bootstrap framework, you tin deep swoop into CSS Filigree vs. Bootstrap comparison.
A modal dialog box written with Bootstrap is formed with three primal components, namely,
- Trigger element, which triggers the modal window to be shown on the webpage. Information technology can be any link on the webpage or whatever button, etc.
- Modal, which is like a holding area for the actual modal window code that will come up when the trigger element is interacted with.
- Modal content, is the actual lawmaking and the content with which the window is formed and displayed equally per the implementation.
And so while automating whatsoever modal window, we first fetch the modal using our web driver then identify the modal content inside it to perform actions.
Demonstration: Handling Modal Dialog Box in Selenium WebDriver Coffee
Having developed a basic understanding of the modal dialog box, information technology'southward fourth dimension to implement it and meet how information technology works in existent-time.
Please notation that for all the examples in this blog, we volition exist using this aforementioned project setup for all the examples in this web log and go on adding more test grade files as we proceed. So practice the setup carefully on your machine for implementation purposes.
Footstep 1. Choose the IDE on which yous want to do the setup. In this blog, Eclipse IDE is being used. You tin can follow the same steps if any other IDE has opted. In example you are using IntelliJ, you tin become through the article on building and executing Selenium Projects.
Step two. Create a Maven Projection in Eclipse and proper name it every bit Dialog_Boxes_With_Selenium_Java.
Footstep 3. Update the pom.xml file to have Selenium (as it will be a web automation project using Selenium WebDriver) and TestNG (to create test flow and execute test cases using Annotations) dependencies.
1 2 3 4 5 vi 7 eight 9 10 11 12 13 fourteen fifteen 16 17 18 xix 20 21 22 23 24 25 26 27 28 29 thirty 31 | < project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns : xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi : schemaLocation = "http://maven.apache.org/POM/four.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd" > < modelVersion > iv.0.0 < / modelVersion > < groupId > Dialog_Boxes_With_Selenium_Java < / groupId > < artifactId > Dialog_Boxes_With_Selenium_Java < / artifactId > < version > 0.0.1 - SNAPSHOT < / version > < build > < sourceDirectory > src < / sourceDirectory > < plugins > < plugin > < artifactId > maven - compiler - plugin < / artifactId > < version > 3.8.1 < / version > < configuration > < release > 16 < / release > < / configuration > < / plugin > < / plugins > < / build > < dependencies > < dependency > < groupId > org . seleniumhq . selenium < / groupId > < artifactId > selenium - java < / artifactId > < version > 3.141.59 < / version > < / dependency > < dependency > < groupId > org . testng < / groupId > < artifactId > testng < / artifactId > < version > vii.5 < / version > < scope > exam < / scope > < / dependency > < / dependencies > < / projection > |
Step four. Now within the src package, add together a parcel and name it every bit exam. This will contain all the test classes which will be created in this web log.
Footstep five. Inside the examination package add a Java class file and name information technology equally BaseClass.java. This file will accept the basic driver functions like, initialize driver, quit driver, etc.
In this web log on how to handle modal dialog box in Selenium WebDriver Java, we will be using the TestNG testing framework for test execution. Reason being, it is widely supported with Selenium Java and provides an easy mode to write and manage test automation scripts with the usage of annotations.
1 two 3 4 5 6 7 8 9 10 11 12 xiii fourteen xv 16 17 18 xix xx 21 22 23 24 25 26 27 28 29 thirty 31 32 33 34 35 36 37 38 39 40 41 | package test ; import java . net . MalformedURLException ; import java . cyberspace . URL ; import org . openqa . selenium . remote . DesiredCapabilities ; import org . openqa . selenium . remote . RemoteWebDriver ; import org . testng . annotations . AfterMethod ; import org . testng . annotations . BeforeMethod ; public class BaseClass { public RemoteWebDriver driver = nix ; Cord username = "<lambdatest_username>" ; String accessKey = "<lambdatest_accesskey>" ; @ BeforeMethod public void setUp ( ) { DesiredCapabilities capabilities = new DesiredCapabilities ( ) ; capabilities . setCapability ( "browserName" , "Chrome" ) ; capabilities . setCapability ( "version" , "92.0" ) ; capabilities . setCapability ( "platform" , "Windows x" ) ; capabilities . setCapability ( "resolution" , "1024x768" ) ; capabilities . setCapability ( "build" , "DialogBoxes And Popular-ups Selenium JAVA" ) ; capabilities . setCapability ( "name" , "DialogBoxes And Pop-ups Selenium Java" ) ; try { driver = new RemoteWebDriver ( new URL ( "https://" + username + ":" + accessKey + "@hub.lambdatest.com/wd/hub" ) , capabilities ) ; } catch ( MalformedURLException eastward ) { Arrangement . out . println ( "Invalid grid URL" ) ; } } @ AfterMethod public void closeDriver ( ) { driver . quit ( ) ; } } } |
Code Walkthrough
We accept created BaseClass.coffee as the first file, which will have the lawmaking to initiate the browser session for Selenium automation and handle the code for browser setup and endmost information technology after test completion. This volition be inherited to our test classes, thus preventing redundancy for such code and providing an abstraction of driver code from every other form user.
Stride 1. Inside the BaseClass, nosotros will exist adding two functions, 1 to initialize the driver and create an instance of it and some other to shut it once the exam cases are executed.
We will be executing the lawmaking on a Selenium Cloud Grid using an instance of Selenium RemoteWebDriver.
The reason is, along with the advantages of Selenium Grid, similar executing multiple cases across various browsers and OS, a Cloud Grid also offers speed and scalability, which makes executions faster and more reliable.
An example of ane such Selenium Cloud Grid is LambdaTest, which facilitates cross browser testing beyond an online browser farm of 3000+ real browsers and operating systems on the cloud. Automation testing tools like LambdaTest provide an interactive reporting dashboard for results analysis along with all the benefits of cloud testing.
Here's a glimpse of LambdaTest cloud Selenium Grid:
You lot can as well Subscribe to the LambdaTest YouTube Channel and stay updated with the latest tutorials around automated browser testing, Cypress testing, CI/CD, and more.
public RemoteWebDriver driver = null ; |
Step ii. Next would be to add the LambdaTest username and access key for your account to exist used to run the script. You lot tin can discover these details in the LambdaTest Profile Section.
String username = "<lambdatest_username>" ; String accessKey = "<lambdatest_accesskey>" ; |
Step 3. Subsequently that, add the first method in this file as setUp(), which would be used to set initial capabilities for the browser and launch the filigree with the given credentials.
You can see we have gear up some capabilities for the Chrome browser to be used for our examination example. Equally we are using the LambdaTest platform here for remote execution, nosotros can accept reward of its Selenium Desired Capabilities Generator to generate such values for a number of browser and operating systems combinations by selecting them every bit required.
Stride iv. Just like the setUp() method would create the driver instance to be used for executing the script, it is a skilful practice to quit the current browser case as before long as the case is completed. To facilitate the same, add the adjacent method as closeDriver() to quit the commuter instance. This would have @AfterMethod notation in TestNG as the method with this annotation volition be called afterwards every test method has completed execution.
@ AfterMethod public void closeDriver ( ) { driver . quit ( ) ; } |
This completes the setup for our base implementation. Let's motion to the next department to implement and see how modal dialog box automation works.
Modal Dialog Box Automation Case
For this web log purpose, nosotros will exist automating the following menses:
- Navigate to https://www.lambdatest.com/selenium-playground/bootstrap-modal-demo.
- Click on Launch Model under Single Modal Instance.
- Fetch the modal container web element.
- Fetch the modal content web elements using the container chemical element.
- Verify and interact with the modal dialog window.
i 2 3 4 5 vi 7 eight 9 10 11 12 xiii fourteen 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | package test ; import org . openqa . selenium . By ; import org . openqa . selenium . WebElement ; import org . testng . Assert ; import org . testng . annotations . Examination ; import org . openqa . selenium . support . ui . ExpectedConditions ; import org . openqa . selenium . back up . ui . WebDriverWait ; public grade TestModalDialogBox extends BaseClass { @ Examination ( clarification = "exam to verify modal dialog box" ) public void verifyModalDialogBox ( ) throws InterruptedException { // to navigate to the website System . out . println ( "Navigating to the website" ) ; commuter . go ( "https://www.lambdatest.com/selenium-playground/bootstrap-modal-demo" ) ; // to click Launch model button - Trigger element System . out . println ( "Clicking launch modal button" ) ; driver . findElement ( By . xpath ( "//push[@data-target='#myModal']" ) ) . click ( ) ; // wait to permit the modal box be visible WebDriverWait expect = new WebDriverWait ( driver , 30 ) ; await . until ( ExpectedConditions . visibilityOfElementLocated ( Past . className ( "modal-dialog" ) ) ) ; // to fetch the spider web chemical element of the modal container System . out . println ( "Fetching the web chemical element for modal container" ) ; WebElement modalContainer = driver . findElement ( By . className ( "modal-dialog" ) ) ; // to fetch the web elements of the modal content and interact with them // code to fetch content of modal trunk and verify it System . out . println ( "Fetching modal torso content and asserting it" ) ; WebElement modalContentBody = modalContainer . findElement ( By . xpath ( ".//div[@form='modal-body']" ) ) ; Assert . assertEquals ( modalContentBody . getText ( ) , "This is the place where the content for the modal dialog displays" , "Verify modal torso message" ) ; // code to click on accept modal button System . out . println ( "Clicking modal accept push button" ) ; WebElement modalAcceptButton = modalContainer . findElement ( By . xpath ( ".//button[contains(text(),'Salve Changes')]" ) ) ; modalAcceptButton . click ( ) ; } } |
Code Walkthrough
Footstep 1. First lines of code in the testcase are to navigate to the URL on which we will take our modal dialog box to automate.
driver . get ( "https://www.lambdatest.com/selenium-playground/bootstrap-modal-demo" ) ; |
Stride 2. After the page has loaded, we click on the push to launch the dialog box. As we learnt, this is the trigger chemical element which makes the dialog box appear.
For this we utilise the XPath element locator to fetch the element using its tag and attribute fundamental-value.
driver . findElement ( By . xpath ( "//button[@data-target='#myModal']" ) ) . click ( ) ; |
Pace 3. After clicking the push, nosotros look for the modal box to be visible. For this, we take used explicit waits, as per which the WebDriver waits for a certain condition to occur earlier proceeding to execute the further code. To know more about explicit waits, you tin can go through this commodity on types of Waits in Selenium.
To utilise these waits in your test automation script, the following imports are washed:
import org . openqa . selenium . back up . ui . ExpectedConditions ; import org . openqa . selenium . back up . ui . WebDriverWait ; |
Footstep 4. Later this, an object of WebDriverWait course is instantiated using the WebDriver reference and maximum time to wait for before raising an exception. The fourth dimension is in seconds.
WebDriverWait wait = new WebDriverWait ( driver , thirty ) ; |
Using this wait object, we implement some "ExpectedConditions" function to exist fulfilled. There are certain predefined conditions for information technology in Selenium, of which we have used visibilityOfElementLocated(), which means to wait until the given WebElement is visible.
expect . until ( ExpectedConditions . visibilityOfElementLocated ( By . className ( "modal-dialog" ) ) ) ; |
Step 5. One time the modal dialog box opens up, we fetch the WebElement of the modal container equally we will be interacting with the elements inside the modal dialog box container.
WebElement modalContainer = commuter . findElement ( By . className ( "modal-dialog" ) ) ; |
Stride 6. Next, we fetch the modal dialog box WebElements to perform actions on their content. One important thing to note hither is the way how the WebElement for the model content is fetched.
For this, in identify of the driver, the WebElement identifier for the modal container is used, and the identifying XPath for the chemical element starts with ".//," which signifies that the respective element to be found is within this chemical element, i.due east., inside the modal dialog box.
The post-obit code showcases this implementation of how elements would be identified and how we tin affirm on information technology or click the button. To larn more nearly assertions you can become through our earlier blog on How To Use Assertions In TestNG With Selenium.
WebElement modalContentBody = modalContainer . findElement ( By . xpath ( ".//div[@form='modal-trunk']" ) ) ; Assert . assertEquals ( modalContentBody . getText ( ) , "This is the identify where the content for the modal dialog displays" , "Verify modal trunk message" ) ; // code to click on accept modal button WebElement modalAcceptButton = modalContainer . findElement ( Past . xpath ( ".//button[contains(text(),'Save Changes')]" ) ) ; modalAcceptButton . click ( ) ; |
Examination Execution
Having understood the code implementation, lets execute the code using TestNG. Once successfully executed, you can meet the following output on the IDE.
Since nosotros executed the code on a remote grid using LambdaTest, execution logs are also available on the LambdaTest Dashboard, including video, steps of the automation script, and network and panel logs.
You can run across your executed test cases under Recent Tests on the Dashboard.
To see the detailed execution for your instance, click on the test case, and you can run into the details like the following:
You can too navigate to the LambdaTest Analytics Dashboard to come across test performance metrics. From the Exam Summary department, you volition come across the total number of tests passed or failed, including completed and awaiting tests. You lot can also see the snapshot of consistent tests from the Examination Overview section.
Intrigued to know more about LambdaTest? Attempt LambdaTest At present!
How to handle Alerts using Selenium Java?
In this department of the weblog on how to handle modal box in Selenium WebDriver Java, we will learn what are alerts and how to handle alerts in Windows using Selenium Java
What are Alerts?
Alerts in web development usually refer to a message or notification that lets the user know about information, namely:
- Asking for access permissions.
- Highlighting mandatory fields on a form.
- Display warning messages or help information.
Different modal dialog boxes, Selenium offers some special functions to deal with alerts. This is because it is a very tricky and time-consuming chore for testers to automate alerts using regular methods. A few of these predefined methods are
- Click Have Button of the alert Dismiss/Cancel an Alert Box
- Click Accept on Alert Box
- Fetch static information from Alert Box
- Transport data to input fields on Alarm Box
driver . switchTo ( ) . warning ( ) . dismiss ( ) ; |
driver . switchTo ( ) . alert ( ) . accept ( ) ; |
driver . switchTo ( ) . alert ( ) . getText ( ) ; |
driver . switchTo ( ) . alarm ( ) . sendKeys ( "Text" ) ; |
sendKeys() function is used to enter information to the input fields on any spider web page in Selenium automation. SenKeys in Selenium performs the same action here by entering data to any input field on the alert.
Demonstration: Handling Alerts Window using Selenium Coffee
For this weblog on how to handle modal dialog box in Selenium Java, we will exist automating the post-obit flow:
- Navigate to https://www.lambdatest.com/selenium-playground/javascript-alarm-box-demo.
- Click on Click Me push nether Java Script Alarm Box.
- Verify the alarm body content equally Please Enter Your Name.
- Enter some data in the alert input box.
- Click OK to take the alarm.
i 2 iii 4 5 6 7 eight ix 10 11 12 13 14 fifteen sixteen 17 18 xix 20 21 22 23 24 25 26 27 28 29 xxx 31 32 33 34 35 36 37 38 | parcel examination ; import org . openqa . selenium . Past ; import org . testng . Affirm ; import org . testng . annotations . Test ; import org . openqa . selenium . support . ui . ExpectedConditions ; import org . openqa . selenium . support . ui . WebDriverWait ; public class TestAlerts extends BaseClass { @ Test ( description = "test to verify alerts" ) public void verifyAlerts ( ) throws InterruptedException { // to navigate to the website System . out . println ( "Navigating to the website" ) ; driver . get ( "https://www.lambdatest.com/selenium-playground/javascript-alarm-box-demo" ) ; // to click the button to get demo alarm System . out . println ( "Clicking launch alert button" ) ; driver . findElement ( Past . xpath ( "(//button[contains(text(),'Click Me')])[3]" ) ) . click ( ) ; // to let the alert be visible WebDriverWait look = new WebDriverWait ( driver , 30 ) ; await . until ( ExpectedConditions . alertIsPresent ( ) ) ; // to fetch the alert torso content and verify it System . out . println ( "Fetching the alert torso content and asserting it" ) ; String alertBodyText = driver . switchTo ( ) . alert ( ) . getText ( ) ; Affirm . assertEquals ( alertBodyText , "Delight enter your name" , "Verify alert body content" ) ; // to enter data as required by the alert System . out . println ( "Entering date in the warning input box" ) ; commuter . switchTo ( ) . alert ( ) . sendKeys ( "LambdaTest" ) ; // to accept the alert Organisation . out . println ( "Accepting the alert" ) ; driver . switchTo ( ) . alarm ( ) . accept ( ) ; } } |
Lawmaking Walkthrough
Step 1. This code also starts with the kickoff stride as navigating to the target folio where the actual automation script would be executed.
driver . get ( "https://world wide web.lambdatest.com/selenium-playground/javascript-alert-box-demo" ) ; |
Pace 2. One time the folio is loaded, we click the push button to become the alert on which alert functions tin can exist implemented and verified.
driver . findElement ( By . xpath ( "(//button[contains(text(),'Click Me')])[iii]" ) ) . click ( ) ; |
Footstep three. Just like for the modal dialog box, for alert as well, explicit expect is existence implemented. Imports and object creation remain same for this case as well with only difference beingness on ExpectedConditions. For supporting alerts, only similar there are predefined functions in Selenium, alertIsPresent() is used in this example.
look . until ( ExpectedConditions . alertIsPresent ( ) ) ; |
Step 4. After the alert is visible, nosotros start with implementing alarm().getText() to fetch the content on the alarm and asserting it.
Just before we can do and so, nosotros demand to make sure that the driver example focus has been switched to the alert from the main window. For this purpose, the switchTo() office is used in Selenium automation testing. This function is used whenever we are working with multiple windows like new tab, alerts, popular ups, etc. in web automation.
Since in this test script, we need to switch to alarm in this test script to interact with information technology, switchTo().alert() is used. Nosotros volition learn more about how to switch between parent/kid windows in the popups section.
Cord alertBodyText = driver . switchTo ( ) . alarm ( ) . getText ( ) ; |
Step v. Here we are using the Affirm class of TestNG to compare the content using the assertEquals() function. In this function, we will pass the expected content, which is the cord and the actual content, which is the body content of the alert that is fetched on the previous stride. If both matches, affirm is passed; else, information technology fails with an mistake that is expected and actual data practice non equal.
Assert . assertEquals ( alertBodyText , "Delight enter your name" , "Verify alert body content" ) ; |
Step 6. Adjacent, we verify the warning().sendKeys() function by inbound some data in the input field.
driver . switchTo ( ) . alert ( ) . sendKeys ( "LambdaTest" ) ; |
Pace 7. The concluding step of this exam scenario is to have the alert for which the predefined method that Selenium provides is being used.
driver . switchTo ( ) . alarm ( ) . accept ( ) ; |
Depending upon the use case, you tin as well implement the function to dismiss/cancel the alarm. For this following method Selenium method can be used
driver . switchTo ( ) . alert ( ) . dismiss ( ) ; |
Test Execution
Equally mentioned for the modal dialog box in the previous section, nosotros tin similarly execute the alerts examination example from IDE and see the output like beneath on successful execution on the IDE and the LambdaTest dashboard for the automation cases.
Wondering how to handle alerts on cloud Selenium Grid? Try LambdaTest Now!
How to handle Popups using Selenium Java?
In this department of the blog on how to handle modal box in Selenium WebDriver Java, we volition learn what are popups and how to handle popups using Selenium Java.
What are Popups?
Pop-upward refers to a new window or tab that pops up or gets opened as a result of some interaction on the webpage. It can come up up in a number of conditions and as per implementation.
In Selenium automation, the driver always focuses on the currently active window and interacts with it. Then whenever we are working with pop-ups in Selenium, some boosted methods are used to shift the commuter'due south focus to the newly opened window and and so back to the main window.
- Go handles of all the windows that are open up at that example.
- Get the current window handle on which the driver is focused.
- Switch to the principal parent window.
- Switch to any specific window using its handle.
driver . getWindowHandles ( ) ; |
driver . getWindowHandle ( ) ; |
commuter . switchTo ( ) . defaultContent ( ) ; |
driver . switchTo ( ) . window ( handleId ) ; |
handleId hither refers to the ids of the window which we can fetch using the getWindowHandle() or getWindowHandles() function of the WebDriver.
Demonstration: Handling Popups using Selenium Coffee
For this blog purpose, we will be automating the post-obit flow:
- Navigate to https://world wide web.lambdatest.com/selenium-playground/window-popup-modal-demo.
- Click on Follow On Twitter under Unmarried Window Popup.
- Switch to a new popup window.
- Assert Follow push on information technology is present.
- Switch back to the primary window.
- Affirm Follow On Twitter is displayed.
one 2 3 4 five 6 7 viii 9 10 11 12 thirteen 14 15 16 17 xviii 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 fifty 51 52 53 54 55 56 57 58 59 60 61 62 63 | package exam ; import java . util . Iterator ; import java . util . Set ; import org . openqa . selenium . By ; import org . openqa . selenium . WebElement ; import org . testng . Affirm ; import org . testng . annotations . Test ; import org . openqa . selenium . support . ui . ExpectedConditions ; import org . openqa . selenium . support . ui . WebDriverWait ; public class TestPopups extends BaseClass { @ Test ( clarification = "examination to verify pop ups" ) public void verifyPopups ( ) throws InterruptedException { // to navigate to the website System . out . println ( "Navigating to the website" ) ; driver . get ( "https://www.lambdatest.com/selenium-playground/window-popup-modal-demo" ) ; driver . manage ( ) . window ( ) . maximize ( ) ; // to fetch and relieve the handle of current window System . out . println ( "storing the primary window handle" ) ; String mainWindowHandle = driver . getWindowHandle ( ) ; // to click the button to go a popup (new tab in this example) System . out . println ( "Clicking launch popup button" ) ; WebElement followButtonOnMainWindow = driver . findElement ( By . xpath ( "//a[contains(@title,'Twitter')]" ) ) ; followButtonOnMainWindow . click ( ) ; // to get the list of all window handles after the new tab // should have length 2 since 1 new tab opens upwards Organisation . out . println ( "Fetching the list of all window handles and asserting them" ) ; Set up < Cord > windowHandles = driver . getWindowHandles ( ) ; Assert . assertEquals ( windowHandles . size ( ) , 2 , "Verify the total number of handles" ) ; // switch to new opened tab Organization . out . println ( "Switching to the new window handle" ) ; Iterator < String > itr = windowHandles . iterator ( ) ; while ( itr . hasNext ( ) ) { String childWindowHandle = itr . next ( ) ; // to skip the handle of our main window and switch to new one if ( ! mainWindowHandle . equalsIgnoreCase ( childWindowHandle ) ) commuter . switchTo ( ) . window ( childWindowHandle ) ; } WebDriverWait wait = new WebDriverWait ( driver , xxx ) ; wait . until ( ExpectedConditions . visibilityOfElementLocated ( By . xpath ( "//span[(text()='Follow')]" ) ) ) ; // to verify that driver focus is shifted to popup window Organisation . out . println ( "Asserting some chemical element on the new popup window to confirm switch" ) ; WebElement twitterFollowButton = commuter . findElement ( By . xpath ( "//span[(text()='Follow')]" ) ) ; Assert . assertTrue ( twitterFollowButton . isDisplayed ( ) , "Verify twitter follow push button is displayed" ) ; // shift driver dorsum to main window and verify System . out . println ( "Switching back to principal window and asserting same" ) ; driver . switchTo ( ) . window ( mainWindowHandle ) ; look . until ( ExpectedConditions . visibilityOfElementLocated ( By . xpath ( "//a[contains(@title,'Twitter')]" ) ) ) ; Assert . assertTrue ( followButtonOnMainWindow . isDisplayed ( ) , "Verify focus is shifted to main window" ) ; } } |
Lawmaking Walkthrough
You can find two special imports in this examination class, namely
import java . util . Iterator ; import java . util . Fix ; |
These are done to support the usage of Set up type Information Construction and Iterator, the function to traverse through the Gear up. More details about these are with the corresponding code where these are used.
Step 1. For writing the automation exam case for handling popular-ups, subsequently navigating to the required webpage, first, we get and save the handle of the master window. This is done equally in one case there is a new popup window, we need to accept some style to differentiate between the handle of the electric current window and the newly opened window.
String mainWindowHandle = commuter . getWindowHandle ( ) ; |
Step 2. After storing this, the adjacent step would be to click on the link text or button, in this instance, on the current/master window, to get the new popup window.
WebElement followButtonOnMainWindow = driver . findElement ( Past . xpath ( "//a[contains(@title,'Twitter')]" ) ) ; followButtonOnMainWindow . click ( ) ; |
Stride 3. At present, equally per the test scenario expectation, we should have two windows on the screen. To verify the same, use the getWindowHandles() method to get identifiers (or window handles) of the respective Windows.
This method returns the list of handles of all the Windows, which to sympathize are the ids of unlike Windows that can exist used to identify them. This entire list is stored in a Set type of data construction for easy accessibility.
As the number of window handles is stored in the Set type variable, we can employ the size() method to fetch the total number of handles in that and affirm as per expectation which is ii here.
Set < Cord > windowHandles = driver . getWindowHandles ( ) ; Affirm . assertEquals ( windowHandles . size ( ) , 2 , "Verify the total number of handles" ) ; |
Pace iv. Next step would be to switch to the new pop upward window. For this, we traverse through the listing of window handles and compare it with the chief window handle value, which we stored in the offset step.
For traversal through the Set up containing all window handles, nosotros are using Iterator. As the name suggests, it ways to visit repeatedly until some point. And so here, we keep on iterating the set for the next values till nosotros reach the last value.
Iterator < String > itr = windowHandles . iterator ( ) ; while ( itr . hasNext ( ) ) { String childWindowHandle = itr . next ( ) ; // to skip the handle of our main window and switch to new one if ( ! mainWindowHandle . equalsIgnoreCase ( childWindowHandle ) ) driver . switchTo ( ) . window ( childWindowHandle ) ; } |
Step five. Once we get a non-matching value, we switch to the new popped-up window and use the Explicit Await like discussed earlier to expect for the new popped-upwardly window using the visibilityOfElementLocated() function and raise an Assert to verify the switch is successful.
// to verify that driver focus is shifted to popup window WebDriverWait look = new WebDriverWait ( driver , xxx ) ; wait . until ( ExpectedConditions . visibilityOfElementLocated ( By . xpath ( "//span[(text()='Follow')]" ) ) ) ; WebElement twitterFollowButton = commuter . findElement ( Past . xpath ( "//bridge[(text()='Follow')]" ) ) ; Assert . assertTrue ( twitterFollowButton . isDisplayed ( ) , "Verify twitter follow push button is displayed" ) ; |
Footstep 6. The last step is to switch back to the main window using its already stored handle and assert some element on it to verify that the commuter focus has been shifted over again to the master window.
driver . switchTo ( ) . window ( mainWindowHandle ) ; Assert . assertTrue ( followButtonOnMainWindow . isDisplayed ( ) , "Verify focus is shifted to master window" ) ; |
Test Execution
In a similar manner as discussed above, after execution, we will become the result on IDE equally follows:
And we can see the detailed execution logs on LamdaTest Dashboard by navigating to the test details and tin come across the data similar:
If you're a Java developer looking to meliorate your skills, the following certification from LambdaTest tin can assistance:
This Selenium Java 101 certification is for commencement to intermediate level Java developers who want to refresh their knowledge of the programming language and learn more about the Selenium automation testing.
Here's a short glimpse of the Selenium Java 101 certification from LambdaTest:
By at present you must take got a fair understanding almost popups and alerts and how yous can handle modal dialog box in Selenium WebDriver Java over a cloud grid like LambdaTest. Withal, if you want to leverage the best features of the cloud setup with faster execution (as good equally the speed of a local setup), yous can endeavor HyperExecute – a blazing fast side by side gen testing cloud, which is upto 70% faster than whatsoever traditional Selenium cloud setup.
Now execute your test at Hyper Speed? Try HyperExecute Now!
Decision
With this blog on how to handle modal dialog box in Selenium WebDriver Java, we have learned the implementation and working for all of these in detail covering all the aspects and functions that yous might encounter and would need while working with these. I hope, past now, y'all would be confident enough to automate whatsoever kind of modal dialog box, alerts, or popups that come upwardly in your automation scripts. And so go ahead and get started with Selenium Coffee automation testing to handle these with ease.
Happy Automating !!
Frequently Asked Questions (FAQs)
Is a dialog box a modal?
Modal Dialogs are one of the most useful features for user interface design. They allow you lot to overlay a dialog box onto your awarding, allowing the user to collaborate with it or dismiss it, without interfering with the main content.
How do y'all use dialog boxes?
A modal dialog box is a small pane that consists of one or more windows with various controls. Modal dialog boxes cake input to all but the agile control. To create a modal dialog box, you lot tin can employ Visual Bones code or create the template and populate information technology with controls in the evolution environs.
To create a dialog box, use the "DialogBox" function. This function uses a template and the name of the process that gets activated when the user makes a choice.
How exercise I stop popups in Selenium?
In order to close the popup window with Selenium, we can utilise the getWindowHandles and getWindowHandle methods for opening the popup window. The getWindowHandles method is used for storing all the window handles in Selenium in a Set data structure. The getWindowHandle method is used to store the window handle of the pop up in focus.
Source: https://www.lambdatest.com/blog/how-to-handle-modal-dialog-box-in-selenium-webdriver-java/
Posted by: cunninghamgiceit.blogspot.com
0 Response to "How To Switch To Modal Window In Selenium"
Post a Comment