Accessing the Browser Page

Beside the Element API to manipulate the DOM in the browser, you can also interact with the browser page by adding stylesheets, executing JavaScript, receiving browser resize events, and so forth.

These features are available through the Page object. You can access the page of the current request with UI.getCurrent().getPage().

Getting the Window Location URL

Use the Page.fetchCurrentURL method to fetch the current URL from the browser.

For example:

UI.getCurrent().getPage().fetchCurrentURL(currentUrl -> {
    // This is your own method that you may do something with the url.
    // Please note that this method runs asynchronously

Getting the Extended Client-Side Details

Use retrieveExtendedClientDetails() in the current Page object to retrieve extended client-side details. The method accepts a callback that, when called after client response, gets an ExtendedClientDetails object with various client-side data.

For example, the following can be used to get the screen width:

UI.getCurrent().getPage().retrieveExtendedClientDetails(details -> {
    // This is your own method that you may do something with the screen width.
    // Please note that this method runs asynchronously

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.

You can execute JavaScript in the browser and pass parameters as follows:

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

Notice that the script is executed asynchronously, so you cannot directly pass values back to the server. Instead, you can use the returned PendingJavaScriptResult instance to add a callback that is called when the result is available.

Browser Window Resize Events

The Page class allows you to register a listener for events that affect the web page and the browser window in which the Vaadin UI resides. The Page instance corresponding to a given UI is accessed by the getPage() method of the UI.

You can get the browser window size by adding a resize listener as follows:

Page page = UI.getCurrent().getPage();
        event ->"Window width="
                + event.getWidth()
                + ", height=" + event.getHeight()));