Avinash Jadhav
Avinash Jadhav

Reputation: 1393

How to return value from JavascriptExecutor.executeScript() method in java

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

Answers (4)

Adrian Smith
Adrian Smith

Reputation: 1073

Try the following:

 String txt = "return document.title";
 JavascriptExecutor js = (JavascriptExecutor) driver;
 String res = (String)js.executeScript(txt);

Upvotes: -1

Aftaab Siddiki
Aftaab Siddiki

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:

  • For an HTML element in js return, this method returns a WebElement
  • For a decimal, a Double is returned
  • For a non-decimal number, a Long is returned
  • For a boolean, a Boolean is returned
  • For all other cases, a String is returned.
  • For an array, return a List<Object> with each object following the rules above.
  • For a map, return a 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

Taylan Derinbay
Taylan Derinbay

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

Murthi
Murthi

Reputation: 5347

Try the following code,

jsExec.executeScript( "return getFileName()");

Upvotes: 0

Related Questions