Webview

Discord Source API Docs Issues Releases
Discord GitHub Javadoc GitHub



Build desktop apps in Java with the web tools you already know. Avaje Webview opens a native window backed by the operating system's own browser engine, so your UI is plain HTML, CSS and JavaScript and your logic stays in Java. Use React, Vue, htmx, or no framework at all.

It uses the iconic Java 25 FFM feature to call the platform's webview directly. Avoiding JNI, bundled native libraries, and runtime dependencies besides JSpecify annotations.

Platform requirements


Platform Engine Requirement
Linux WebKitGTK 6.0 libgtk-4, libwebkitgtk-6.0, libjavascriptcoregtk-6.0 must be installed
macOS WKWebView Built into macOS
Windows WebView2 (Edge) Pre-installed on Windows 10+

Linux install example (Debian/Ubuntu):

sudo apt-get install libgtk-4-1 libwebkitgtk-6.0-4 libjavascriptcoregtk-6.0-1

Quick Start


1. Add avaje-webview dependency.

<dependency>
  <groupId>io.avaje.webview</groupId>
  <artifactId>avaje-webview</artifactId>
  <version>${avaje.webview.version}</version>
</dependency>

2. JVM flags

On macOS, the first webview must be created on the OS main thread. Pass -XstartOnFirstThread to the JVM:

java -XstartOnFirstThread --enable-native-access=ALL-UNNAMED -jar myapp.jar

3. Build a Webview

Webview webview = Webview.builder()
    .enableDeveloperTools(true)
    .title("My App")
    .html("<h1>Hello World</h1>")
    .build();

webview.run();

Or navigate to a URL:

Webview webview = Webview.builder()
    .title("My App")
    .navigate("https://avaje.io")
    .build();

webview.run();

Options


Window Properties

Webview webview = Webview.builder()
    .title("Configurable Window")
    .width(1200)
    .height(800)
    .enableDeveloperTools(true) // Enable right-click > Inspect
    .resizable(false)           // Lock to width/height, no user resize
    .maximizable(false)         // Hide/disable the maximize button (ignored on Linux)
    .maximize(true)             // Start maximized (ignored if fullscreen(true))
    .fullscreen(true)           // Start fullscreen, takes precedence over maximize
    .minSize(600, 400)          // Minimum size the user can resize to
    .maxSize(1920, 1080)        // Maximum size the user can resize to
    .build();

// Set window constraints after creation
webview.setMinSize(600, 400);
webview.setMaxSize(1920, 1080);

// Resize, or lock to a fixed size
webview.setSize(1024, 768);
webview.setFixedSize(800, 600);

// Dark mode
webview.setDarkAppearance(true);

Window State

Control and query the window state at runtime. The state-changing methods return the Webview so they can be chained.

webview.maximizeWindow();
webview.unmaximizeWindow();  // Back to the prior size and position
webview.minimizeWindow();
webview.restoreWindow();     // Restore after minimize
webview.fullscreen();
webview.exitFullscreen();
webview.focusWindow();       // Bring to front, restoring first if minimized

boolean maximized = webview.isMaximized();
boolean minimized = webview.isMinimized();
boolean fullscreen = webview.isFullscreen();
WindowSize size = webview.getSize(); // Content area size in logical pixels

Hiding and Showing

By default the window shows itself once the first page has loaded, which avoids a flash of blank content. Pass showOnFirstLoad(false) to keep it hidden until you call showWindow(), for example to finish some setup first:

Webview webview = Webview.builder()
    .showOnFirstLoad(false)
    .navigate("http://localhost:8080")
    .build();

webview.onPageLoaded(_ -> {
    webview.eval("initApp()");
    webview.showWindow();
});

webview.run();

hideWindow() hides the window without closing it. The page keeps running, and showWindow() brings it back.

Borderless Windows

Webview webview = Webview.builder()
    .borderless(true) // No title bar, borders, or minimize/maximize/close buttons
    .build();

Combine with webview.startWindowDrag() to implement a custom draggable title bar, since a borderless window has no native title bar for the user to grab.

Keep the native outline (drop shadow and thin border) while still removing the title bar:

Webview webview = Webview.builder()
    .borderless(true, true) // outline=true keeps the native border/shadow
    .build();

Transparent Windows

Webview webview = Webview.builder()
    .borderless(true)
    .transparent(true) // Window background is see-through wherever the page doesn't paint
    .html("<body style='background:transparent'>...</body>")
    .build();

Combine with a page that only paints part of its area (e.g. background: transparent plus a backdrop-filter: blur(...) card) to get a native-looking translucent window. Usually paired with borderless(true) so there's no opaque title bar left behind.

Child Windows

Webview parent = Webview.builder().title("Parent").build();

Webview child = Webview.builder()
    .title("Child")
    .parent(parent) // Blocks the parent's input until this window closes
    .build();

The parent window is disabled (blocked from mouse/keyboard input) as soon as the child is built, and re-enabled automatically when the child closes.

Pass true as a second argument to parent(...) to keep the parent locked to the child's position while dragging (Windows and macOS only currently):

Webview child = Webview.builder()
    .parent(parent, true) // parent moves with the child when dragged
    .build();

Set Window Icon

// From file path
webview.setIcon(Path.of("icon.ico"));

// From classpath resource
webview.setIcon(getClass().getResource("/icon.ico").toURI());

Note: GTK4 dropped support for arbitrary file-based window icons. On Linux, the app icon is set via the .desktop file and icon theme. setIcon is a no-op on Linux.

Content Protection

Hide the window's contents from screen capture, so screenshots, recordings, and screen shares see a blank area instead:

Webview webview = Webview.builder()
    .contentProtection(true) // Hidden from capture from the moment it opens
    .build();

// Toggle at runtime
webview.setContentProtection(false);

Supported on Windows and macOS. Does nothing on Linux.

User Agent

Webview webview = Webview.builder()
    .userAgent("MyApp/1.0") // Defaults to the platform engine's user agent
    .navigate("https://example.com")
    .build();

// Change later, applies from the next page load
webview.setUserAgent("MyApp/1.1");

Events and Navigation


Window Events

webview.onResize(size -> System.out.println("now " + size.width() + "x" + size.height()));
webview.onFocusChanged(focused -> System.out.println(focused ? "focused" : "unfocused"));
webview.onPageLoaded(url -> System.out.println("loaded " + url));

onPageLoaded fires every time a page finishes loading, whether from navigate, setHTML, or the user following a link. Read the current URL at any time with getPageUrl() (content from setHTML reports about:blank).

onCloseRequested lets you stop the user from closing the window, for example to ask about unsaved changes first. Calling close() yourself always works, so you can close for real once they confirm:

webview.onCloseRequested(() -> {
  if (!hasUnsavedChanges()) {
    return true;
  }
  webview.eval("askToClose()"); // the page asks, then calls a binding that runs webview.close()
  return false;
});

onNavigate runs before the page goes somewhere else (a link click, a script changing location, a form submission, a redirect, etc.). Return false to stay put. A common use is keeping your app's own pages in the window and sending everything else to the user's browser:

webview.onNavigate(url -> {
  if (url.startsWith("https://myapp.example/")) {
    return true;
  }
  Webview.openExternal(URI.create(url));
  return false;
});

The check runs on the UI thread, so keep it quick. Iframes are checked too, so an allowlist needs to include anything the page embeds. Navigations started in Java with navigate or setHTML are not checked.

Webview.openExternal(uri) opens an http/https URI in the default browser, or a mailto: URI in the mail client.

New Window Requests

The webview never opens popup windows itself. By default, target="_blank" links and window.open open in the default browser or mail client. Adding an onNewWindow listener replaces that default, so you can open the URL in another Webview, in this one, or not at all:

webview.onNewWindow(url -> webview.navigate(url)); // open in this window instead

Java-JavaScript Bridge


Executing JavaScript from Java

Webview webview = Webview.builder()
    .html("<html><body><h1 id='title'>Original</h1></body></html>")
    .build();

// Execute JavaScript in the webview once the page has loaded
webview.onPageLoaded(_ -> webview.eval("document.getElementById('title').textContent = 'Updated!';"));

