Docs

Calling JavaScript from the Server

Call JavaScript functions from the server.

The Element API contains methods for executing JavaScript in the browser from the server side.

Declare the JavaScript in a Java interface and call it through Element.executeJs(Class). The build collects the declared JavaScript into the frontend bundle, and the client runs it from there. Nothing is compiled from a string in the browser, so the call works under a strict content security policy. callJsFunction() works under such a policy as well, since it calls a function that already exists on the element — unless an argument is a JsFunction built with JsFunction.of().

The other methods described on this page — executeJs(String, Object…​), JsFunction.of(), and addJsInitializer(String, Object…​) — send the JavaScript to the browser as a string that’s compiled there. Avoid them for anything a declaration can express. addJsInitializer(JsFunction) works under such a policy as well, when the function it’s given is declared as a snippet rather than built with JsFunction.of().

Declaring JavaScript in Java

An interface annotated with @JsDefinition declares JavaScript that the build collects into the bundle. It also extends one of three marker interfaces, which decides what its methods declare: JsInvokers, covered in this section, for JavaScript that runs on an element when a method is called; JsModuleInvokers for JavaScript that runs on what a JavaScript module exports, called through Page.executeModuleJs(Class); or JsSnippets for JavaScript that’s only passed on as a function (see Declaring Snippets). An interface extends only one of them.

Call the declared JavaScript of a JsInvokers interface through Element.executeJs(Class), which hands out an implementation of the interface; calling a method of it schedules the JavaScript that the method declares.

Each method of the interface is usually annotated with @JsExpression, whose value is the JavaScript expression to run. The arguments of the call are available inside the expression as $0, $1, and so on, and the element the implementation was obtained from is this. Without the annotation, the method calls the JavaScript function of the same name on the element, as shown below.

The arguments must be a type supported by the communication mechanism. The supported types are String, Boolean, Integer, Double, JsonNode, Element, Component, and JsFunction.

Passing a JsFunction built with JsFunction.of() is allowed, but it brings the browser-side compilation back, since the client builds such a function from its body string. Declare a method for the JavaScript instead, or pass a function declared as a snippet.

The last parameter of a method can be declared variadic, such as String…​, to accept a variable number of trailing arguments instead of a fixed one. The build turns it into a JavaScript rest parameter, so reference it the same way as any other parameter and spread it where the expression needs the individual values.

Example 1. Declaring and calling a variadic method
Source code
Java
@JsDefinition
public interface ClassNamesJs extends JsInvokers {

    @JsExpression("this.classList.add(...$0)")
    void add(String... classNames);
}
Source code
Java
public void highlight() {
    getElement().executeJs(ClassNamesJs.class)
            .add("selected", "highlighted");
}
Example 2. Declaring and calling JavaScript through a @JsDefinition interface
Source code
Java
@JsDefinition
public interface GreeterJs extends JsInvokers {

    @JsExpression("window.alert($0)")
    void showGreeting(String greeting);
}
Source code
Java
public void greet(String message) {
    getElement().executeJs(GreeterJs.class).showGreeting(message);
}

If a method has no @JsExpression, calling it calls the JavaScript function of the same name on the element and passes the arguments of the call to it. The last argument of a variadic method is passed as separate arguments, the same as in an explicit expression.

Example 3. Calling a JavaScript function of the element
Source code
Java
@JsDefinition
public interface PopoverJs extends JsInvokers {

    void showPopover();
}
Source code
Java
public void openPopover() {
    getElement().executeJs(PopoverJs.class).showPopover();
}

This only works for methods declared in an interface that extends JsInvokers. A method inherited from an interface that doesn’t extend it still needs @JsExpression.

Use a declared method when the name of the function is known when you write the code. Use callJsFunction() when the name is only known at runtime, or to call a function on a property of the element, such as $connector.method, without writing an @JsExpression.

A method returns void, PendingJavaScriptResult, or JavaScriptResult with a type argument, to retrieve a return value the same way an expression does (see Return Values). Declaring JavaScriptResult with a type argument hands the value to its handlers already converted to that type, with no type token needed at the call site.

Example 4. Declaring JavaScript that returns a value
Source code
Java
@JsDefinition
public interface OverflowJs extends JsInvokers {

    @JsExpression("return this.scrollWidth > this.clientWidth")
    PendingJavaScriptResult isContentClipped();
}
Source code
Java
public void updateTooltip() {
    getElement().executeJs(OverflowJs.class)
            .isContentClipped()
            .then(Boolean.class, this::setTooltipEnabled);
}

