Htmlunit ScriptException“console”未定义

时间:2011-12-31 21:26:09

标签: java javascript rhino htmlunit

我正在使用htmlunit 2.9并且在java脚本解析时因为console因以下异常而导致脚本异常

function debug(o){
  if (console && console.log){
    console.log(o)
  }
};

Stacktrace

EcmaError:
    lineNumber=[168]
    column=[0]
    lineSource=[null]
    name=[ReferenceError]
    sourceName=[script in http://localhost:808/mypage/ll.html from (154, 36) to (301, 14)]
    message=[ReferenceError: "console" is not defined. (script in http://localhost:8080.com/mypage/ll.html from (154, 36) to (301, 14)#168)]
com.gargoylesoftware.htmlunit.ScriptException: ReferenceError: "console" is not defined. (script in http://localhost:8080.com/mypage/ll.html from (154, 36) to (301, 14)#168)
         at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine$HtmlUnitContextAction.run(JavaScriptEngine.java:595)
         at net.sourceforge.htmlunit.corejs.javascript.Context.call(Context.java:537)
         at net.sourceforge.htmlunit.corejs.javascript.ContextFactory.call(ContextFactory.java:538)
         at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:545)
         at com.gargoylesoftware.htmlunit.javascript.JavaScriptEngine.callFunction(JavaScriptEngine.java:520)
         at com.gargoylesoftware.htmlunit.html.HtmlPage.executeJavaScriptFunctionIfPossible(HtmlPage.java:896)
         at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeEventHandler(EventListenersContainer.java:195)
         at com.gargoylesoftware.htmlunit.javascript.host.EventListenersContainer.executeBubblingListeners(EventListenersContainer.java:214)

如果我在firefox上尝试指定页面它工作正常,我已经尝试过v 3.6以及9.0.1。

我还尝试设置setThrowExceptionOnScriptError(false)以避免异常但发动机停止或在收到错误后不解析javascript。

javascript引擎是否可以在javascript中理解console

3 个答案:

答案 0 :(得分:2)

您的if条件结构不正确:

if (console && console.log){

如果没有设置,那将首先发出错误;在未定义的环境中访问console就像访问任何未定义的变量一样;它将抛出一个ReferenceError

尝试:

if( typeof console != "undefined" && console.log ) {

或者:

if(window.console && console.log) {

它不会在Firefox中引发错误,因为Firefox实现了Firebug API,Chrome和Safari也是如此。但是,默认情况下,Internet Explorer不会,因此,值得在此处进行正确的功能检查,因为它会在未实现此API的浏览器中引发ReferenceError。

答案 1 :(得分:2)

答案 2 :(得分:0)

您的代码确实使用了java脚本控制台对象,并且在当前版本之前它不受支持,并且承诺在下一个版本中支持它,因为它是here