根据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 + "]");且文件不存在或不支持桌面,则除了消息侦听器之外,什么也不会发生:

javascript - JavaFX调用JavaScript以执行WebView中的Java功能不起作用-LMLPHP

因此,我已经将myFile更新为PC上的new File("C:\\Users\\dzikoysk\\Desktop\\panda.txt");,现在一切正常:

javascript - JavaFX调用JavaScript以执行WebView中的Java功能不起作用-LMLPHP

无论如何,在您的代码</html>标记中丢失了。在某些较旧的WebEngine版本中,它也可能会引起问题,请注意诸如此类的细节-引擎存在许多错误,但未实现功能。

09-30 10:26