0

Currently I am opening a HTML page in webview. Code is as follows:

    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();

I want to display a value in a HTML page. Can anybody suggest me how I can pass a value from above Java code while loading the HTML page.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
Manish
  • 1,274
  • 3
  • 22
  • 59
  • Does this help you?https://stackoverflow.com/questions/14187963/passing-parameters-javafx-fxml – Aalexander Dec 18 '20 at 07:37
  • @Alex I don't think that's related. That Q&A is about FXML and how to pass information between various controller instances. The OP has a `WebView` and is looking to manipulate the web page from Java. – Slaw Dec 18 '20 at 07:55
  • @Manish Look into [`WebEngine#executeScript(String)`](https://openjfx.io/javadoc/15/javafx.web/javafx/scene/web/WebEngine.html#executeScript(java.lang.String)). – Slaw Dec 18 '20 at 07:57
  • @Alex I just want to inject a value which I can print in web page. – Manish Dec 18 '20 at 08:03

1 Answers1

1

You can use WebEngine#executeScript to set any javascript objects or values on the webpage. But you would still need to write custom javascript that reads that value and displays it inside the DOM. Something along this

engine.executeScript("document.getElementByid('myDiv').innerHTML = '" + myValue + "'");

A different way if you have full control over the HTML is to parse the HTML with String.replace and replace a placeholder inside your HTML with the value you want to have.

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

Marcel
  • 1,606
  • 16
  • 29