JavaScript上传到JavaFX FXML

时间:2013-11-28 04:15:29

标签: javafx-2 fxml

我在SampleController.java中使用FXML WebView来显示Web内容。现在的问题是如何在html文件中从javascript调用java函数,或者当点击webview网页时应该执行javascript并调用Bridge()中的代码来执行。 JavaFX WebView有一些示例,但找不到FXML WebView的任何示例。

    public class SampleController implements Initializable {

    @FXML Button write, read;
    @FXML ToolBar toolbar;
    @FXML WebView webview;
    WebEngine webEngine;
    JSObject window;

    @FXML
    private void setText(MouseEvent e){
        webEngine.executeScript("writeText()");
    }
    @FXML
    private void getText(MouseEvent e){
        String str = (String) webEngine.executeScript("readText()");
        System.out.println(str);
    }

    @Override
    public void initialize(URL url, ResourceBundle rb) {
        webEngine = webview.getEngine();
        webEngine.load(getClass().getResource("test.html").toString());

     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) {
            window = (JSObject) webEngine.executeScript("window");
            window.setMember("app", new Bridge());

        }
    }
});     
    }    
}

   // code for javaScript call

    public class Bridge {   
    public void exit() {
        Platform.exit();
    }

    public void display(String str){
        System.out.println(str);
    }
}

// Here is HTML with with javaScript
    <!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script>
            function writeText(){
                document.getElementById("div1").innerHTML = "New text!";
            }
            function readText(){
                var str = document.getElementById("div2").innerHTML;
                return str;
            }

        </script>
    </head>
    <body>
        <div id="div1">Urdu Books<img src="book.png" alt="book"></div>
        <div id="div2">Here is a text for you!</div>
        <div id="div3"></div>
        <p>Click <a href="#" onclick="java.exit()">here </a>to exit the application
        <p>Click <a href="#" onclick="java.display('This is value')"> Display </a> a value
    </body>
</html>

1 个答案:

答案 0 :(得分:0)

执行此操作window.setMember("app", new Bridge());您基本上告诉JS引擎将新的Bridge对象设置为窗口对象的app成员。

现在,在您的javascript代码中,您可以调用您的桥接方法,例如window.app.exit()或更简单app.exit(),因为window是全局对象。