passing values to JavaFX from javascript

ⅰ亾dé卋堺 提交于 2019-12-02 10:27:25
José Pereda

I've tried a simplified version of your code:

    WebEngine webEngine = browser.getEngine();

    webEngine.getLoadWorker().stateProperty().addListener((ov,oldState,newState)->{
        if(newState==State.SUCCEEDED){
            JSObject window = (JSObject) webEngine.executeScript("window");
            window.setMember("app", new JavaApplication());
        }
    });
    webView.getEngine().loadContent("<html>\n"
            + " <script>function initialize() {"
            + " var lengthInMeters = 5; " 
            + " app.calljavascript(lengthInMeters);"
            + "} </script> "
            + "    <body onLoad=\"initialize()\">Hi!\n"
            + "    </body>\n"
            + "</html>");

and it's not working.

In your case and in my approach, setMember() is called after the web has been loaded, so initialize() is called before by the load method. Consequently, app.calljavascript() fails.

The solution is this:

    WebEngine webEngine = browser.getEngine();
    JSObject window = (JSObject) webEngine.executeScript("window");
    window.setMember("app", new JavaApplication());

    browser.getEngine().loadContent("<html>\n"
            + " <script>function initialize() {"
            + " var lengthInMeters = 5; " 
            + " app.calljavascript(lengthInMeters);"
            + "} </script> "
            + "    <body onLoad=\"initialize()\">Hi!\n"
            + "    </body>\n"
            + "</html>");

Notice we set the member before the web content is loaded.

EDIT

I've created a more elaborated answer here.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!