When using WebDriver's executeScript method, the returned text from an alert is provided rather than the value obtained from a JavaScript

Here is my JavaScript code embedded in an HTML file:

function CallMe(a,b){
            alert("Hello");
            var c = a + b;
            return c;
        }

Below is my Java code for Selenium WebDriver:

JavascriptExecutor executor = (JavascriptExecutor)driver;
Object result = null;

try{
    result = executor.executeScript("return(CallMe(5,4))");
    driver.switchTo().alert().accept();
}catch(NoAlertPresentException ex){
    System.out.println("Alert not found");
}
driver.manage().timeouts().setScriptTimeout(30,TimeUnit.SECONDS);
System.out.println(result.toString());

When I run the Java program, it shows "Hello" as output if the alert box is present. However, if I remove the alert box, it displays "9" as expected result.

I'm curious why the remaining JavaScript statements are not executed when there's an alert box, even though I have accepted it in my Java code.

If anyone has an alternative solution or explanation, please share. Thank you!

Answer №1

alert() function in javascript pauses the execution until the alert is dismissed. In this case, WebDriver's JavascriptExecutor quickly retrieves the text from the alert box instead of waiting indefinitely for the entire script to finish synchronously. This allows Java execution to continue smoothly and enables the driver to take action on the alert. However, after handling the alert, the WebDriver no longer receives any further results from the javascript.

If you're interested, you can modify your code to observe this halt in execution by adding some logs:

function CallMe(a,b){
    console.log('before alert at ' +new Date().toString());
    alert("Hello");
    console.log('after alert at ' +new Date().toString());
    var c = a + b;
    return c;
}

To address this issue, consider using executeAsyncScript() instead of executeScript() to prevent blocking. This method allows you to wait for the alert to be displayed, close it, and then retrieve the result of your javascript execution. Refer to WebDriver executeAsyncScript vs executeScript and follow the instructions in the answer to Alert handling in Selenium WebDriver (selenium 2) with Java for more guidance.

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

"Displaying the y-axis in d3.js: A Step-by-Step

I am a beginner in d3.js and I'm having trouble with my y-axis not showing up in the browser. Can someone please help me find a solution? var barOffset=5; var barWidth=50; var width=700,height=700; function processData(data,key){ var objects=[]; ...

What type does a React stateless functional component Flow return?

If I have a structure like this const RandomComponent = (props) => ( <div> <SomeSubComponent id={props.id} /> <AnotherSubComponent type={props.type} /> </div> ) How do I specify the return type using Flow, i.e., wha ...

Convert a div into a clickable link using JavaScript without using too many classes or any ids

After using shortcodes generated by functions.php in a WordPress parent theme, I have come across the following HTML code: <div class="pricing-table-one left full-width "> <div class="pricing-table-one-border left"> <div class=" ...

Fetching JSON and API data to populate Graphs for Android Application

I'm currently working on an Android app using Kotlin to track Covid-19 data. I've implemented retrofit to fetch the information from an API provided by CovidActNow.org, which requires an API key. However, when testing my app, the data is not bein ...

Ensure data accuracy by triggering the cache - implementing SWR hook in Next.js with TypeScript

I recently implemented the swr hook in my next.js app to take advantage of its caching and real-time updates, which has been incredibly beneficial for my project (a Facebook clone). However, I encountered a challenge. The issue arises when fetching public ...

Transferring data from PHP to JavaScript using AJAX

I'm currently working on a project that involves generating random numbers on both JavaScript and PHP pages, and I need to display them on the HTML page using JavaScript. So far, I have successfully set up both pages to generate random numbers. Howev ...

Exploring the Efficiency of Selenium for Testing Enterprise Web Applications

As a newcomer to Selenium Automation in a DevOPS environment, I am comfortable using the framework and automating some basic tests. However, I am unsure of the extent of functionality that can be automated in an Enterprise Web Application. Our test automat ...

Is it necessary for Java programmers to manually release memory for JNI objects?

One example involves a class that utilizes JNI. Here is some code snippet: public class JniUser { private String name; private int age; public native int getAge(); public native String getName(); } In the native code, the name and age fiel ...

Tips for preventing a child div from moving when scrolling towards it and creating an internal scroll with a smooth animation using either JavaScript or jQuery

Looking to add scrolling functionality with animation to a child div on my webpage? Check out this example. I attempted using JavaScript's on scroll function, but it didn't work as expected. Currently, I have it set up to trigger on click of cer ...

Troubleshooting: How to resolve the issue of receiving undefined values when passing API data to a child component with Axios in React

I am encountering difficulties in retrieving data that I pass to a child component. The issue may be related to the Promise not being resolved at the time of access, but I am unsure how to address it. My goal is to ensure that the data is fully retrieved f ...

Using Commas to Separate ChartJS Data Points

I am having trouble formatting numbers in a ChartJS graph to include commas. For example, my data points are currently displayed as 1032.05, 4334.75, 8482.46 but I need them to show as 1,032.05, 4,334.75, 8,482.46. If you would like to see the current cod ...

Analyzing two columns to determine if one column contains a specific text value and the other column presents a radio button in an HTML form

Is there a way to compare two columns in HTML, where one column contains text values (OK/NG) and the other has radio buttons for manual evaluation? The desired outcome is to display the result in a third column labeled "Difference" using either jQuery or J ...

Adjusting the dimensions of a tri-fiber canvas prior to saving it

I have a unique inquiry regarding Three Fiber. Once the download button is clicked, it generates a base64 using toDataURL, which can then be downloaded. The resulting image adopts the height and width of the canvas, which in turn matches the height and w ...

Guide to displaying aggregated table field values in an input field when checking the checkbox

How can I retrieve the value of the second span and display it in an input field when a checkbox is checked? For example, if there are values like 500 in the first row and 200 in the second row, when the checkbox in the first row is ticked, the value of 50 ...

Is there a way to continuously cycle through multiple images fading in and out at various locations on a webpage using absolute positioning?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"><head> <title>Harley's Art Gallery</title> <script t ...

How can I showcase the data from a JSON file on a website using Jquery.GetJSON in combination with HTML/JS on a

I have searched for similar questions, but none of the answers have solved my issue. The JSON code can be found at this link. I am attempting to show the "value_sell" and "value_buy" objects from the "official" and "blue" sections. I have inserted the fo ...

Modifying element information in JavaScript for a Django/Heroku web application

Is it possible for me to update the values of a data object within my JavaScript code? My JavaScript receives post messages from an iframe, and I need to store this information in the correct objects. However, I am unsure if this can be done on the HTML su ...

Adjusting the filter location in React-admin

This is the common method of implementing filters in react-admin https://i.stack.imgur.com/M8yq7.png However, in my particular scenario, I require the filters to be inside each column heading. For example: https://i.stack.imgur.com/GU2Pz.png The filter ...

Steer clear of utilizing Number() when working with scientific notation

I am attempting to perform the following task Number("0.00000000000122") yields 1.22e-12 However, my goal is to convert that number from a String to a Number. console.log(Number("0.00000000000122")) ...

Do class bindings with variables need to be inline when using Vue 3?

Consider the following HTML: <template v-for="(child, index) in group"> <div :class="{'border-pink-700 bg-gray-100 ': selected === child.id}"> <div>Container Content</div> </div> & ...