根据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);
上面是在初始化方法中,然后对于其他类(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");
我的电脑上存在该文件,现在一切正常:
无论如何,在你的代码中 </html>
标签丢失。在某些较旧版本的 WebEngine 中,它也可能会导致问题,请小心此类细节 - 该引擎有很多错误并且未实现功能。
关于javascript - Javafx 调用 javascript 在 webview 中执行 java 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48955193/