How to edit HTML page (in a webview) from Javafx without reloading the page?
Asked Answered
C

1

5

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));
Cinda answered 24/10, 2018 at 2:1 Comment(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.Arsenic
M
6

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);
Margertmargery answered 24/10, 2018 at 9:28 Comment(1)
I had to trick your code a bit to work with mine but it works perfectly thanks!Cinda

© 2022 - 2024 — McMap. All rights reserved.