Nothing about the JavaScript is decided at the call site: the build generates one function per declared expression into the bundle, and the client runs that function after looking it up by an identifier of the JavaScript. The expression itself is never sent to the browser, and a production bundle carries the generated functions only — the Java names stay on the server. A method without @JsExpression is the exception: the JavaScript it runs calls the function of the same name, so that name is in the bundle.

A production build collects only the definitions it can reach from the entry points of the application, the same way it collects @JsModule. Definitions from Flow’s own jar are always collected. A definition that’s only used through reflection, or from code that no route or other entry point leads to, is left out of the bundle, and a call to it fails in the browser. To keep such a definition, name it with @Uses on a class that the build reaches. See Production Build for how @Uses works.

This requires the default bundle optimization of the production build: with optimizeBundle set to false, every definition found on the classpath is collected. Development mode also collects every definition.

Note
The interface is checked when executeJs(Class) hands out the implementation. It must extend JsInvokers and be annotated with @JsDefinition. Every method must return void, PendingJavaScriptResult, or JavaScriptResult with a type argument that’s known from the interface (see Typed Results); a method that returns a snippet type is refused with the method named. A method inherited from a parent interface that doesn’t extend JsInvokers must be annotated with @JsExpression, since only methods declared in a JsInvokers interface can call a JavaScript function of the element. A default or static method is refused, since it’s implemented in Java rather than declaring JavaScript to run in the browser.

When the JavaScript isn’t about a particular element, declare it the same way and run it through Page.executeJs(Class), which works with global browser APIs instead of with an element (see Accessing the Browser Page). There, every method needs @JsExpression, since there’s no element whose JavaScript function could be called.

Importing Module Exports

@JsDefinitionImport imports names from a JavaScript module, so the expressions of a definition can call what the module exports. The module doesn’t need to put anything on window:

Example 5. Importing a named export and calling it from an expression
Source code
Java
@JsDefinition
@JsDefinitionImport(from = "./highlight.js", exports = "highlight")
public interface HighlightJs extends JsInvokers {

    @JsExpression("highlight(this, $0)")
    void highlight(String term);
}

The attributes name what is imported, the same way the parts of a JavaScript import statement do: defaultExport() names the default export, namespace() imports the whole module under one name, and exports() lists named exports, each kept under its own name. @JsDefinitionImport(from = "./my.js", defaultExport = "a", namespace = "b", exports = {"c", "d"}) gives the expression what import a, { c, d }, * as b from "./my.js" would. The attributes are optional and can be combined, but at least one name has to be given; a module that’s only loaded for its side effects is declared with @JsModule instead. The exception is an interface that extends JsModuleInvokers, whose one import without names is the module that its JavaScript runs on as this.

The default export is reached through defaultExport(), or as default of the namespace(). A named export keeps its name and can’t be renamed, so when two modules export the same name, import one of them as a namespace instead.

from() is resolved the same way as JsModule.value(): a path starting with ./ names a file in the project’s frontend folder or in a jar’s META-INF/frontend, and any other path names an npm package or a file in one. When the build can’t find the file that a ./ path names, it fails, as it does for a missing @JsModule file, with an error that names the annotated interface, the methods that use the import, and the module. An npm package isn’t looked for in advance: when it isn’t installed, the frontend build fails on it.

The annotation can be repeated, and several annotations that name the same module load it as one module. The imports belong to the interface that declares them: a method inherited from another interface sees the imports of the interface that declares the method, not those of the interface it’s called through.

Example 6. Each method sees the imports of the interface that declares it
Source code
Java
@JsDefinitionImport(from = "./highlight.js", exports = "highlight")
public interface HighlightMethods extends JsInvokers { 1

    @JsExpression("highlight(this, $0)") 2
    void highlight(String term);
}

@JsDefinition
@JsDefinitionImport(from = "./scroll.js", exports = "scrollToMatch")
public interface SearchResultJs extends HighlightMethods {

    @JsExpression("scrollToMatch(this)") 3
    void scrollToMatch();
}
  1. Only extended, never passed to executeJs(Class), so it doesn’t need @JsDefinition.

  2. Sees highlight, also when called through SearchResultJs, but not scrollToMatch.

  3. Sees scrollToMatch, but not highlight.

