来自Javascript的WebView回调

时间:2013-01-26 21:50:41

标签: webview javafx javafx-2

我尝试基于last example in WebEngine's javadoc从JavaScript调用Java )创建一个从Javascript到Java的回调的简单示例。但是,当我单击WebView中的链接时,不会调用Java方法,页面也会消失。

public class TestOnClick extends Application {

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

            Scene scene = new Scene(webView);

            stage.setScene(scene);
            stage.setWidth(1200);
            stage.setHeight(600);
            stage.show();

            String webPage = "<html>\n"
                    + "    <body>\n"
                    + "        <a href=\"\" onclick=\"app.onClick()\">Click here</a>\n"
                    + "    </body>\n"
                    + "</html>";

            System.out.println(webPage);

            webView.getEngine().loadContent(webPage);

            JSObject window = (JSObject) webEngine.executeScript("window");
            window.setMember("app", new JavaApp());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

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

    public static class JavaApp {

        public void onClick() {
            System.out.println("Clicked");
        }
    }
}

注意:在使用webView.getEngine().getLoadWorker().exceptionProperty().addListener(...)监视加载工作程序时,我看不到WebView中抛出任何异常。

1 个答案:

答案 0 :(得分:6)

您正在尝试在创建之前访问webview DOM模型。

将您的JavaApp相关代码包装到页面加载侦听器以实现您的目标:

webEngine.getLoadWorker().stateProperty().addListener(new ChangeListener<Worker.State>() {
    @Override
    public void changed(ObservableValue<? extends State> ov, State t, State t1) {
        if (t1 == Worker.State.SUCCEEDED) {
            JSObject window = (JSObject) webEngine.executeScript("window");
            window.setMember("app", new JavaApp());
        }
    }
});