Hello. Please tell me: how can I execute a script located on a remote site in a java application? I tried to use ScriptEngineManager, but for some reason he doesn’t want to work at all. Set a task to write your own browser. But I just can not figure out the scripts. Initially, the site scripts are downloaded to the folder. But when they start to run, a bunch of errors crashes. For example, that there is no window variable, but after all, window is not a variable? Or am I misunderstanding something?

public void scriptExecutor(){ try{ File file = new File("/Users/user/desktop/js"); File[] f = file.listFiles(); ScriptEngineManager manager = new ScriptEngineManager(); ScriptEngine engine = manager.getEngineByName("nashorn"); for(int i = 0; i<f.length; i++){ System.out.println(f[i]); engine.eval(Files.newBufferedReader(Paths.get(f[i].getAbsolutePath()))); } }catch(Exception e){e.printStackTrace();} } 
  • 2
    window is an object representing a browser window. When the script is executed in a Java application, there is no browser, therefore no window . - user194374
  • Thank you very much for your reply. I will try to make a window for the browser. - leprikon
  • Could you tell me what this error means? Expected; but found var? - leprikon
  • one
    I can only translate: "A semicolon was expected, but a variable was encountered." Something with syntax. Just say without seeing the code is impossible. - user194374
  • Got it. Thank you very much. The script is incorrectly copied. - leprikon

1 answer 1

You have a very ambitious task. Create a browser, I would say this aerobatics. Google built chrome using webkit. If you have a task to make a full-fledged browser, I would advise not to reinvent the wheel and use the same webkit as an engine.
Now on the merits. Your problem is that nashorn is just a js engine. Unfortunately, he doesn't know anything about the browser context, about the window object, he doesn't even know anything about alert. In order to force it to execute code from a page, you need to create a context in accordance with the specifications for the browser context. That is, you need to create a window, document object and a bunch of other objects and methods and add them to the nashorn execution context.

First, take a look at the specification of the window object.

You can also look at some existing projects similar to what you are doing, for example jxwb

  • Often monitor your answers. Thank you for your deep and competent answers. It is a pity that SO has not yet entered a subscription - dirkgntly
  • Thank you for your reply. Indeed, in order to run some javascript, it was necessary to add objects such as window, document, etc. And as I understand it, to achieve the full execution of all javascript is a very non-trivial task. Once again, thank you for the answer, you really helped me figure it out. Thank you very much) - leprikon