The module is loaded the first time a method of the declaring interface is called, not when the application starts, so a module that only some views need doesn’t slow the others down; later calls reuse the loaded module. A @JsModule on the same interface is still loaded eagerly. Because the call waits for its modules, even ones already loaded, its JavaScript runs after the JavaScript of the calls that follow it in the same round trip, rather than in call order, and two calls that import different modules may run in either order. When a later call depends on what this one does, make it from the result of this one, for example by returning PendingJavaScriptResult and making the next call in its handler. Code that later calls rely on, such as the connector that a component sets up, is better called through an interface that extends JsModuleInvokers, whose modules are loaded with the view; it is called through Page.executeModuleJs(Class) and names its module with a @JsDefinitionImport that imports no names.

The imported names are given to the expression as parameters, so each one has to be a JavaScript identifier that isn’t a reserved word, such as default or this, and not $0, $1, …, which name the arguments of the call, or $executionContext, which Flow reserves. A name can be declared only once by the imports of an interface. Because the expression runs in a function of its own, arguments inside it holds the imported values rather than the arguments of the call; use $0, $1, … instead.

The annotation applies to an interface whose methods are called through a definition that extends JsInvokers or JsModuleInvokers: the definition itself or an interface it extends. The imports only reach the methods that the annotated interface declares itself, so an interface that declares no method of its own, such as a definition that only inherits its methods, is refused; annotate the interface that declares the methods instead. The annotation is also refused on a JsSnippets interface, since its functions aren’t asynchronous and can’t wait for a module to load, and on an interface annotated with @JsStringFallback, since a string expression can’t name anything from a module. On a class, the annotation stops the build with an error that names the class. An optimized production build checks only the classes that the application reaches, as it does for definitions.

Declaring Snippets

An interface annotated with @JsDefinition that extends JsSnippets instead of JsInvokers declares snippets: JavaScript that isn’t run when a method is called. Its methods return a snippet type — JsFunction, JsSnippet, DomEventFilter, DomEventData, or an interface that extends JsSnippet — instead of void or PendingJavaScriptResult. Calling such a method answers with that value, which is passed on to something that calls it later in the browser, such as addJsInitializer(JsFunction). Like any other declaration, the build collects the snippet into the bundle when it can reach it, so nothing is compiled from a string in the browser.

A snippet isn’t bound to an element, so get the implementation of its interface from JsSnippets.of(Class) rather than from executeJs(Class). The implementation holds no state, so it can be kept in a constant and shared.

An interface extends exactly one of JsInvokers, JsModuleInvokers, and JsSnippets. Passing a JsSnippets interface to executeJs(Class), or a JsInvokers interface to JsSnippets.of(), is a compile error, since each method accepts only the matching marker type. A method whose return type doesn’t match the kind the interface declares is refused with the method named.

The arguments of the Java call are captured and available in the expression as $0, $1, and so on. The expression is the body of the function, so it has to return a value if the caller expects one. The function takes no parameters of its own, unless the method is annotated with @JsFunctionParameterNames, which names the parameters that the caller passes to the function when it calls it.

Return Values

Add a listener to the PendingJavaScriptResult instance that a call answers with to access the value from a return statement in the JavaScript. This works the same way for a declared expression, an executeJs() expression, and a function called through callJsFunction(). A declared method has to declare PendingJavaScriptResult, or JavaScriptResult with a type argument (see Typed Results), as its return type to give access to the result.

Example 7. Checking for support of Constructable Stylesheets in the browser
Source code
Java
@JsDefinition
public interface FeatureDetectionJs extends JsInvokers {

    @JsExpression("return 'adoptedStyleSheets' in document")
    PendingJavaScriptResult supportsConstructableStylesheets();
}
Source code
Java
public void checkConstructableStylesheets() {
    getElement().executeJs(FeatureDetectionJs.class)
            .supportsConstructableStylesheets()
            .then(Boolean.class, supported -> {
                if (supported) {
                    System.out.println(
                            "Feature is supported");
                } else {
                    System.out.println(
                            "Feature isn't supported");
                }
            });
}

If the return value is a JavaScript Promise, the client only sends the return value to the server when the Promise is resolved.

Typed Results

Declare JavaScriptResult with a type argument instead of PendingJavaScriptResult to get the value already converted to that type, with no type token needed at the call site:

Example 8. Declaring a method that returns a typed result
Source code
Java
@JsDefinition
public interface DeepThoughtJs extends JsInvokers {

    @JsExpression("return 42")
    JavaScriptResult<Integer> getAnswer();
}
Source code
Java
public void revealAnswer() {
    getElement().executeJs(DeepThoughtJs.class).getAnswer()
            .then(answer -> Notification.show(
                    "The answer is " + answer));
}

