Search code examples
javascriptmigrationvaadin

Migrate Page.getCurrent().getJavaScript().addFunction to Vaadin Flow


I have the following Vaadin 8 code:

Page.getCurrent().getJavaScript().addFunction("getDocument", args -> {
    ...
    //java rest call
    ...
});

getDocument is called in javascript code.

window.documentSign = function(signerUrl,procedure) {
    ....
    getDocument(signerRequest.responseText,procedure,messageId);
    ....
}

How can I migrate this piece of code to Vaadin Flow 14?

Thank you in advance.


Solution

  • addFunction in Vaadin 8 provides a way for JavaScript to send data back to the server.

    I guess this isn't a one-time case that can be handled by returning a value (or a Promise) through executeJs. I also guess this case isn't related to a component class where you can define a @ClientCallable method in Java and access that from JS through element.$server.

    What remains is firing a custom DOM event on the <body> element and listening for that event on the UI element through Java.

    Firing a event from JS:

    document.body.dispatchEvent(new CustomEvent('event-name', { detail: 'String from JS' }));
    

    Listening for the event in Java:

    ui.getElement().addEventListener("event-name", event -> {
      System.out.println(event.getEventData().getString("event.detail"));
    }).addEventData("event.detail");