Documentation versions (currently viewingVaadin 14)

You are viewing documentation for an older Vaadin version. View latest documentation

Executing JavaScript in the Browser

You can use server-side Java to execute simple JavaScript snippets in the browser. You can also pass parameters to the executed script as variables named $0, $1 and so on. Vaadin automatically serializes and escapes the parameter values.

Example: Executing JavaScript in the browser and passing parameters.

public static void logElementSize(String name,
        Element element) {
    Page page = UI.getCurrent().getPage();

            "console.log($0 + ' size:', "
            + "$1.offsetWidth, $1.offsetHeight)",
            name, element);

The supported parameter types are String, Boolean, Integer, Double, JsonValue and Element.

The script is executed after the DOM tree has been updated based on server-side changes. The parameter value is null for a parameter of type Element that is not attached after the update (according to the server-side component structure)

JavaScript evaluation scope
The page.executeJs() method runs the JavaScript in the scope of the page (i.e. the window object). Component and element scoped access is described in Element API, Remote Procedure Calls.
The script is executed asynchronously, so you cannot directly pass values back to the server. Instead, the returned PendingJavaScriptResult instance can be used to add a callback that is run when the result is available.

Vaadin provides a ready-made solution (without custom JavaScript execution) to listen to browser window-resize events for the from the server side. See Browser Window Resize Events for more.