Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Htmlunit ScriptException "console" is not defined

I am using htmlunit 2.9 and on java script parsing I am getting script exception due to console in following exception

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)

if I try specified page on firefox it works fine, I have tried v 3.6 as well as 9.0.1.

i have tried also to set setThrowExceptionOnScriptError(false) in order to avoid exception but engine stops or do not parse javascript after getting an error.

Is there any way that javascript engine can understand console in javascript?

like image 490
Rehman Avatar asked Apr 25 '26 18:04

Rehman


1 Answers

Your if condition isn't properly structured:

if (console && console.log){

That first if will throw an error if its not set; accessing console in environments its not defined in is like accessing any undefined variable; it will throw a ReferenceError.

Try:

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

Or:

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

It doesn't throw in error in Firefox since Firefox implements the Firebug API, as do Chrome and Safari. But, by default, Internet Explorer does not, so, it's worth doing a proper feature check here, as it will throw a ReferenceError in browsers that don't implement this API.

like image 139
Yahel Avatar answered Apr 27 '26 08:04

Yahel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!