The value is converted with Jackson, so any type Jackson can deserialize works, including beans and generic types such as List<Person>. A value that can’t be converted to the declared type goes to the error handler passed to then(), and fails a future obtained from toCompletableFuture(); without an error handler, it’s logged as a warning.

The type argument has to be known from the interface. It can be a concrete type, such as JavaScriptResult<Integer>. It can also be a type variable that an interface the definition extends binds to a concrete type. A raw or wildcard JavaScriptResult is refused, and so is a type variable that no interface binds to a concrete type, since nothing says what to convert the value to.

With JavaScriptResult<JsonNode>, the handlers get the JSON as the browser sent it. To choose the Java type at the call site instead, by calling then() with a Class or TypeReference, declare the method as returning PendingJavaScriptResult (see Deserializing Generic Types with TypeReference).

Deserializing Generic Types with TypeReference

The then() method accepts a Class parameter for simple types, but this doesn’t work for generic types like List<Person> due to Java type erasure. For these cases, use the Jackson TypeReference overloads.

Example 9. Deserializing a JavaScript array into a List<Person>
Source code
Java
@JsDefinition
public interface ItemsJs extends JsInvokers {

    @JsExpression("return this.getItems()")
    PendingJavaScriptResult getItems();

    @JsExpression("return this.getPersonMap()")
    PendingJavaScriptResult getPersonMap();
}
Source code
Java
getElement().executeJs(ItemsJs.class).getItems()
        .then(new TypeReference<List<Person>>() {},
                items -> {
                    // items is List<Person>
                    items.forEach(person ->
                            System.out.println(person.getName()));
                });

An error handler can be provided as a second callback. It receives an error message as a String when the JavaScript execution fails or the returned value can’t be converted to the target type:

Source code
Java
getElement().executeJs(ItemsJs.class).getItems()
        .then(new TypeReference<List<Person>>() {},
                items -> processItems(items),
                errorMessage -> handleError(errorMessage));

Without an error handler, a value that can’t be converted is logged as a warning and the result handler isn’t run.

You can also use toCompletableFuture(TypeReference) to get the result as a CompletableFuture:

Source code
Java
CompletableFuture<Map<String, Person>> future = getElement()
        .executeJs(ItemsJs.class).getPersonMap()
        .toCompletableFuture(
                new TypeReference<Map<String, Person>>() {});

If the execution fails or the returned value can’t be converted to the target type, the future completes exceptionally with a JavaScriptException. When the value can’t be converted, its cause is the conversion error.

executeJs Method

The Element.executeJs() method runs a JavaScript expression given as a string. The browser compiles the expression, so a strict content security policy blocks the call. Declare the JavaScript in Java instead (see Declaring JavaScript in Java). Use this method only for JavaScript that can’t be declared — an expression that isn’t known until runtime, for example.

The executeJs() method accepts two parameters: the JavaScript expression to invoke; and the parameters to pass to the expression. The given parameters are available as variables named $0, $1, and so on.

The arguments passed to the expression must be a type supported by the communication mechanism. The supported types are String, Integer, Double, Boolean, JsonNode, Element, Component, and JsFunction (see Passing JavaScript Functions).

Example 10. Calling MyModule.complete(true) on the client side
Source code
Java
public void complete() {
    getElement().executeJs("MyModule.complete($0)", true);
}
Example 11. Passing a JSON array to a JavaScript expression
Source code
Java
public void setItems(List<String> items) {
    getElement().executeJs("this.items = $0", items);
}
Warning
Avoid Script Injection Vulnerabilities
Always pass arguments using the $0, $1, …​ notation to avoid script injection vulnerabilities. Never concatenate or interpolate strings to build JavaScript code to be executed.

If you need to run JavaScript without having access to an element, use the UI.getCurrentOrThrow().getPage().executeJs() method.

callJsFunction Method

The Element.callJsFunction() method allows you to run a client-side component function from the server side. The method accepts two parameters: the name of the function to call; and the arguments to pass to the function.

The name of the function and the arguments are sent to the browser, which looks the function up on the element and calls it. No JavaScript is compiled from a string for this call, so it works under a strict content security policy. A dotted name, such as $connector.method, is resolved on the element property by property, and the function is called with the property it’s read from as this.

