Solving the puzzle of closing a challenging JavaScript popup with Selenium in JavaScript

Dealing with popups in Selenium can sometimes be tricky, especially when encountering unusual behavior. I recently encountered a situation where I found it difficult to close a popup window after clicking a button.

Upon executing the code below:

WebElement button = driver.findElement(...);
log.info("step 1");
button.click();
log.info("step 2");
Alert alert = driver.switchTo().alert();
alert.accept();
WebElement nextButton = driver.findElement(...);
nextButton.click();

I noticed that the log did not display the "step 2" message. Moreover, Eclipse seemed to freeze after the button click, despite the fact that the click was successful and a subsequent popup appeared on the page.

Upon further investigation, I discovered that the button's onclick function contained the following JavaScript code:

continueButton();return;

It seemed that the popup window was being triggered from within the continueButton() function.

My theory is that my Java code was waiting for this JavaScript function to complete and return control. However, since the popup window was blocking the JavaScript execution, I couldn't proceed with closing the window programmatically. Interestingly, manually closing the window allowed the Java code to resume execution and the "step 2" message to appear in the log.

Given that I couldn't modify the page source, I attempted to run the JavaScript code separately, instead of simulating the click event:

jsexecutor.execute("continueButton();")
log.info("step 1");
Alert alert = driver.switchTo().alert();
alert.accept();
jsexecutor.execute("return;")

However, this approach resulted in the same behavior - the popup window appeared, but the "step 1" message was not logged, indicating that the Java execution was halted.

Is there a workaround for this issue that doesn't require changing the page source?

Answer №1

When using switchTo().alert() and then findElement(...) to trigger a click() action on the nextbutton, there are specific considerations to keep in mind. It is important to handle a JS Alert by ensuring that it is properly displayed in the HTML before proceeding. Furthermore, after confirming an Alert, it is crucial to wait for the target button to become clickable before executing the action:

log.info("step 1");
driver.findElement(By.xpath("xpathExpression_of_button")).click();
new WebDriverWait(driver, 5).until(ExpectedConditions.alertIsPresent());
log.info("step 2");
driver.switchTo().alert().accept();
new WebDriverWait(driver, 5).until(ExpectedConditions.elementToBeClickable(driver.findElement(By.xpath("xpathExpression_of_nextButton")))).click();

Answer №2

After much trial and error, I have finally come up with a solution. Before the click event that triggers the popup window and halts my code execution, I implemented a Thread to pause for a few seconds and then close the popup window by clicking its close button:

    DelayedClicker delayedClicker = new DelayedClicker(getDriver(),
            xpath, 30, log,
            EnumXpath.POPUP_WINDOW_TITLE, null);
    delayedClicker.start();
    WebElement button = getDriver()
            .findElement(...)));
    button.click();

Within the Thread itself

    Thread.sleep(delay * 1000);
    if (windowTitle != null)
        switchWindowByTitle(windowTitle);
    if (frameTitle != null)
        switchFrameByTitle(frameTitle);
    WebElement button = driver.findElement(By.xpath(xpath));
    button.click();

Admittedly, it's not ideal to have the same WebDriver instance in two separate Threads, but in this scenario, it appears to be the only viable option. By initiating the Thread before the code block occurs, the popup is effectively handled, allowing the code to proceed without obstruction.

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

Transferring information between two tables in a MongoDb database

