我在JavaFx应用程序中有一个控制器,该控制器可通过WebView加载Web内容。我想访问JavaScript中声明的变量。所以我有一个问题,因为我是JS的新手。如何在JavaScript中声明变量以通过JSObject类中的getMember()方法访问它?控制器如下所示:
public class MainController implements Initializable {
@FXML
public WebView webView;
@FXML
private ListView<String> listOfInterest;
//Variables to load map page
private WebEngine webEngine;
/*MenuBar methods*/
@Function
public void closeApplication() {
Optional<ButtonType> confirmationResult = Dialog.closeApplicationConfirmation();
if (confirmationResult.get() == ButtonType.OK) {
Platform.exit();
}
}
@Function
public void openReport() {
try {
AnchorPane anchorPane = UtilsConnection.getFXML("/FXML/ReportWindow.fxml");
Scene scene = new Scene(anchorPane);
Stage stage = new Stage();
stage.setScene(scene);
stage.setTitle(UtilsConnection.getBundles().getString("title.rep"));
stage.getIcons().add(new Image("images/logo.png"));
stage.setResizable(false);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
}
@Function
public void openAbout() {
Dialog.informationAlert(UtilsConnection.getBundles().getString("textAbout.app")
,UtilsConnection.getBundles().getString("headerAbout.app")
,UtilsConnection.getBundles().getString("aboutTitle.app"));
}
@Override
public void initialize(URL location, ResourceBundle resources) {
//Loading map through HTML file
try {
URL url = this.getClass().getResource("/html/mainMap.html");
webEngine = webView.getEngine();
webEngine.setJavaScriptEnabled(true);
webEngine.getLoadWorker().stateProperty().addListener(((observable, oldValue, newState) -> {
if(newState == Worker.State.SUCCEEDED){
JSObject fromJS = (JSObject) webEngine.getDocument();
String value = (String) fromJS.getMember("toJava");
System.out.println(value);
}
}));
webEngine.load(url.toString());
} catch (Exception e) {
Dialog.error(UtilsConnection.getBundles().getString("error.map"));
}