问题
I'm wondering about this code snippet I'm using:
WebView webView = new WebView();
JSObject jsobj;
webEngine = webView.getEngine();
try {
webEngine.load(getClass().getResource("index.html").toExternalForm());
} catch (Exception e) {
e.printStackTrace();
}
try {
jsobj = (JSObject) webEngine.executeScript("window");
jsobj.setMember("java", new DataModel());
} catch (Exception e) {
e.printStackTrace()
}
This line webEngine.load(getClass().getResource("index.html").toExternalForm());
loads my index.html
into the WebView
. Since it is a single page application, that's all I need and there are no more questions about it.
Now to get back to the question in the title:
Does this line: jsobj = (JSObject) webEngine.executeScript("window");
set the JSObject
reference to the "window object" as it's defined by w3school?
Meaning that jsobj
is now equal to the window object, that represents the open window in the browser?
If so: Is this likely to be the reason why my application won't work if I use "reload page" over the context menu in the WebView
, since it would generate a new window object
?
Bonus question: In my JavaScript I can acces the model using java.methodName();
is "java" here an identifier or how would I call it? It's not exactly an instance, so I wouldn't call it like this.
Edit:
This is my Java class:
public class DataModel{
public void alert(String msg) {
System.out.println(msg);
}
}
From my JavaScript, which is embedded in index.html
I can call java.alert("hello world");
to print hello world
. Since I'm passing the model reference to the window object
every function in my JavaScript has access to the DataModel.class
. From the JavaScript point of view: Is "java." an identifier, reference, instance, ...?
回答1:
According to this site, webEngine.executeScript("window")
would in fact return the JavaScript Window object. There's also a whole bunch of other code snippet goodies to look!
java
in this case is a handler that can be used by your JavaScript, within the Window object. So your JavaScript, when referencing java
can expect to access the DataModel
object.
Also, you normally want to refresh your page with location.reload()
in JavaScript.
If you're looking to save state between reloads, you'll want to capture the current HTML and then use the WebView's loadContent functionality when the reload is complete. You could also get the WebView's document so you can directly modify nodes at any level.
来源:https://stackoverflow.com/questions/36599484/does-javafx8-webengines-executescriptwindow-method-refer-to-the-javascript