Java Selenium Javascript executor fails to return desired result

Attempting to execute a javascript function I created to gather all comments from an HTML site using xpath (requirement).
The function, when pasted directly into a browser without the 'return' statement, works flawlessly.
However, when run through the selenium 'javascriptexecutor', it returns an empty array.
I understand that javascript statements need to be enclosed in a " code "+ format, but for clarity purposes, I structured my code like this.
Hoping someone can assist me with this issue :)

ChromeDriver driver = new ChromeDriver();
String url = "AprivateSamplePage";
driver.get(url);
JavascriptExecutor js = (JavascriptExecutor) driver;
String text = (String)  js.executeScript("return nodes =[]; 
xPathResult=document.evaluate('//comment()',document,null,XPathResult.ANY_TYPE, null); 
nodes =[]; 
node = xPathResult.iterateNext(); 
while (node) {nodes.push(node.textContent); 
node =  xPathResult.iterateNext();}
nodes;").toString();
System.out.print(text);

The Output appears as follows:

Only local connections are allowed.
Okt 30, 2018 8:56:07 AM org.openqa.selenium.remote.ProtocolHandshake createSession
INFORMATION: Detected dialect: OSS
[]
Process finished with exit code 0

Answer №1

The script

js.executeScript("return nodes =[];");
is the only part being executed, while the rest of the script is disregarded after that return statement. This results in an empty array being returned.

According to the javaDoc documentation for executeScript(String), your script code is enclosed and run as the body of an anonymous function like this:

function f() {
    return nodes = [];
    xPathResult = document.evaluate('//comment()', document, null, XPathResult.ANY_TYPE, null);
    nodes = [];
    node = xPathResult.iterateNext();
    while (node) {
        nodes.push(node.textContent);
        node = xPathResult.iterateNext();
    }
    nodes;
}();

Each script statement is separated by ";". Since the first statement is a return statement, the function ends there and returns the empty array as the result.

In the browser console, the script behaves as expected because it does not halt at the return statement, but rather displays the final value of nodes;.

To correct this issue, you should move the return statement from the first to the last position:

xPathResult = document.evaluate('//comment()', document, null, XPathResult.ANY_TYPE, null);
nodes = [];
node = xPathResult.iterateNext();
while (node) {
    nodes.push(node.textContent);
    node = xPathResult.iterateNext();
}

return nodes;

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

To close the responsive menu, simply click anywhere outside of the navigation bar

My issue involves a responsive menu with Bootstrap. On desktop, the menu closes fine; however, on the responsive view, I want it to close when clicking outside of the nav menu in any area. Here is my navigation code: <!-- Navigation --> <nav id= ...

Error occurred in the "main" thread due to org.openqa.selenium.WebDriverException

Encountering an error while testing my application in Eclipse IDE using Java. Appium server is running, and port numbers match. The log trace is provided below. Any assistance would be greatly appreciated. Thank you. Below is the code snippet used to test ...

What is preventing me from returning the result of $.ajax, but I can return the result of $http.post?

I am facing an issue with having 2 return statements in my code: return $http.post({ url: CHEAPWATCHER.config.domain + 'api/Authenticate', contentType: 'application/x-www-form-urlencoded; charset=UTF-8', data: data }); re ...

Organizing requirejs and angularjs code structure into separate files

Looking to organize my Angular application with requirejs by separating controllers, services, and directives into different files. Hoping to achieve this structure: src/ components/ Navigation/ index.js module.js NavigationCon ...

What strategies can I implement to integrate Cordova with a combination of Meteor and React?

I'm currently struggling to implement a Cordova plugin with Meteor and React. According to the documentation: You should wrap any functionality that relies on a Cordova plugin inside a Meteor.startup() block to ensure that the plugin has been fully ...

Is it considered fashionable to utilize HTML5 data attributes in conjunction with JavaScript?

Currently, I am utilizing HTML5 data attributes to save information such as the targeted DOM element and to initialize events using jQuery's delegation method. An example of this would be: <a href="#" data-target="#target" data-action="/update"> ...

In React, the ES6 prototype method map failed to render anything on the screen

Is there an issue with my map method implementation? var App = React.createClass({ getInitialState(){ return { items:[1,2,3] } }, renderItem(){ return( this.state.items.map((item,i))=> <li key={i}> { ...

An error of type 'TypeError' has occurred, where it is unable to access the property 'render' of an undefined element in

I'm using a function in my controller to render the "result" in my "home-page" view, which is calling my model to execute the query. exports.searchNoms = (req, res) => { getDatabaseModel.searchNoms(req).then(function(result) { console.l ...

Unusual Behavior Observed in JavaScript Map Reduce

var t = [-12, 57, 22, 12, -120, -3]; t.map(Math.abs).reduce(function(current, previousResult) { return Math.min(current, previousResult); }); // returns 3 t.map(Math.abs).reduce(Math.min); // returns NaN I'm puzzled as to why the second variant ...

Implementing AJAX to dynamically insert content into div elements on the page

Currently facing a small issue with my AJAX implementation for creating comments on posts. The functionality is working well, but the problem arises when executing it in the index.html.erb view. The create.js.erb file locates the initial div labeled "comme ...

Create a package that is compatible with both node and browser environments

After successfully creating a node NPM package that acts as a wrapper for a specific JSON API using node's http, https, and querystring modules, I am now looking to expand its usability by making it compatible with browsers. This would involve replaci ...

Unable to begin the previous project on my Mac, but it functions properly on Windows

After running npm i, I encountered the following error message which I am unsure how to resolve. I tried reinstalling Node.js, Python, and Pyenv, but the issue persists. Interestingly, the same version of Node.js on Windows runs the project without any p ...

Adapting Vue.js directive based on viewport size - a guide

Having an element with the v-rellax directive, I'm utilizing it for prallax scrolling in this particular div: <div id="image" v-rellax="{ speed: -5 }"></div> Currently, there's a need to adjust the speed property ...

What could be causing the NoScript tag to malfunction across different web browsers?

I've incorporated the NoScript tag into my JSP pages in the head section. To avoid conflicts with tiles, I made sure not to include multiple NoScript tags. However, I am experiencing issues in Internet Explorer where it doesn't seem to be working ...

What Causes My Issue with $(document).ready()?

Currently delving into the world of jQuery, but I've hit a roadblock. Below is the snippet in question: var script = document.createElement('script'); script.src = 'https://code.jquery.com/jquery-3.4.1.min.js'; script.type = " ...

Does the Node Schedule library create new processes by spawning or forking them?

Is the node-schedule npm module responsible for spawning/forking a new process, or do we need to handle it ourselves? var cron = require('node-schedule'); var cronExpress="0 * * * *"; cron.scheduleJob(cronExpress, () => { //logger.info(" ...

Utilizing Codeigniter for transmitting JSON data to a script file

When querying the database in my model, I use the following function: function graphRate($userid, $courseid){ $query = $this->db->get('tblGraph'); return $query->result(); } The data retrieved by my model is then encoded in ...

What is the best way to incorporate a minimum width and maximum width in CSS that add up to 100% when necessary?

Can anyone help me find CSS rules that can set a fixed width for an element (width: 500px) but also allow it to be responsive with max-width: 100% if the container is narrower than the element? I saw this example and it works perfectly: .elem { width: 60 ...

What is the best way to retrieve user interaction data in Discord.js v13?

Is there a way to retrieve the activities from interaction.options? Whenever I try using interaction.options.getUser, I encounter this error message: cannot read properties of undefined (reading 'activities') Below is the snippet of my code: con ...

Display information using AngularJS within the Ionic framework

I am attempting to display a variable that is within a for loop. Here is my code where I store the value of $scope.datosTuto[i].Nombre in a variable. When I use an alert to print $scope.NombTuto, I can see the data but I want to display it on my HTML page. ...