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?