webview.run();

To run a script on every page load, register it with setInitScript(script). Use setInitScript(script, true) to inject it into nested iframes as well.

Reading values back from JavaScript

eval doesn't give you anything back. When you need a value from the page, use evalResult, which returns a CompletableFuture holding the result as JSON:

webview.evalResult("document.getElementById('name').value")
    .thenAccept(json -> System.out.println(json)); // "\"Ada\""

// await works too, and returned Promises are waited on
webview.evalResult("await fetch('/status').then(r => r.json())")
    .thenAccept(json -> System.out.println(json));

// JavaScript errors fail the future with a JavaScriptException
webview.evalResult("missingFunction()")
    .exceptionally(e -> {
        System.out.println(e.getMessage()); // ReferenceError: ...
        return null;
    });

The expression must be a single JavaScript expression; wrap several statements in an IIFE. undefined comes back as "null". The future fails with JavaScriptException when the script has a syntax error, throws, rejects, or returns something that can't be turned into JSON.

The future completes on the UI thread. From a background thread you can block on it with get() or join(). On the UI thread, such as inside a binding, blocking would freeze the window forever, so those calls throw IllegalStateException. Use thenAccept and friends there.

Calling Java from JavaScript

Bind Java functions as async window globals that return Promises:

Webview webview = Webview.builder()
    .title("Java Bridge Example")
    .html("""
        <!DOCTYPE html>
        <html>
        <body>
           <button onclick="callJava()">Call Java</button>
           <div id="result"></div>
           <script>
               async function callJava() {
                   try {
                       const result = await greet('World');
                       document.getElementById('result').textContent = result;
                   } catch (error) {
                       console.error('Java error:', error);
                   }
               }
           </script>
        </body>
        </html>
    """)
    .build();

// Bind Java method to JavaScript — args arrive as a JSON array string
webview.bind("greet", (String jsonArgs) -> {
    return "\"Hello, " + jsonArgs + "!\""; // return value must be valid JSON
});

webview.run();

Binding callbacks receive arguments as a JSON array string and must return a valid JSON string. The JavaScript side receives the return value as the resolved Promise value. Bindings persist across page navigations; remove one with unbind(name). The examples below use avaje-jsonb, but any JSON library works.

Complex Data Exchange

@Json
record User(String name, int age) {}

@Json
record UserRequest(String action, String userId) {}

Webview webview = Webview.builder()
    .html("""
        <script>
            async function getUser() {
                const user = await fetchUser({ action: 'get', userId: '123' });
                console.log(user.name, user.age);
            }
        </script>
    """)
    .build();

webview.bind("fetchUser", (String jsonArgs) -> {
    UserRequest request = Jsonb.instance().type(UserRequest.class).list().fromJson(jsonArgs).getFirst();
    User user = new User("Alice", 30);
    return Jsonb.instance().toJson(user);
});

webview.onPageLoaded(_ -> webview.eval("getUser();"));
webview.run();

Multiple Windows


Multiple windows are supported on all platforms. Additional windows can be created from any thread once the first window's event loop is running.

try (var w1 = Webview.builder().build()) {
    w1.bind("openSecond", _ -> {
        Thread.ofPlatform().start(() -> {
            try (var w2 = Webview.builder().html("<h1>Window 2</h1>").build()) {
                w2.run();
            }
        });
        return "null";
    });
    w1.setHTML("<button onclick='openSecond()'>Open second window</button>");
    w1.run();
}

macOS constraint: the first Webview must be created on the OS main thread (-XstartOnFirstThread). Additional windows may be created from background threads.

Linux constraint: the first Webview must be created on the thread that will call run(). All subsequent windows dispatch their init to that thread automatically.

To touch a webview from a background thread, schedule the work on its event thread with webview.dispatch(() -> ...).

Console output


Webview webview = Webview.builder()
    .redirectConsole(true) // Defaults to false
    .build();

With redirectConsole(true), console.log, console.warn, console.error, etc. are forwarded to java.lang.System.Logger under the name io.avaje.webview. Configure your logging framework (e.g. Simple Logger) to see webview JS console output.