Skip to content

How to Listen to Vaadin component events in a JavaFX WebView?

I have created a form with Vaadin Flow (Vaadin version 21) with a save button. This form is then shown in a JavaFX WebView (Version 17.0.1) and now I want to listen to events in the form like save button from JavaFX, so I can update JavaFX parts of the application. I have seen examples like:

How to retrieve components from HTML webview in JavaFX

But they don’t work since doc.getElementById("xxx") does not work at all and returns null. If I use the xpath method described there, I do get the button element, but then the adding the listener by calling the

((EventTarget) button).addEventListener("click", e -> doSomeAction(), false);

does not help. When I click the button the Vaadin listener works but the “javafx” listener does not get the event.

So my question is if there is a known solution for this Use Case?


You can invoke Java methods from JavaScript with upcalls. It works by assigning a JavaScript object to a Java one:

JSObject jso = (JSObject)webEngine.executeScript("window");

jso.setMember("java", new JavaObj());

Full example:

public class JavaObj {
  public void myMethod() {
webEngine.setJavaScriptEnabled(true); // Obviously...

webEngine.getLoadWorker().stateProperty().addListener((observable, oldState, newState) -> {
  if(newState == Worker.State.SUCCEEDED) {
    JSObject jso = (JSObject)webEngine.executeScript("window");

    jso.setMember("java", new JavaObj());
((EventTarget) button).addEventListener("click", e -> UI.getCurrent().getPage().executeJs("java.myMethod()"), false);

More about upcalls here.