Thursday, January 24, 2019

How to call a Java method from a JavaScript function in the browser

In this video I demonstrate how to call a Java method that runs in the server from a JavaScript function running in the web browser:

In short, you need a Java web application with the Vaadin dependencies (you can quickly create one here), a script file in the webapp/frontend/ directory, and a Java class with a method annotated with @ClientCallable that sends an Element to the JavaScript function. The JavaScript function can use the $server object in the Element instance to call the annotated Java method.

Here's the code:

public class MainView extends Div {
    public MainView() {
                "someJavaScriptFunction($0)", getElement());


    public someJavaMethod(String message) {


function someJavaScriptFunction(element) {
    element.$server.someJavaMethod("Hello server!");

You can read the full step-by-step tutorial here.