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.

Java

  1. public static void logElementSize(String name,
  2. Element element) {
  3. Page page = UI.getCurrent().getPage();
  4. page.executeJs(
  5. "console.log($0 + ' size:', "
  6. + "$1.offsetWidth, $1.offsetHeight)",
  7. name, element);
  8. }

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)

Note
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.