My current database in mongo is named "sell" and it contains two tables: "Car" and "Order". In the "Car" table, there is an attribute called "price". When I run the following command in the mongo shell: db.Order.aggregate([ { $lookup: { from: ...

Using JS or jQuery to organize JSON data into a multidimensional array

Dealing with frontend processing of a response from a server that provides event reviews for the season has been challenging. In this case, there can be multiple reviewers for the same event and the simplified version of the response appears as follows: [ ...

Tips for restricting camera movement in threejs

Being new to working with threejs, I am struggling to set limits on the camera position within my scene. When using OrbitControls, I noticed that there are no restrictions on how far I can zoom in or out, which I would like to change. Ideally, I want the c ...

Gain entry to Zurb Foundation for Apps modules within your AngularJS application

Currently, I am developing an AngularJS application utilizing Foundation for Apps. One key element in my layout is a Foundation Apps panel that serves as the top menu. <div zf-panel="" id="topMenu" position="top" class="panel-fixed">...</div> ...

Making an AJAX call to a PHP script to add data

Could you assist me in understanding why my code is resulting in a double insert? I have a JavaScript function that makes an AJAX request to a save.php file to insert data into a database. However, each time I submit it, it performs the insertion twice, al ...

Using API calls to update component state in React-Redux

I am currently working on setting up a React application where clicking on a map marker in one component triggers the re-rendering of another component on the page. This new component should display data retrieved from a database and update the URL accordi ...

Respond to a recommendation with a response

I've been working on setting up a bot for my Discord server, and I recently added a "marry" command to it. Whenever a user makes an offer, a message announcing the proposal pops up with two reaction options. The first reaction signifies yes, while th ...

What is the method to prolong the end date of fullCalendar.js through Javascript?

I am facing the same issue as this individual. I am unsure of how to add one day to the end date. I do not want to alter the database value, only modify it on the HTML page. Currently, this is my calendar (no Moment.js joke intended): $(document).ready(f ...

Using an AngularJS array with ng-repeat

As soon as a websocket message is received, the code below executes: connection.onmessage = function (eventInfo) { var onConnectionMessage = JSON.parse(eventInfo.data); if (onConnectionMessage.messageType === "newRequest") { getQuizRequests(); } } T ...

Tips for Managing Pop-Up IFrame Windows Using Selenium

Just starting out with Selenium. https://i.sstatic.net/hvvMm.png Currently tackling the challenge of handling a pop-up form. Every time I click on the New Button, a pop-up form like this one opens up. https://i.sstatic.net/jvNgO.png I've tried usin ...

On page load, refresh the content of the div based on the selected radio button values

My goal is to automatically collect the values of checked radio buttons when the page loads, rather than waiting for a user interaction like clicking a radio button. Below is the JavaScript code I am using: $(function () { updateDivResult(); $(&a ...

Exploring the intricacies of Java's advanced data binding capabilities using JSON

I'm currently facing an issue with the @OneToMany bindings and the bindFromRequest method in Java Play. The situation involves a Client model that contains multiple FinancialAsset models @Entity public class Client extends Model { ... @OneToMany(cas ...

How can Components access variables declared in a custom Vue.js plugin?

I had developed a unique Vue js plugin to manage global variables as shown below: CustomConstants.js file: import Vue from 'vue' export default { install(Vue){ Vue.CustomConstants = { APP_VERSION: '2.1.0' ...

Ways to determine if an equation contains multi-digit numbers

A project is underway to create a system for converting infix notation to postfix. Take a look at the following code snippet: import javax.swing.*; import java.util.Stack; public class InfixToPostfix { public static int Precedence(char c) { ...

Is it possible to capture a screenshot of a website quickly using Python?

Currently, I am looking to automate a web game. To achieve this, I have been retrieving pixels from the screen using the following method: data = driver.get_screenshot_as_file("screen.png") #Take Screenshot image = Image.open("screen.png&quo ...

What could be causing the request body in ExpressJs to be blank?

Using ExpressJs, I have created a simple app that can handle post requests and form submissions. Below is the code snippet from my index.js file: require ('./models/db'); const express = require('express') const app = express() const bo ...

Combining Java with Node.js modules

I'm interested in incorporating Angular2 as the client side framework and Java as the server side. However, I am unfamiliar with how to integrate Angular2 into a Java project. Is it advisable to initialize the NPM system within the Java project and in ...

Enhancing MEAN Stack Application by Updating Table Post Database Collection Modification

In my efforts to ensure that my table data remains synchronized with the database information, I have encountered an issue. Whenever Data Changes: $scope.changeStatus = function($event,label,status){ var target = $event.currentTarget; target ...

Keep your session active on Selenium by utilizing the default Chrome profile for seamless browsing

Attempting to utilize Selenium with my Google profile, I wrote the following code: options = webdriver.ChromeOptions() options.add_argument(r"user-data-dir=C:\Users\myprofile\AppData\Local\Google\Chrome\User Data&q ...

React component experiencing double execution of SetTimeout function

Every time I render the App component, the code inside setTimeout seems to be running twice. I've noticed that setTimeout executes after the call stack is cleared. I wonder if this has any connection to the issue. Could it be related to how React ha ...