【问题标题】:How to pass a value in javaFx Webview html page如何在 javaFx Webview html 页面中传递值
【发布时间】:2020-12-18 07:31:55
【问题描述】:

目前我正在 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 代码中传递一个值。

【问题讨论】:

标签: java html javafx webview


【解决方案1】:

您可以使用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

【讨论】:

  • 试过了,但 html 页面仍然显示 {myVar} 它没有被 myValue 取代
  • 你需要将字符串 {myVar} 放在你的 HTML 文件中:D
  • 是的,这是我的 html 页面中的“编号:{myVar}
  • ok resource.toString 有文件路径而不是内容。让我看看。
  • 需要将html文件加载为字符串,然后使用.loadContent()
猜你喜欢
  • 1970-01-01
  • 2014-11-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-24
  • 1970-01-01
  • 1970-01-01
  • 2013-04-13
相关资源
最近更新 更多