[英]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.我已经在 java 文件中编写了一种方法,并在
org.openqa.selenium.JavascriptExecutor
的帮助下从该 java 文件方法调用了一种在 java 脚本文件中编写的方法。 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.我可以从 java 文件调用
getFileName()
方法,但我可以获取文件名的值。 If I give alert(fileName)
it is showing fileName but not able to return that method in java file.如果我给
alert(fileName)
它显示 fileName 但无法在 java 文件中返回该方法。
Is there any way to return the value from js file to java file with the help of API of selenium JavascriptExecutor ?有没有办法在 selenium JavascriptExecutor的 API 的帮助下将值从 js 文件返回到 java 文件?
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. JavascriptExecutor.executeScript("<javascript code>")
允许您执行 JavaScript 代码,但是当您传递给 executeScript 的代码返回一个值时,Selenium 将不知道运行时的确切返回类型是什么,因为 JavaScript 可以返回类似Number
、 String
、 Array
、 Object
等。
To handle all return types, executeScript
returns an object of 'Object' class which in turn can handle any return type of JavaScript.为了处理所有返回类型,
executeScript
返回一个“Object”类的对象,而该对象又可以处理 JavaScript 的任何返回类型。 We can typecast the object returned to any one of following supported objects:我们可以将返回的对象类型转换为以下任何一种支持的对象:
WebElement
WebElement
Double
is returnedDouble
Long
is returnedLong
Boolean
is returnedBoolean
String
is returned.String
。List<Object>
with each object following the rules above.List<Object>
,每个对象都遵循上述规则。Map<String, Object>
with values following the rules above.Map<String, Object>
。 Unless the value is null or there is no return value, in which null is returnedYou need to cast it to String when trying to get the response.尝试获取响应时,您需要将其转换为 String。 Something like this:
像这样的东西:
String fileName = (String) jsExec.executeScript("return getFileName();");
试试下面的代码,
jsExec.executeScript( "return getFileName()");
Try the following:请尝试以下操作:
String txt = "return document.title";
JavascriptExecutor js = (JavascriptExecutor) driver;
String res = (String)js.executeScript(txt);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.