The arguments passed to the function must be a type supported by the communication mechanism. The supported types are String, Boolean, Integer, Double, JsonNode, Element, Component, and JsFunction (see Passing JavaScript Functions). Passing a JsFunction built with JsFunction.of() brings the browser-side compilation back, since the client builds such a function from its body string. A function declared as a snippet doesn’t.

Example 12. Calling the clearSelection() JavaScript function on the root element from the server side
Source code
Java
public void clearSelection() {
    getElement().callJsFunction("clearSelection");
}
Example 13. Calling the expand(otherComponentElement) JavaScript function on the root element from the server side
Source code
Java
public void setExpanded(Component otherComponent) {
    getElement().callJsFunction("expand",
            otherComponent.getElement());
}
Example 14. Passing a JSON object to a JavaScript function
Source code
Java
public void configure(String label, int count) {
    ObjectNode config = JacksonUtils.createObjectNode();
    config.put("label", label);
    config.put("count", count);
    config.put("enabled", true);
    getElement().callJsFunction("configure", config);
}

Undelivered Invocations

An invocation scheduled on the server is held in memory until it’s written into a response for the browser. An application that keeps scheduling invocations which never reach the browser grows until it runs out of memory. Once 1000 invocations for one UI are waiting to be sent, Flow logs a warning naming the component they belong to, the expression of the most recent one, and why nothing is being delivered. The warning is logged once per UI.

Invocations pile up whenever nothing carries them to the browser:

  • The owner is detached. An invocation for a detached element is held until that element is attached again, which never happens for a component the application has discarded.

  • The owner is invisible. Invocations for an invisible component are kept until it becomes visible.

  • The UI has no open push connection. Nothing is sent until the browser makes a request of its own, which a closed tab whose session hasn’t expired yet never does.

Where only the latest value matters — a progress value, a clock, a live measurement — avoid scheduling a new invocation for every update:

  • Keep the PendingJavaScriptResult that executeJs() returns, and call cancelExecution() on it before scheduling the next one.

  • If the invocation only sets an element property, use Element.setProperty() instead of executeJs(). Only the last value of a property is sent.

  • In a background task, compare UI.getLastUpdateSentTimestamp() against the current time and stop scheduling updates while the browser isn’t receiving them.

The timestamp is readable without the session lock, so a background task can decide whether to update the UI before acquiring it:

Source code
Java
if (Duration.between(ui.getLastUpdateSentTimestamp(), Instant.now())
        .compareTo(STALE_THRESHOLD) < 0) {
    ui.access(() -> statusLabel.setText(statusText));
}

It tells when the pending updates were last written towards the browser, not that the browser received them, and for a UI that has had no response written yet it’s the time the UI was created.

To find the code that schedules the invocations, enable debug logging for com.vaadin.flow.component.internal.PendingJavaScriptInvocationUtil, which then also logs the call site of the invocation that triggered the warning. Turning that logger off silences the warning.

Passing JavaScript Functions

A JsFunction lets you build a reusable JavaScript function on the server and pass it as a parameter to executeJs() or callJsFunction(). The function arrives on the client as a real callable function with its captured values pre-bound, so you don’t need to concatenate JavaScript fragments to embed server-side values.

The function body is compiled on the client, so a strict content security policy blocks it — also when the function is passed to a method of a JavaScript definition. Where the body is known in advance, declare the JavaScript in Java instead (see Declaring JavaScript in Java).

The first argument to JsFunction.of() is a JavaScript function body. The remaining arguments are captured values, referenced inside the body as $0, $1, … using the same naming convention as executeJs() parameters.

Example 15. Defining a function and invoking it
Source code
Java
JsFunction greet = JsFunction.of(
        "return $0 + ' ' + $1;", "Hello", "World");
getElement().executeJs(
        "this.textContent = $0();", greet);

Captures may be any value supported as an executeJs() parameter. An attached Element arrives as the corresponding DOM node; a detached Element arrives as null.

Example 16. Capturing an element
Source code
Java
Div target = new Div();
add(target);

JsFunction mutate = JsFunction.of(
        "$0.textContent = 'updated';",
        target.getElement());
getElement().executeJs("$0();", mutate);

Declaring Runtime Arguments

Use withArguments() to declare named parameters that the function accepts at call time. The body references them by name, and the JavaScript that invokes the function passes them positionally:

Example 17. A function with runtime arguments
Source code
Java
JsFunction format = JsFunction
        .of("return prefix + ':' + suffix;")
        .withArguments("prefix", "suffix");
getElement().executeJs(
        "this.textContent = $0('alpha', 'beta');", format);

Controlling this

