1

i'm trying to call document in java using scriptEngine here is my code

     ScriptEngineManager scriptEngineManager=new ScriptEngineManager();
     ScriptEngine scriptEngine=scriptEngineManager.getEngineByName("nashorn");
    scriptEngine.eval("function func(){" +
    "document.location.href=someUrl;" +
                  "var text=document.getElementsByTagName('textarea')[0];"}"
                    );
            Invocable invocable= (Invocable) scriptEngine;
            ((Invocable) scriptEngine).invokeFunction("func");

it throws an exception

javax.script.ScriptException: ReferenceError: "document" is not defined in <eval> at line number 1
DoctorDo
  • 331
  • 2
  • 6
  • 15

1 Answers1

3

The script engine in Java provides the ability to execute Javascript code, but does not provide an emulation of a browser.

document, window and other objects are defined by the browsers but are not mandated to be present by ECMAScript specification (http://www.ecma-international.org/ecma-262/5.1/#sec-15).

metlos
  • 306
  • 2
  • 5
  • You don't need javascript to do that. Use HTTP clients like https://github.com/square/okhttp or https://hc.apache.org/ to download the **raw HTML** of the page. That will NOT give you the DOM of the page as you would expect in a browser, though (which you would not get in a script engine either). To obtain the DOM from the raw html text, check for example this http://stackoverflow.com/questions/457684/reading-html-file-to-dom-tree-using-java – metlos Mar 02 '16 at 10:48
  • thank you. I want to load document and add EventListener for button programmatically, that's why i'm using javascript. – DoctorDo Mar 02 '16 at 11:01