Skip to content Skip to sidebar Skip to footer

Getting Html Input Value In Javafx Webview?

Is it possible to get the value of a HTML input inside a WebView in JavaFX? If so, how would I use an event so the value updates automatically? Example App: package webviewinput

Solution 1:

TL;DR: Yes, it's possible, but it requires a bit of a hacky workaround.

First of all, I'm going to move the HTML to it's own separate file, to make editing easier, and just create cleaner code in general.

editor.html

<!DOCTYPE html><html><head><metacharset="UTF-8"><title>Example Live-view</title><metaname="viewport"content="width=device-width, initial-scale=1.0"></head><body><textareaplaceholder="Typing 'exit' will kill the program."></textarea><script>document.querySelector("textarea").addEventListener("keyup", function(){
                
                window.status = this.value;
            });
        </script></body></html>

The basic structure is really simple, but what about the <script> element? What does it do?

document.querySelector("textarea").addEventListener("keyup", function(){
     window.status = this.value;
});

AFAIK, it isn't possible to straight out get the value of an input in JavaFX, so you have to make a workaround. In this case, I'm setting the window status with the textarea value, whenever there is a keyup event in the textarea.

Now we need to set up the webview in our JavaFX.

WebviewInputValue.java

package webviewinputvalue;

publicclassWebviewInputValueextendsApplication {
    
    private WebView InitWebview(){
        
        //Create browserWebViewbrowser=newWebView();
        WebEnginerender= browser.getEngine();
        
        //Load simple HTMLStringeditor= WebviewInputValue.class.getResource("editor.html").toExternalForm();
        render.load(editor);
        
        //Listen for state change
        render.getLoadWorker().stateProperty().addListener((ov, o, n) -> {
            if (Worker.State.SUCCEEDED == n) {
                render.setOnStatusChanged(webEvent -> {
                        
                    //Call value change
                    onValueChange(webEvent.getData());
                });
            }
        });
        
        return browser;
    }
    
    //called when value changesprivatevoidonValueChange(String data){
        
        //Print out data
        System.out.println(data);
        
        //If the data is equal to "exit", close the programif("exit".equals(data)){
            
            //Print goodbye message
            System.out.println("Received exit command! Goodbye :D");
            
            //Exit
            System.exit(0);
        }
    }
    
    @Overridepublicvoidstart(Stage primaryStage) {
        
        //Create browserWebViewbrowser= InitWebview();
                
        StackPaneroot=newStackPane();
        root.getChildren().add(browser);

        Scenescene=newScene(root, 300, 250);

        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */publicstaticvoidmain(String[] args) {
        launch(args);
    }
}

Again, very simple code. Let's dig into it:

private WebView InitWebview(){
    
    //Create browserWebViewbrowser=newWebView();
    WebEnginerender= browser.getEngine();
    
    //Load simple HTMLStringeditor= WebviewInputValue.class.getResource("editor.html").toExternalForm();
    render.load(editor);
    
    //Listen for state change
    render.getLoadWorker().stateProperty().addListener((ov, o, n) -> {
        if (Worker.State.SUCCEEDED == n) {
            render.setOnStatusChanged(webEvent -> {
                    
                //Call value change
                onValueChange(webEvent.getData());
            });
        }
    });
    
    return browser;
}

First we create the webview and engine, then load the editor.html file into the webview. Next, we fetch the loadWorker, which is what controls the window.status object we are writing to with the JS. We then get the state property, and add an listener. If the listener is added successfully, then listen for a change event.

When the change event, we'll call our onValueChange method:

//called when value changesprivatevoidonValueChange(String data){
    
    //Print out data
    System.out.println(data);
    
    //If the data is equal to "exit", close the programif("exit".equals(data)){
        
        //Print goodbye message
        System.out.println("Received exit command! Goodbye :D");
        
        //Exit
        System.exit(0);
    }
}

This is extremely simple. onValueChange is called with the textarea value as the data parameter. In this case, I'm printing it to the console. If I type exit into the textarea, then it will print a goodbye message and close the application.

finished project

And that's it! If you run the above code, then it'll log the textarea value into the console real-time!

Note:

Your project structure should look this, with editor in the same dir as the java file, if you want this code to work straight off:

structure

Also, I'm obviously missing the imports in the java code.

Solution 2:

3 years later, but I hope it will help someone. I found how to get text from TextArea without changing html page

Runnablecheck= () -> {            
    WebEngineengine= webView.getEngine();
    if (engine != null) {
        Documentdocument= engine.getDocument();
        if (document != null) {
            Elementelement= document.getElementById("samlResponse");
            if (element instanceof HTMLTextAreaElement) {
                HTMLTextAreaElementtextArea= (HTMLTextAreaElement) element;
                Stringtext= textArea.getValue();
                if (text != null && !text.isEmpty()) {
                    System.out.println("BINGO:\n" + text);
                    System.exit(0);
                }
            }
        }
    }
};

newThread(() -> {
    while (true) {
        Platform.runLater(check);

        try {
            Thread.sleep(1_000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}).start();

Post a Comment for "Getting Html Input Value In Javafx Webview?"