Tips for navigating from one popup to another in Selenium WebDriver

Here is the situation:

  1. Perform an activity in the main window.
  2. Click on "Save" button which triggers a confirmation popup with "OK" and "CANCEL" buttons.
  3. Select "OK" on the confirmation popup and another success popup appears with an "OK" button.
  4. Click on "OK" on the success popup.
  5. Switch back to the main window.

The popups mentioned above are HTML based. How can I handle this scenario in Selenium? I am new to Selenium and I am currently stuck at this point.

https://i.sstatic.net/SGfKR.png

Code

String ParentWindow = driver.getWindowHandle(); //switching from parent to pop up window 
for (String Child_Window : driver.getWindowHandles()) { 
driver.switchTo().window(Child_Window);
WebDriverWait wait = new WebDriverWait(driver, 30);// 1 minute 
wait.until(ExpectedConditions.visibilityOfElementLocated(By.‌​name("test")));   
driver.findElement(By.xpath("//input[@value='test']")).click‌​();
} 
driver.switchTo().window(ParentWindow); 

HTML

<div>
<div class="msgBoxContainer">
<div id="msgBox1473308035532Image" class="msgBoxImage">
<img src="styles/images/confirm.png">
</div>
<div id="msgBox1473308035532Content" class="msgBoxContent">
<p>
<span>Are you sure you want to Save??</span>
</p>
</div>
</div>
<div id="msgBox1473308035532Buttons" class="msgBoxButtons">
<input id="msgBox1473308035532FirstButton" class="msgButton" type="button"  value="Yes" name="Yes">
<input class="msgButton" type="button" value="No" name="No">
</div>
</div>
</div>

// Upon clicking OK on the first popup, the corresponding div is destroyed and a new div for the second popup is generated.

<div id="msgBox1473308225709" class="msgBox" style="background-image:     url("styles/images/msgBoxBackGround.png"); opacity: 1; top: 52.5px; left: 566.5px;">
<div class="msgBoxTitle">Information</div>
<div>
<div class="msgBoxContainer">
<div id="msgBox1473308225709Image" class="msgBoxImage">
<img src="styles/images/info.png">
</div>
<div id="msgBox1473308225709Content" class="msgBoxContent">
<p>
<span>Registration completed</span>
</p>
</div>
</div>
<div id="msgBox1473308225709Buttons" class="msgBoxButtons">
<input id="msgBox1473308225709FirstButton" class="msgButton" type="button"   value="Yes" name="Yes">
</div>
</div>
</div>

Answer №1

When you click on the Save button, make sure to handle the information dialog box in the following way:

WebDriverWait wait = new WebDriverWait(driver,10);

//For the first dialog box
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.msgButton[id*='msgBox'][id*='FirstButton']"))).click();

//Now do the same for the second dialog box
wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.msgButton[id*='msgBox'][id*='FirstButton']"))).click();

Note:- You don't need to switch windows, these dialog boxes are simple HTML elements. So handle them normally by locating these elements.

Edited1: If you're having trouble clicking using WebElement.click(), try using the Actions class to move the element before clicking as shown below:

Actions act = new Actions(driver);

//For the first dialog box
WebElement firstDialog = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.msgButton[id*='msgBox'][id*='FirstButton']")));
act.moveToElement(firstDialog).click().perform();

//Now do the same for the second dialog box
WebElement secondDialog = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.msgButton[id*='msgBox'][id*='FirstButton']")));
act.moveToElement(secondDialog).click().perform();

Edited2: If you still can't click, try using JavascriptExecutor like this:

//For the first dialog box
WebElement firstDialog = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.msgButton[id*='msgBox'][id*='FirstButton']")));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",firstDialog);

//Now do the same for the second dialog box
WebElement secondDialog = wait.until(ExpectedConditions.visibilityOfElementLocated(By.cssSelector("input.msgButton[id*='msgBox'][id*='FirstButton']")));
((JavascriptExecutor)driver).executeScript("arguments[0].click()",secondDialog);

Answer №2

1) Open the main window and perform an activity.

Insert your code here

2) After completing the activity, click on the Save button which triggers a Confirmation popup with OK and CANCEL options.

Instructions for handling the confirmation popup:

Alert simpleAlert = driver.switchTo().alert();
        String alertText = simpleAlert.getText();
        System.out.println("Alert text is " + alertText);
        simpleAlert.accept();

3) Click on the OK button in the confirmation popup to proceed to another success popup that only has an OK button.

The next popup will appear with just an OK button.

simpleAlert.accept();

4) Once you see the success popup, click on the OK button to close it.

 WebDriverWait wait = new WebDriverWait(driver, 30);
  simpleAlert.accept();

5) Return to the main window after completing the activities in the popups.

 driver.switchTo().defaultContent();

You may also use the following code snippet:

String parentWindowHandler = driver.getWindowHandle(); // Store the reference to the parent window
String subWindowHandler = null;

Set<String> handles = driver.getWindowHandles(); // Obtain all window handles
Iterator<String> iterator = handles.iterator();
while (iterator.hasNext()){
    subWindowHandler = iterator.next();
}
driver.switchTo().window(subWindowHandler); // Switch to the popup window
                                              // Perform necessary operations

driver.switchTo().window(parentWindowHandler);  

Answer №3

When dealing with a JavaScript pop-up, utilize the alert class.

    WebDriverWait wait = new WebDriverWait(driver, 30);
    // Handling the first Alert
    Alert firstAlert = wait.until(ExpectedConditions.alertIsPresent());
    firstAlert.accept();

    // Dealing with the second Alert
    Alert secondAlert = wait.until(ExpectedConditions.alertIsPresent());
    secondAlert.accept();

    driver.switchTo().defaultContent();

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

