javaFX webview window.onload is fired before loadworker succeeds

久未见 提交于 2019-12-02 08:12:47
José Pereda

Maybe it's too late for an answer to this problem, but after answering this question, I've been trying to find a reason why executeScript has to be called after the complete load of the webpage.

So I've done this test:

    public class EarlyWebEngineTest extends Application {

    @Override
    public void start(Stage stage) {
        final WebView webView = new WebView();
        final WebEngine webEngine = webView.getEngine();

        // Early call of executeScript to get a JavaScript object, a proxy for the 
        // Java object to be accessed on the JavaScript environment
        JSObject window = (JSObject) webEngine.executeScript("window");
        window.setMember("app", new JavaApplication());

        webEngine.getLoadWorker().stateProperty().addListener((ov,oldState,newState)->{
            if(newState==State.SCHEDULED){
                System.out.println("state: scheduled");
            } else if(newState==State.RUNNING){
                System.out.println("state: running");
            } else if(newState==State.SUCCEEDED){
                System.out.println("state: succeeded");
            }
        });

        Button button=new Button("Load Content");
        button.setOnAction(e->webEngine.loadContent("<html>"
                + " <script>function initialize() {"
                + " var nameVar = \"This is a JS var\"; " 
                + " app.callJavascript(nameVar);"
                + "} </script>"
                + "    <body onLoad=\"initialize()\">Hi, this is a test!</body>"
                + "</html>"));

        VBox vbox = new VBox(10,button,webView);
        Scene scene = new Scene(vbox,400,300);

        stage.setScene(scene);
        stage.show();

    }

    public class JavaApplication {

        public void callJavascript(String msg){
            System.out.println("JS>> "+msg);
        }
    }

    public static void main(String[] args) {
        launch(args);
    }

}

The content is not loaded until the button is clicked, but we've already created the JavaScript object on the browser.

Before clicking the button, there's nothing on the output console. But if we click the button... this is the output:

state: scheduled
state: running
JS>> This is a JS var
state: succeeded

As we can see, the Java object is effectively passed to the script before the latter is executed, and app.callJavascript is successfully called while the content is being loaded.

Note that for the common purpose of accessing the loaded DOM, the usual approach of calling executeScript after State.SUCCEEDED is still the recommended way.

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