Reputation: 33
According to the JavaFX docs, you can execute Java code with JavaScript function. Below is my code:
engine = webview.getEngine();
engine.load("http://localhost:8080/testing.php");
openExcel callback = new openExcel();
JSObject window = (JSObject) engine.executeScript("window");
window.setMember("app", callback);
The above is in the initialize method, then for the other class(openExcel) I've got something like this:
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 file:
<html>
<head>
<script>
function openExcel() {
app.open();
alert('hello world');
}
</script>
</head>
<body>
<button onclick="openExcel()">Open excel</button>
</body>
The problem that I'm facing is that when I click in the button "openExcel" it does nothing? I need help!
Upvotes: 2
Views: 2111
Reputation: 1578
I've tried to reproduce your problem and it seems like your bridge is throwing error/message and you can't see the output. I used your code to create a simple test with JavaScript message listener:
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");
}
}
}
}
If I remove System.out.println(message + "[at " + lineNumber + "]");
and file does not exist or desktop is not supported then nothing happens but with the message listener:
So I've updated myFile
to new File("C:\\Users\\dzikoysk\\Desktop\\panda.txt");
that exists on my PC and now everything works:
Anyway, in your code </html>
tag is missing. In some older versions of WebEngine it can also cause problems, be careful with details like that - the engine has a lot of bugs and not implemented features.
Upvotes: 2