Develop a custom JavaScript code block in Selenium WebDriver using Java

Recently, I came across a JavaScript code snippet that I executed in the Chrome console to calculate the sum of values in a specific column of a web table:

var iRow = document.getElementById("DataTable").rows.length
var sum = 0
var column = 5
for (i=1; i<iRow; i++){
    var retail = document.getElementById("DataTable").rows[i].cells.item(5).innerText
    var splitRetailPrice = retail.split(" ")
    for(j=0; j<splitRetailPrice.length; j++){
        var trimValue = splitRetailPrice[1]
        var intPrice = Number(trimValue)
        sum += intPrice
        break
    }
}
console.log(sum)

However, when I tried implementing this code using Selenium WebDriver with locator elements, it took more than 5 minutes due to the large number of rows in the web table.

I'm contemplating running the JavaScript code directly through Selenium using Java. Is this a viable solution?

If so, how do I go about incorporating multiple lines of JavaScript code and returning the computed value? I've seen examples with single line returns, but I need assistance creating a method that can handle multiple lines of code and return a value.

SECOND ATTEMPT:

Following some suggestions on a similar issue, I attempted the following approach:

JavascriptExecutor js = (JavascriptExecutor)driver;
String val = (String) js.executeScript(
        "return"+
        "var iRow = document.getElementById('DataTable').rows.length"+
        "var sum = 0"+
        "for (i=1; i<iRow; i++){"+
            "var retail = document.getElementById('DataTable').rows[i].cells.item(5).innerText"+
            "var splitRetailPrice = retail.split("+" "+")"+ //passing a space as a delimiter.
            "for(j=0; j<splitRetailPrice.length; j++){"+
                "var trimValue = splitRetailPrice[1]"+
                "var intPrice = Number(trimValue)"+
                "sum += intPrice"+
                "break"+
            "}"+
        "}");

System.out.println(val);

Unfortunately, I encountered an error: org.openqa.selenium.JavascriptException: SyntaxError: unexpected token: identifier

Can anyone help me identify what's causing this issue?

Answer №1

This is how I tackled the issue and found a solution that might be useful to someone else.

public int calculateTotalCost() {

 JavascriptExecutor js = (JavascriptExecutor) driver;
 Long totalRows = (Long) js.executeScript("return document.getElementById('DataTable').rows.length");
 int sumRetail = 0;

 for (int j = 1; j < totalRows; j++) {
  String retailPrice = (String) js.executeScript(
   "return document.getElementById('DataTable').rows[" + j + "].cells.item(5).innerText"); //6th column
  String[] splitPrice = retailPrice.split(" "); //split the actual value
  int price = Integer.valueOf(splitPrice[1]);
  sumRetail += price;
 }
 return sumRetail;
}

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

Getting input elements with Puppeteer can be done by waiting for the page to fully load all elements within the frameset tag

