如何在 javaFx Webview html 页面中传递值
How to pass a value in javaFx Webview html page
目前我正在 webview 中打开一个 HTML 页面。代码如下:
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
URL resource = getClass().getClassLoader().getResource("test.htm");
webEngine.load( resource.toString() );
Scene scene = new Scene(webView,width,height);
primaryStage.setScene(scene);
primaryStage.setAlwaysOnTop(true);
primaryStage.setFullScreen(true);
primaryStage.setFullScreenExitHint("");
Platform.setImplicitExit(false);
System.out.println("Starting the webview....");
primaryStage.show();
我想在 HTML 页面中显示一个值。谁能建议我如何在加载 HTML 页面时从上面的 Java 代码传递一个值。
您可以使用 WebEngine#executeScript 在网页上设置任何 javascript 对象或值。但是您仍然需要编写自定义 javascript 来读取该值并将其显示在 DOM 中。
沿着这个
engine.executeScript("document.getElementByid('myDiv').innerHTML = '" + myValue + "'");
如果您完全控制 HTML,另一种方法是用 String.replace 解析 HTML,并用您的值替换 HTML 中的占位符想拥有
String htmlContent = .../* read HTML file as string */;
webEngine.loadContent(htmlContent.replace("{myVar}", myValue), "text/html");
这可以通过各种框架进行扩展,例如 Apache Commons StringSubstututor
https://commons.apache.org/proper/commons-text/apidocs/org/apache/commons/text/StringSubstitutor.html
目前我正在 webview 中打开一个 HTML 页面。代码如下:
WebView webView = new WebView();
WebEngine webEngine = webView.getEngine();
URL resource = getClass().getClassLoader().getResource("test.htm");
webEngine.load( resource.toString() );
Scene scene = new Scene(webView,width,height);
primaryStage.setScene(scene);
primaryStage.setAlwaysOnTop(true);
primaryStage.setFullScreen(true);
primaryStage.setFullScreenExitHint("");
Platform.setImplicitExit(false);
System.out.println("Starting the webview....");
primaryStage.show();
我想在 HTML 页面中显示一个值。谁能建议我如何在加载 HTML 页面时从上面的 Java 代码传递一个值。
您可以使用 WebEngine#executeScript 在网页上设置任何 javascript 对象或值。但是您仍然需要编写自定义 javascript 来读取该值并将其显示在 DOM 中。 沿着这个
engine.executeScript("document.getElementByid('myDiv').innerHTML = '" + myValue + "'");
如果您完全控制 HTML,另一种方法是用 String.replace 解析 HTML,并用您的值替换 HTML 中的占位符想拥有
String htmlContent = .../* read HTML file as string */;
webEngine.loadContent(htmlContent.replace("{myVar}", myValue), "text/html");
这可以通过各种框架进行扩展,例如 Apache Commons StringSubstututor https://commons.apache.org/proper/commons-text/apidocs/org/apache/commons/text/StringSubstitutor.html