无法在此代码中初始化“文档”

时间:2012-06-28 12:55:33

标签: java javascript selenium-firefoxdriver

我正在尝试使用selenium web driver从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文件中使用。

先谢谢 基兰

2 个答案:

答案 0 :(得分:1)

我认为当驱动程序实例内置ScriptEngine时,不需要使用ScriptEngine。

来自FAQ

您可以通过将WebDriver实例强制转换为JavascriptExecutor来执行Javascript。在Java中,这看起来像:

WebDriver driver; // Assigned elsewhere
JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("return document.title");

答案 1 :(得分:0)

我试过这个

JavascriptExecutor js = (JavascriptExecutor) driver;
js.executeScript("C:\\QA\\Selenium\\workspace\\Module-NewServiceOrder\\src\\momentum\\getInputIds.js","");

但这是结果

Exception : org.openqa.selenium.WebDriverException: null (WARNING: The server did not provide any stacktrace information)

命令持续时间或超时:63毫秒 构建信息:版本:'2.24.1',修订版:'17205',时间:'2012-06-19 16:53:24' 系统信息:os.name:'Windows 7',os.arch:'amd64',os.version:'6.1',java.version:'1.7.0_03' 驱动程序信息:driver.version:RemoteWebDriver 会议ID:e2a43e1d-0eec-4640-ac0f-d72a485d98f8

我甚至无法进入功能