我正在尝试使用 selenium Web 驱动程序从 java 调用 javascript 函数。
这是代码
WebDriver driver = new FirefoxDriver();
driver.get("C:\\KIRAN\\TrialAndError.htm"); // The html page is loaded here
// Following is the way i am trying to run the javascript
ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("javascript");
String script = "function getInputIds(param) {
print(\"inside getInputIds\");
var elems = document.form[0].elements;
var length = elems.length;
var arr = new Array();
var match_found = 0;
for (i = 0; i < elems.length; i++) {
match_found = elems[i].id.match(/order_unit_line_rate_\\d+_unit/);
if (match_found) {
arr.push(elems[i].id);
}
}
print(elems[1].id);}";
engine.eval(script);
Invocable inv = (Invocable) engine;
inv.invokeFunction("getInputIds", "Scripting!!" );
但是这是我运行此代码时遇到的错误
inside getInputIdsException : javax.script.ScriptException: sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "document" is not defined. (<Unknown source>#1) in <Unknown source> at line number 1
请通过初始化“文档”对象来帮助我运行这段代码。
还让我知道是否可以返回数组“arr”以在 javascript 之外的 java 文件中使用。
在此先感谢基兰