I am working on JavaFX 2.2, I am using webview to integrate html code in the JavaFX scene and was able to load the html correctly. I was following this link and was trying to pass some objects from javascript to webview/controller but I am getting null values at java side.
I have saved a interface object in JSObject like below
webEngine.getLoadWorker().stateProperty().addListener(
new ChangeListener<State>() {
@Override
public void changed(ObservableValue<? extends State> ov,
State oldState, State newState) {
if (newState == State.SUCCEEDED) {
JSObject win = (JSObject) webEngine.executeScript("window");
win.setMember("app", new JavaApp());
}
}
}
);
I have created a class
public class JavaApp {
public void exit() {
Platform.exit();
}
public void print(Date date) {
System.out.println("Parm:"+date);
}
public Date getValue() {
return new Date();
}
}
My html is
<html lang="en">
<head>
<script type="text/javascript">
function callJava(){
app.print(new Date());
var val = app.getValue();
app.print(val);
}
</script>
</head>
<body>
<p>Help</p>
<p><a href="about:blank" onclick="callJava();">Exit the Application</a></p>
</body>
</html>
In above code I always get null values printed in JavaApp.print() method. Interesting point is when I changed the parameter from Date to String in print method and pass the string from javascript, I get correct values.
How I can transfer objects in this case especially Date object. Any help is much appritiated
Java does not know the Date
class of javascript.
2.3 Data Type Conversions
You can pass a javascript object to Java, ( you have to wrap it in a JSObject
) but you can get directly only parameters like these:
My solution for you:
public class JavaApp {
public void exit() {
Platform.exit();
}
//public void print(Date date) {
// System.out.println("Parm:"+date);
// }
public void print(long date) {
System.out.println("Parm:"+new Date(date));
}
public Date getValue() {
return new Date();
}
}
<html lang="en">
<head>
<script type="text/javascript">
function callJava(){
// app.print(new Date());
app.print(new Date().getTime());
var val = app.getValue();
app.print(val);
}
</script>
</head>
<body>
<p>Help</p>
<p><a href="about:blank" onclick="callJava();">Exit the Application</a></p>
</body>
</html>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With