Manish
Manish

Reputation: 1517

How to pass a value in javaFx Webview html page

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.

Upvotes: 0

Views: 477

Answers (1)

Marcel
Marcel

Reputation: 1768

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

Upvotes: 1

Related Questions