Seeking to gather all input elements on this website: This is how the element source page appears. Below is my code snippet: const puppeteer = require("puppeteer"); function run() { return new Promise(async (resolve, reject) => { try { ...

Issue with Pagination functionality when using Material-UI component is causing unexpected behavior

My database retrieves data based on the page number and rows per page criteria: const { data: { customerData: recent = null } = {} } = useQuery< .... //removed to de-clutter >(CD_QUERY, { variables: { input: { page: page, perPag ...

An issue occurred during the project compilation using npm

My project installation process is giving me some trouble. Initially, when I run npm install, it successfully installs all the dependencies. However, when I proceed to execute npm run compile, I encounter an error. Below is the log file for a better under ...

Tips for containing a moving element within the boundaries of its container div

I have a dynamic box placed inside another box, and I want to restrict its movement within the boundaries of the parent container. How can I achieve this? In simpler terms: I need the frog to stay within the frogger. HTML <div id="frogger"> ...

Karma jasmine and an angular controller that utilizes the 'Controller as' syntax (where 'this' is used instead of $scope)

I'm having trouble setting up karma for my unit tests, specifically on a basic example: Here is the controller file: angular.module('balrogApp.requests', [ /* Dependencies */ ]) // Routes configuration .config(['$routeProvider&a ...

The function does not provide an output of an Object

I have two JavaScript classes, Controller.js and Events.js. I am calling a XML Parser from Events.js in Controller.js. The Parser is functioning but not returning anything: SceneEvent.prototype.handleKeyDown = function (keyCode) { switch (keyCode) { ...

What is the best way to implement a date range filter in AngularJS for a specific year or month?

I am just starting to learn AngularJS. I have a date formatted as follows: d MMM y. However, I have two fields - one called "from" and the other "to" - that should act as filters for the date range, based on a year range or month range. Here is how I am or ...

HtmlUnit may be experiencing memory issues, such as Out Of Memory errors and potential memory leaks

When using Selenium alongside HtmlUnitDriver with javascript enabled in Java, I encounter Out Of Memory errors while simply browsing the same page with a single GET command. How can I resolve this issue? ...

Utilizing $http (REST) to send information from a form

Struggling to leverage Angular for CRUD processes, especially encountering difficulties with POST requests to the server. This is my controller: angular.module('myModule').controller("ListingCtrl", function($scope, posts) { $scope.addProje ...

The JavaScript-generated form element will not be included in the data submitted through the POST method

While it may appear that this question has been asked before, my specific inquiry seems to be unique as I have not found a similar answer in other threads. Therefore, I am initiating a new discussion. My issue revolves around a form which contains a link ...

Exploring the contrast between Selenium's --headless and -silent modes

Whenever I use the selenium option argument on my personal computer, whether in --headerless or --silent modes, everything runs smoothly. However, when attempting to run it on a client's device, it throws an error with a strange code. I've even t ...

Incorporate an additional javascript document into a VueJS component

What is the most efficient method to include Javascript files in Vue.js components? ...

Unlock the Power of Core 2 MVC with the Cutting-edge Integration of

Looking for a solution on how to effectively use JQuery Datatables with Core MVC? Check out this helpful resource: Using jQuery DataTables Grid With ASP.NET CORE MVC I recently downloaded the sample project and made some modifications to fit my needs. It ...

JavaScript random number functionality experiencing an unexpected problem

function generateRandomNumbers(){ var max = document.getElementById('max').value; var min = document.getElementById('min').value; var reps = document.getElementById('reps').value; var i; for (i=0; i<reps ...

Activate the CSS on a click event using the onClick method

I am trying to implement a transition that triggers when clicking on a specific div element. Currently, the transition only occurs with the active css class. How can I achieve this effect by simply clicking on the div itself? I am using reactjs and believe ...

What is the process for utilizing Selenium to establish a connection with a pre-existing FireFox instance via the debugger port?

I am looking to start Firefox and geckodriver separately, but it seems that selenium does not provide an interface for running a geckodriver that can connect to an existing FireFox instance. For Chrome, I have been able to achieve this with the following ...

Can this JSON object be created? If so, what is the process to do so?

Is it possible to create a JSON array with integers like the examples below? "data" : [ "1000": "1000", "1200": "1200", "1400": "1400", "1600": "1600", "1800": "1800", ] or "data" : [ 1000: 1000, 1 ...

Injecting Vue.JS data into an HTML attribute

I'm currently exploring Vue.JS and working on a status bar. I am curious about how to incorporate data from Vue into an HTML attribute. <div class="progress"> <div class="progress-bar" role="progressbar" aria-valuenow="score" aria-valuem ...

Sharing information between External JavaScript and React JS/Redux

Incorporating React-redux into an externalJs application (built on a custom JS framework) has posed a challenge for me. I am trying to initialize data for the Redux store from externalJS, but it seems that the external script is unable to access the React ...

Threads are never truly concluded in a satisfactory manner

I'm encountering an issue where some threads don't seem to be properly terminated. When I pause one of these threads in debug mode, the following list appears: Thread [<14> pool-2-thread-1] (Suspended) <VM does not provide monitor ...