Using a JavaScript Map to merge results from multiple mongoDB queries

Running two separate queries to combine results into a map is faster than running a single, larger query. I create a dictionary using the _id field and set the entire object as the value. let sessions = await getListSessions(minDate, maxDate); if (confi ...

Displaying Kartik's growling animation using AJAX within Yii2 framework

Utilizing kartik growl to display a message via ajax success I attempted the following: This is the javascript code: $.post({ url: "forwardpr", // your controller action dataType: 'json', data: {keylist: keys,user:userdata}, success: f ...

Issues with the webpack-dev-server and React

I was just reading up on Webpack and the moment came for me to start using it, but I ran into an error. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6a09180b471e1f1e ...

The results from various <div> elements are displayed based on the selection made from the dropdown menu

<body> <label for="country">Country : </label> <select id="country"> <option>Please select</option> <option name="CountryRevenue">Revenue</option> <option name="CountryQuantity">Quantity ...

Tips for dealing with "Unresponsive Script" pop-ups affecting Firefox using watir-webdriver

I've been experiencing issues with this pesky popup disrupting many of my tests. Even basic DOM interactions like checking if an element exists are timing out. Is there a way to detect when the popup appears and dismiss it? A warning message pops up: ...

Struggling to get SVG and <p> elements to align on the same line using display:inline-block?

Alright, I'm struggling to align this HTML content properly. The generated code looks like: <div id = "innerCal"> <div id = "calCell"><p>[</p> <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 447 443"><defs>< ...

I'm having difficulty with this calculator program as it is not providing the correct result

My coding class requires me to achieve the following output: Enter the first number! 9 Enter the Second number! 5 9 + 5 = 14 9 - 5 = 4 9 * 5 = 45 9 / 5 = 1.8 and I'm facing an issue where my program is returning 1.0 instead of 1.8. How can I fix thi ...

Tips for efficiently sending multiple ajax requests

Seeking help with my ajax knowledge. Currently, I have a function that is supposed to insert multiple items into an SQL database using a PHP page. However, it seems to only be inserting the last item entered. Here's the code snippet: function submitI ...

Large data sets may cause the Highchart Bar to not display properly

Currently, I am working on a web project that displays traffic usage in chart mode using Highchart Bar. The issue I am facing is that there are no errors thrown when running this code. <script type="text/javascript"> $(function () { $(&apos ...

What is the method for accessing the locale and messages of the IntlProvider within a component?

My index.js file includes the following code: import trFi from './translations/fi_FI.json'; import trSv from './translations/sv_SE.json'; ReactDOM.render( <IntlProvider locale={my_locale} messages={{ fi: trFi, sv: trSv } ...

When using jQuery's ajax() function, it is possible to pass HTML as data and change the ampersands in URLs to &amp;

I have encountered an issue where I am capturing the HTML content of a page and attempting to send it as a string to a PHP web service using jQuery's ajax() function. However, when I receive the parameter on the PHP side, the &s in the URLs present wi ...

Having trouble scrolling to click on an invisible element due to a thread error in Selenium: Element visibility issue

I am facing an issue with clicking on an element that is not visible and requires scrolling to become visible. I have attempted to use JavaScript executor and action to resolve this problem, but encountered a thread error stating the element is still not v ...

` Why isn't Glide.js functioning correctly when incorporated into a Bootstrap 4 modal component?`

I'm currently utilizing Glide.js and a Bootstrap 4 modal on our team page to showcase the biography of the selected team member. This functionality is achieved by extracting the attribute of the clicked team member and using it as the startAt: index f ...

ECharts - Version 3.1.6 Event Plugin

I am looking for advice regarding the management of two charts with reference to echars from Baidu (version 3.1.6). Is there a way to control both charts by engaging in a click event on one of them? In simpler terms, how can I capture and respond to the c ...

Using Vue with Webpack and PapaParse for efficient data parsing

I have encountered an issue while trying to implement PapaParse's worker option () with Vue's webpack template (https://github.com/vuejs-templates/webpack). The error message I'm receiving is: Uncaught ReferenceError: window is not #defi ...

JavaScript not redirecting to HTML page as expected

I have developed a basic login page that makes an Ajax request to the backend. However, I am experiencing difficulties with redirecting the page upon successful login. The redirect function only seems to work 1 in 15 times, and I'm unsure of the reaso ...

Image not displaying correctly with Neatshow JS Plugin

I've added neatshow.min.js to my project and I'm following all the instructions in the script. The first step is to hide images with CSS, then show them using the script. Here are my instructions: $(window).ready(function(){ $('img&ap ...

Encountered an issue when trying to upload WordPress media files through XML-RPC

Here is a code snippet that I have created. public void uploadFile() throws Exception { byte file[] = org.apache.commons.io.FileUtils.readFileToByteArray(new File(path + realName)); String wpUpFile = fileToString(new File(path ...

What is the best way to extract basic information from a JSON object?

What is the best way to retrieve the weight value from this specific object? var prescription = "{'type':'" + $('#medi-type option:selected').val() +"',"+ "'weight':" + $('#weight').val() +","+ ...

Mastering basic DOM manipulation in React with ES6 techniques

My goal is to update the header text when a button is clicked. After trying the code below, I noticed it doesn't work and there are no console errors: class Test extends React.Component { click() { $(".update").val("new value") } ...