In JavaScript, the value of this inside a function depends on how the function is invoked, not where it is defined. The body of a JsFunction follows this convention – this is not bound to the host element automatically.

When the function is invoked as $0(…​) from inside an executeJs() expression, the body’s this is the global object (or undefined in strict mode), not the element on which executeJs() was called. To set this explicitly, invoke the function with Function.prototype.call(): its first argument becomes this inside the body.

Example 18. Calling the function with a specific this
Source code
Java
JsFunction setOwnText = JsFunction
        .of("this.textContent = msg;")
        .withArguments("msg");
getElement().executeJs(
        "$0.call(this, 'host element text');", setOwnText);

If the body always needs to reference the same element regardless of how the function is called, pass it as a capture instead of relying on this.

Client-Side Lifecycle With addJsInitializer

The Element.addJsInitializer() method registers a JavaScript initializer that runs each time a client-side DOM node is created for the element, and whose returned cleanup callback runs when that DOM node is discarded or the returned Registration is removed.

Use this when you need to install something on the client-side DOM – an event listener, a third-party widget, an observer – and reliably tear it down. A one-shot executeJs() call doesn’t cover two cases: a real re-attach gives the element a brand-new DOM node that no longer has your listener, and cleanup from a server-side detach listener cannot be delivered because the element is leaving the tree.

Pass the initializer as a String expression, or as a JsFunction declared as a snippet.

Passing an Expression

The addJsInitializer(String, Object…​) overload takes the initializer as a JavaScript expression. The expression is compiled in the browser, so a strict content security policy blocks it.

The expression syntax is the same as executeJs(): this is the host element on the client, and parameters are referenced as $0, $1, …. If the expression returns a function, that function is invoked at teardown.

Example 19. Installing a listener with cleanup
Source code
Java
Registration registration = getElement().addJsInitializer("""
        const handler = (event) => console.log($1, event.target);
        this.addEventListener($0, handler);
        return () => this.removeEventListener($0, handler);
        """, "click", "clicked");

Here $0 is "click" and $1 is "clicked", so the event type and the log label come from the server rather than being hard-coded in the expression.

Passing a Declared Function

The addJsInitializer(JsFunction) overload takes the initializer as a function instead of as an expression. Declare it as a snippet of a @JsDefinition interface that extends JsSnippets (see Declaring Snippets) and obtain it through JsSnippets.of(), so nothing is compiled from a string in the browser and the initializer works under a strict content security policy:

Example 20. Declaring an initializer and passing it to addJsInitializer
Source code
Java
@JsDefinition
public interface ListenJs extends JsSnippets {

    @JsExpression("""
            const listener = () => this.classList.toggle($0);
            this.addEventListener('click', listener);
            return () => this.removeEventListener('click', listener);""")
    JsFunction toggleOnClick(String className);
}
Source code
Java
getElement().addJsInitializer(
        JsSnippets.of(ListenJs.class).toggleOnClick("active"));

The function runs with the element as this, at the same moments as a String initializer. The arguments of the call that created the snippet are available as $0, $1, … in its expression.

The initializer is called with no arguments. A function that declares parameters of its own — with @JsFunctionParameterNames or JsFunction.withArguments() — is rejected with an IllegalArgumentException. Pass the values the function needs as arguments of the snippet method instead.

Remove the registration on the server when the listener is no longer needed; the cleanup callback then runs on the client, for either overload.

Re-Attach Semantics

The initializer is re-run after a real re-attach – when the element is removed from the DOM in one round trip and re-added in a later one, and so the browser receives a fresh DOM node. It is not re-run when the element is detached and re-attached on the server inside a single round trip, because the client never discarded its DOM.

Cleanup Constraints

The return value of the initializer is read synchronously. A function is treated as the cleanup callback; returning null, undefined, or nothing at all (no return) means there’s no cleanup. Returning any other value – including a Promise resolving to a function – is logged as an error on the client.

If setup is asynchronous, don’t return the Promise. Keep a reference to the pending work and return a cleanup function that awaits it before tearing down. Awaiting the same promise in the cleanup callback ensures the resource is torn down even if cleanup runs before the asynchronous setup has finished – otherwise a slow import could create the widget after cleanup has already run, leaking it:

Source code
Java
getElement().addJsInitializer("""
        const widgetPromise = import('./my-widget.js')
                .then((module) => module.create(this));
        return async () => (await widgetPromise).destroy();
        """);

AB7EDF45-DB22-4560-AF27-FF1DC6944482

Updated –