4

This is how I load my page and I would like to modify it while it's in the browser

    WebView browser = new WebView();
    WebEngine engine = browser.getEngine();
    String cwd = System.getProperty("user.dir");
    String name = "\\src\\web\\index.html";
    engine.loadContent(getPATHtoHTML(cwd + name));
Gilbert Gabriel
  • 422
  • 2
  • 8
  • 23
  • 1
    You can refresh the page using the same method with new content: `engine.loadContent("new Content...")`; To edit HTML you have to use `javafx.scene.web.HTMLEditor`. – prasad_ Oct 24 '18 at 02:21

1 Answers1

5

The DOM document is available and can be modified. This updates the content of the WebView. The following example simply appends some text to the body, but more complex manipulations are possible:

@Override
public void start(Stage stage) {
    WebView webView = new WebView();
    WebEngine engine = webView.getEngine();
    engine.loadContent("<html>"
            + "<body></body>"
            + "</html>");
    TextField textField = new TextField();
    Button button = new Button("add");
    button.setOnAction(evt -> {
        String text = textField.getText();
        Document doc = engine.getDocument();
        Element element = (Element) doc.getElementsByTagName("body").item(0);
        element.appendChild(doc.createTextNode(text));
    });

    Scene scene = new Scene(new VBox(webView, textField, button));

    stage.setScene(scene);
    stage.show();
}

If you also want to modify the file, you could also output the result to a file:

DOMSource domSource = new DOMSource(engine.getDocument());
StreamResult result = new StreamResult(outputFile);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer transformer = tf.newTransformer();
transformer.setOutputProperty(OutputKeys.METHOD, "html");
transformer.transform(domSource, result);
fabian
  • 80,457
  • 12
  • 86
  • 114