簡體   English   中英

Javafx調用javascript來執行webview中的java函數不起作用

[英]Javafx calling javascript to excute java function in webview not working

根據 JavaFX 文檔,您可以使用 JavaScript 函數執行 Java 代碼。 下面是我的代碼:

engine = webview.getEngine();
engine.load("http://localhost:8080/testing.php");
openExcel callback = new openExcel();
JSObject window = (JSObject) engine.executeScript("window");
window.setMember("app", callback);

以上是在 initialize 方法中,然后對於另一個類(openExcel),我有這樣的事情:

public class openExcel {

    public void open() {
        if (Desktop.isDesktopSupported()) {
            try {
                File myFile = new File("C:\\Users\\HP\\Desktop\\v3.01.xlsm");
                Desktop.getDesktop().open(myFile);
            } catch(IOException ex) {
                System.out.println("Your application is not support");
            }
        }
    }

}

HTML文件:

 <html> <head> <script> function openExcel() { app.open(); alert('hello world'); } </script> </head> <body> <button onclick="openExcel()">Open excel</button> </body>

我面臨的問題是,當我單擊“openExcel”按鈕時,它什么也不做? 我需要幫助!

我試圖重現您的問題,但您的網橋似乎在拋出錯誤/消息,而您看不到輸出。 我使用您的代碼創建了一個帶有 JavaScript 消息偵聽器的簡單測試:

public class WebEngineTest extends Application {

    @Override
    public void start(Stage primaryStage) {
        WebConsoleListener.setDefaultListener((webView, message, lineNumber, sourceId) -> {
            System.out.println(message + "[at " + lineNumber + "]");
        });

        WebView webView = new WebView();
        WebEngine engine = webView.getEngine();
        engine.loadContent("<html><head><script>function openExcel() { app.open(); alert('hello world'); } </script></head><body><button onclick=\"openExcel()\">Open excel</button></body></html>");

        JSObject window = (JSObject) engine.executeScript("window");
        window.setMember("app", new OpenExcel());

        Scene scene = new Scene(webView, 300, 150);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    public class OpenExcel {

        public void open() {
            if (!Desktop.isDesktopSupported()) {
                throw new RuntimeException("Desktop is not supported");
            }

            try {
                File myFile = new File("C:\\Users\\HP\\Desktop\\v3.01.xlsm");
                // File myFile = new File("C:\\Users\\dzikoysk\\Desktop\\panda.txt");
                Desktop.getDesktop().open(myFile);
            } catch(IOException ex) {
                System.out.println("Your application is not support");
            }
        }

    }

}

如果我刪除System.out.println(message + "[at " + lineNumber + "]"); 並且文件不存在或桌面不受支持,那么除了消息偵聽器之外什么也沒有發生

控制台異常預覽

所以我已經將myFile更新為new File("C:\\\\Users\\\\dzikoysk\\\\Desktop\\\\panda.txt"); 存在於我的 PC 上,現在一切正常:

應用預覽

無論如何,在您的代碼中缺少</html>標記。 在一些舊版本的 WebEngine 中,它也可能導致問題,請注意此類細節 - 引擎有很多錯誤且未實現的功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM