1

I need to run a javascript function from java and save the response in a variable. I wrote the following code but it does not work:

public Object execute(String value) {
    SwingUtilities.invokeLater(() -> {
        new JFXPanel();
        Platform.runLater(() -> {
            WebView browser = new WebView();
            WebEngine webEngine = browser.getEngine();
            webEngine.setJavaScriptEnabled(true);

            Object response = webEngine.executeScript(value);
            Platform.exit();
        });
    });
    return response;
}

I'm using "WebView" because my javascript code, uses functions like "window", "document" and the libraries as "ScriptEngineManage" does not work in my case.

How can i solve this problem? My code works but the "response" is returned before that the executeScript ends.

Joseph
  • 335
  • 1
  • 3
  • 13
  • How do you determine that you get the result before the script is finished? It would also help to see the content of `value` which is the script that is executed. – hotzst Dec 27 '15 at 13:47

1 Answers1

0

You never set any content to your WebView. You need to call something like

browser.getEngine().load(url)

or

browser.getEngine().loadContent(html)

You need to provide at least a minimal html page to be able to access JS objects like window or document. And you have to wait for the WebEngine's state to have finished the load before accessing the Javascript objects.

P.J.Meisch
  • 18,013
  • 6
  • 50
  • 66