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

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

You don't need javascript to do that. Use HTTP clients like github.com/square/okhttp or 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 stackoverflow.com/questions/457684/…
thank you. I want to load document and add EventListener for button programmatically, that's why i'm using javascript.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.