Reputation: 1393
I have written one method in java file and calling one method which is written in java script file with the help org.openqa.selenium.JavascriptExecutor
from that java file method. here is the code snippet:
public void validateFilename() {
JavascriptExecutor jsExec = (JavascriptExecutor) webDriver;
jsExec.executeScript("getFileName();");
}
function() {
window.getFileName = function() {
var fileName = "sampleFile.txt";
return fileName;
}
};
I am able to call method getFileName()
from java file but I am able to get the value of file name. If I give alert(fileName)
it is showing fileName but not able to return that method in java file.
Is there any way to return the value from js file to java file with the help of API of selenium JavascriptExecutor?
Upvotes: 1
Views: 17830
Reputation: 1073
Try the following:
String txt = "return document.title";
JavascriptExecutor js = (JavascriptExecutor) driver;
String res = (String)js.executeScript(txt);
Upvotes: -1
Reputation: 261
JavascriptExecutor.executeScript("<javascript code>")
allows you to execute JavaScript code, but when the code you pass to executeScript returns a value, Selenium won't know what the exact return type is at run time as JavaScript can return anything like Number
, String
, Array
, Object
etc.
To handle all return types, executeScript
returns an object of 'Object' class which in turn can handle any return type of JavaScript. We can typecast the object returned to any one of following supported objects:
WebElement
Double
is returnedLong
is returnedBoolean
is returnedString
is returned.List<Object>
with each object following the rules above. Map<String, Object>
with values following the rules above.
Unless the value is null or there is no return value, in which null is returned Upvotes: 3
Reputation: 148
You need to cast it to String when trying to get the response. Something like this:
String fileName = (String) jsExec.executeScript("return getFileName();");
Upvotes: 1
Reputation: 5347
Try the following code,
jsExec.executeScript( "return getFileName()");
Upvotes: 0