javahtmljavafxwebviewjavafx-webengine

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


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

Solution

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