繁体   English   中英

如何在 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"); 

This can get extended with various frameworks such as Apache Commons StringSubstututor https://commons.apache.org/proper/commons-text/apidocs/org/apache/commons/text/StringSubstitutor.html

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM