0

I am trying to use Rhino to covert some JavaScript code to Java. As anyone who has any experience at all with JavaScript knows "document" is used for lots of things. So, it is used in various functions in the code I am using. However, when I execute Rhino it just gives me this error

js: uncaught JavaScript runtime exception: ReferenceError: "document" is not defined.

Does anyone know what is causing this? And if so how to fix it? I am using Rhino version 1.7 on Ubuntu 14.10 64 bit.

Or if anyone could atleast show me how to evaluate JavaScript from within Java. I have done some research, but the code never works.

3
  • What is the nature of the JavaScript code you're trying to "convert"? Mar 14, 2015 at 20:41
  • Outside a browser based environment document doesn't mean much Mar 14, 2015 at 20:42
  • Well then, what would I use?
    – crank123
    Mar 15, 2015 at 1:28

2 Answers 2

1

Rhino is a just interpreter with only defines base object. Object such as 'document' 'window' is external HTML DOM object. It is out of scope for Rhino, or any other Javascript interpreter (such as jscript(IE) , V8 , spidermonkey, and nashorn).

Please refer java-based HtmlUnit which also uses Rhino and it defines most of HTML DOM objects. It is updated quite well.

6
  • So, how could I get around this?
    – crank123
    Mar 15, 2015 at 21:06
  • Since HtmlUnit can't just load JavaScript code and spit out Java code in a specified file name.
    – crank123
    Mar 15, 2015 at 23:27
  • okay. you have second question. You like to convert js to java class? Please take a look stackoverflow.com/questions/231550/… Mar 16, 2015 at 12:33
  • I hope it helps. I have never used this feature. Good luck! Mar 16, 2015 at 12:38
  • 1
    I'm very sorry! Nashorn may be better. Apr 1, 2015 at 18:54
1

After hours of digging and research I have been able to find out how to resolve this problem...

I have done two things.

I stopped using Rhino (considering it is outdated) and I switched to Nashorn


I also found out how to implement document

How to append xml nodes (as a string) into an existing XML Element node (only using java builtins)?

That took very unconventional means to find this answer, which would make any programmer go "Oh...That's one way to do it."

The way implemented in the question actually worked.

DISCLAIMER

My problems are not completely solved. Nashorn still gives me this error Exception in thread "main" java.lang.ClassCastException: Cannot cast java.lang.String to org.w3c.dom.DocumentType But, that's another question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.