# Migrate from ComposeNativeWebview

Move an app from the ComposeNativeWebview library to the Nucleus webview module. Swap the Maven coordinates, run the desktop WebView in a Nucleus window, and review the few API and behavior changes.

Move an app from the ComposeNativeWebview library (`composewebview`) to the Nucleus
[`webview` module](/docs/webview). Coming from 1.0.x, it is a dependency swap: the package is the
same, `dev.nucleusframework.webview`, and `WebView`, `WebViewState`, `WebViewNavigator`, the
settings, the cookie manager and the JS bridge keep their signatures. Coming from the
1.0.0-alpha / beta builds (`io.github.kdroidfilter`, the Wry backend), the imports change too and
the desktop WebView moves into a Nucleus window.

Its code moved into the Nucleus repository. Bug fixes and new WebView features land in Nucleus, in
the `webview` module, under the Nucleus version.

## Why the code moved

ComposeNativeWebview 1.0.x already depended on Nucleus: its desktop WebView is a `NativeView` of
the Nucleus window runtime (`decorated-window-tao`, plus `core-runtime`). Each Nucleus release meant
a matching WebView release, from a second repository with its own CI.

In the Nucleus repository, the WebView, the window runtime it embeds into, the packaging and the
other modules are built, tested and released together:

- **One version.** `nucleus.webview` always matches the `window-runtime` and `nucleus-application`
  you use. A change to `NativeView` that would break the WebView fails in the same pull request.
- **One CI pipeline.** It builds the WebView natives of every platform (WebView2 on Windows x64
  and ARM64, WKWebView on macOS, WebKitGTK on Linux x64 and aarch64) and publishes every target
  (JVM, Android, iOS, Wasm) in the same release.
- **The same rules as the rest of Nucleus**: JNI only, `java.util.logging` on the desktop, GraalVM
  metadata in the JAR, a public API checked for binary compatibility.

That makes the WebView far easier to maintain: one codebase, one release, and the people who
change the window runtime see what it does to the WebView.

## What's new

The common API is the one of 1.0.3. The desktop backends were rewritten behind it, on rules found
by a torture suite: each scenario runs a real `nucleusApplication` with real engines, drives it
from other threads and with real input (posted window messages on Windows, `NSEvent`s on macOS, a
uinput device on Linux), and checks the result from the page, the engine or the OS. What
ComposeNativeWebview 1.0.3 did not do:

- **Several WebViews in one window on Windows.** The old backend created a DirectComposition
  target per view, and a window accepts only one: every WebView after the first failed. Views now
  share one target per window.
- **Load errors on the desktop.** `state.errorsForCurrentRequest` stayed empty on every desktop
  backend
  ([ComposeNativeWebview#69](https://github.com/NucleusFramework/ComposeNativeWebview/issues/69)).
  macOS and Linux now report main-frame failures there, and a WebView2 that cannot be created lands
  there too instead of leaving the state `Initializing` for good.
- **Edit shortcuts.** ⌘X / ⌘C / ⌘V / ⌘A / ⌘Z / ⇧⌘Z work in the page on macOS instead of beeping
  ([#68](https://github.com/NucleusFramework/ComposeNativeWebview/issues/68)), and Ctrl+Z /
  Ctrl+Shift+Z / Ctrl+Y undo and redo on Linux, where WebKitGTK binds no undo key.
- **Linux on X11.** The page shows instead of rendering black
  ([#72](https://github.com/NucleusFramework/ComposeNativeWebview/issues/72)), and right clicks
  open WebKit's menu without taking the app down
  ([#45](https://github.com/NucleusFramework/ComposeNativeWebview/issues/45)).
- **The JS bridge survives `location.hash` changes**
  ([#42](https://github.com/NucleusFramework/ComposeNativeWebview/issues/42)).
- **Text round-trips intact.** Strings cross JNI as UTF-16: emoji and other characters outside the
  BMP, and U+0000, come back from `evaluateJavaScript`, the bridge and cookies as sent. The old
  backends used modified UTF-8, and on Linux escaped every non-ASCII byte of script results and
  cookie values.
- **Profiles that persist where they should.** On Linux, views with the same data directory share
  one cookie jar, kept on disk under `$XDG_DATA_HOME/<appId>/webkitgtk`; the old backend gave each
  view a throwaway context. On Windows, the default profile is `%LOCALAPPDATA%\<appId>\WebView2`
  instead of a folder next to `java.exe` (or inside Program Files once installed). On macOS 14+,
  `dataDirectory` selects a website data store of its own; it was ignored.
- **Pages keep their own background.** macOS and Linux no longer inject
  `background-color: #fff !important` into every page.
- **Large HTML.** On Windows, `loadHtml` loads pages past Chromium's 2 MiB URL limit.
- **Robustness.** A JS bridge handler that throws is logged instead of closing the application. A
  backend that cannot be created leaves an empty WebView instead of throwing inside composition. A
  WebView moved under another parent, or recreated by a keyed list, gets a live backend instead of
  the one its old composition just destroyed. Calls from any thread are marshalled to the engine's
  thread (they failed silently or raced before), and every script, cookie and capture call is
  answered exactly once, also when the view goes away.
- **The web target, rebuilt.** The iframe is composed with Compose's own `HtmlElementView`: it is
  placed and clipped like any composable (the old overlay was positioned by hand on
  `document.body`, at `z-index: 1000`, and covered the UI when scrolled), Tab moves focus into and
  out of a same-origin page, a URL loaded after HTML shows, and `wasmJSWebSettings.backgroundColor`
  is a valid CSS colour.
- **`captureImageBitmapOrNull()`** on the desktop decodes a capture into a Compose `ImageBitmap`
  through Skia, with no AWT.

Android and iOS keep the implementation of 1.0.3; only the bridge's exception handling changed
there.

## You don't need the whole framework

Nucleus is modular: `nucleus.webview` is one artifact, and only one target needs the rest of
Nucleus.

- **Android, iOS and the web**: the WebView is a library like any other. It depends on Compose,
  kotlinx.coroutines and kotlinx.serialization only: no Nucleus application, plugin or window.
- **The desktop** is the exception: the WebView renders only inside a Nucleus window
  (`nucleusApplication`). The page is a native view (WebView2, WKWebView, WebKitGTK) that the
  Nucleus window runtime embeds as a `NativeView`: Compose places it, clips it, routes input to it
  and draws over it (the `content` slot of `WebView`). Outside a Nucleus window there is no host
  and the WebView stays an empty box.

  ComposeNativeWebview's first desktop backend did it on AWT, the backend of Compose Desktop's
  windows: a Rust Wry WebView, reached through UniFFI and JNA, attached as a child of a heavyweight
  AWT canvas inside a `SwingPanel`. Compose could not draw over it, its bounds were pushed by a
  16 ms Swing timer, another timer pumped Windows messages, focus was handed over by hand on click.
  Each of those hacks cost performance and was too much to keep working alone, which is why 1.0.0
  already moved to the Nucleus window runtime, built for this kind of embedding.

## Before you start

- Find your version. `dev.nucleusframework:composewebview` 1.0.0 to 1.0.3 is the Nucleus line
  (same package). `io.github.kdroidfilter:composewebview` 1.0.0-alpha-01 to 1.0.0-beta-02 is the
  Wry line (package `io.github.kdroidfilter.webview`).
- Use Compose Multiplatform 1.13 or later and JDK 17 or later, as Nucleus 3.0 requires. On
  Android, `minSdk` stays 21.
- Your app moves to Nucleus 3.0 at the same time. 1.0.x ran on Nucleus 2.5 with
  `nucleusApplication(backend = NucleusBackend.Tao)` and `decorated-window-tao`: read
  [Migrate from Nucleus 2.x](/docs/migrate/from-2.x). A Wry-line app runs in a Compose Desktop
  `Window`: read [Migrate from JetBrains Compose Desktop](/docs/migrate/from-jb-compose).

## Replace the dependency

| ComposeNativeWebview | Nucleus |
| --- | --- |
| `dev.nucleusframework:composewebview` (1.0.x) | `dev.nucleusframework:nucleus.webview` |
| `io.github.kdroidfilter:composewebview` (alpha / beta) | `dev.nucleusframework:nucleus.webview` |
| `io.github.kdroidfilter:wrywebview` (alpha / beta, brought by `composewebview`) | Removed: no Wry, UniFFI or JNA |
| `dev.nucleusframework:nucleus.decorated-window-tao` (2.5, brought by `composewebview` 1.0.x) | `dev.nucleusframework:nucleus.window-runtime`, brought by `nucleus.webview` on the JVM |

```diff title="build.gradle.kts"
 kotlin {
     sourceSets {
         commonMain.dependencies {
-            implementation("dev.nucleusframework:composewebview:1.0.3")
+            implementation("dev.nucleusframework:nucleus.webview:3.0.0")
         }
         jvmMain.dependencies {
-            implementation("dev.nucleusframework:nucleus.nucleus-application:2.5.5")
+            // nucleusApplication and the Nucleus windows the desktop WebView renders in
+            implementation("dev.nucleusframework:nucleus.nucleus-application:3.0.0")
         }
     }
 }
```

`<version>` is the Nucleus version, 3.0.0 or later. The artifact covers the same targets as
before: JVM desktop, Android, iOS (`iosArm64`, `iosSimulatorArm64`) and Wasm (`wasmJs`). It brings
its natives (`nucleus_webview` for each platform, plus `WebView2Loader.dll` on Windows) inside the
JVM JAR.

## Replace the imports

From 1.0.x, nothing changes: the package is still `dev.nucleusframework.webview`. From the Wry
line, replace the root:

| ComposeNativeWebview | Nucleus |
| --- | --- |
| `io.github.kdroidfilter.webview.web.*` (`WebView`, `WebViewState`, `WebViewNavigator`, `LoadingState`, `WebContent`, …) | `dev.nucleusframework.webview.web.*` |
| `io.github.kdroidfilter.webview.jsbridge.*` | `dev.nucleusframework.webview.jsbridge.*` |
| `io.github.kdroidfilter.webview.cookie.*` | `dev.nucleusframework.webview.cookie.*` |
| `io.github.kdroidfilter.webview.setting.*` | `dev.nucleusframework.webview.setting.*` |
| `io.github.kdroidfilter.webview.request.*` | `dev.nucleusframework.webview.request.*` |
| `io.github.kdroidfilter.webview.util.*` (`KLogger`, `KLogSeverity`) | `dev.nucleusframework.webview.util.*` |
| `io.github.kdroidfilter.webview.wry.*` (`WryWebViewPanel`) | Removed |

```bash
grep -rl 'io.github.kdroidfilter.webview' --include='*.kt' src \
  | xargs sed -i 's/io\.github\.kdroidfilter\.webview/dev.nucleusframework.webview/g'
```

On macOS, write `sed -i ''`.

## Port the code

### Desktop: run under nucleusApplication

From 1.0.x, drop the `backend` argument; `nucleusApplication` has only the Tao runtime now:

```diff
 import dev.nucleusframework.application.DecoratedWindow
-import dev.nucleusframework.application.NucleusBackend
 import dev.nucleusframework.application.nucleusApplication

-fun main() = nucleusApplication(backend = NucleusBackend.Tao) {
+fun main(args: Array<String>) = nucleusApplication(args) {
     DecoratedWindow(onCloseRequest = ::exitApplication, title = "Browser") {
         Browser("https://example.com")
     }
 }
```

From the Wry line, replace Compose Desktop's `application` and `Window` the same way:

```diff
-import androidx.compose.ui.window.Window
-import androidx.compose.ui.window.application
+import dev.nucleusframework.application.Window
+import dev.nucleusframework.application.nucleusApplication

-fun main() = application {
+fun main(args: Array<String>) = nucleusApplication(args) {
     Window(onCloseRequest = ::exitApplication, title = "Browser") {
         Browser("https://example.com")
     }
 }
```

The rest of the app's move (Gradle plugin, dialogs, tray) is in
[Migrate from JetBrains Compose Desktop](/docs/migrate/from-jb-compose). The
`--enable-native-access=ALL-UNNAMED` flag that Wry's JNA asked for came from that backend; check
whether your other libraries still need it before you remove it.

### State, navigator and content

Unchanged. The same code compiles against `nucleus.webview`:

```kotlin
import dev.nucleusframework.webview.web.WebView
import dev.nucleusframework.webview.web.rememberWebViewNavigator
import dev.nucleusframework.webview.web.rememberWebViewState

@Composable
fun Browser(url: String) {
    val state = rememberWebViewState(url) {
        customUserAgentString = "MyApp/1.0"
    }
    val navigator = rememberWebViewNavigator()

    Column(Modifier.fillMaxSize()) {
        Row {
            Button(onClick = { navigator.navigateBack() }, enabled = navigator.canGoBack) { Text("Back") }
            Button(onClick = { navigator.reload() }) { Text("Reload") }
            Button(onClick = { navigator.loadHtml("<h1>Hello</h1>") }) { Text("HTML") }
        }
        WebView(state, Modifier.weight(1f), navigator) {
            // Compose drawn over the page: a loading bar, a dialog…
            if (state.isLoading) LinearProgressIndicator(Modifier.fillMaxWidth())
        }
    }
}
```

### API mapping

| Area | ComposeNativeWebview 1.0.x | Nucleus |
| --- | --- | --- |
| Composable | `WebView(state, modifier, navigator, webViewJsBridge, onCreated, onDispose, content)` | Same |
| State | `rememberWebViewState(url, headers) { settings }`, `rememberWebViewStateWithHTMLData`, `rememberWebViewStateWithHTMLFile` | Same |
| Observable state | `isLoading`, `loadingState`, `lastLoadedUrl`, `pageTitle`, `errorsForCurrentRequest` | Same; `errorsForCurrentRequest` now filled on macOS and Linux desktops |
| Navigator | `rememberWebViewNavigator(requestInterceptor)`, `loadUrl(url, headers)`, `loadHtml`, `loadHtmlFile`, `navigateBack`, `navigateForward`, `reload`, `stopLoading`, `canGoBack`, `canGoForward` | Same |
| JavaScript | `navigator.evaluateJavaScript(script) { result -> }` | Same |
| JS bridge | `rememberWebViewJsBridge(navigator)`, `WebViewJsBridge(navigator, jsBridgeName)`, `IJsMessageHandler`, `JsMessage`, `processParams`, `dataToJsonString` | Same; a throwing handler is logged and its call dropped |
| Cookies | `state.cookieManager.setCookie(url, Cookie(…))`, `getCookies`, `removeCookies`, `removeAllCookies` | Same |
| Settings | `WebSettings` (`isJavaScriptEnabled`, `customUserAgentString`, `zoomLevel`, `backgroundColor`, `logSeverity`, …), `androidWebSettings`, `desktopWebSettings`, `iOSWebSettings`, `wasmJSWebSettings` | Same fields and defaults |
| Interception | `RequestInterceptor`, `WebRequest`, `WebRequestInterceptResult.Allow` / `Reject` / `Modify` | Same |
| Custom engine | `LocalWebViewFactory`, `WebViewFactoryParam`, `defaultWebViewFactory`, `NativeWebView` | Same |
| Screenshot | `IWebView.captureScreenshotOrNull()` (bytes) | Same, plus `captureImageBitmapOrNull()` on the desktop |
| Release | Leave the composition; `onDispose(nativeWebView)` | Same: there is no `dispose()` to call |

A few common cases, which compile unchanged from 1.0.x:

```kotlin
// JS bridge: the page calls window.kmpJsBridge.callNative("echo", params, callback)
val bridge = rememberWebViewJsBridge(navigator)
LaunchedEffect(bridge) {
    bridge.register(object : IJsMessageHandler {
        override fun methodName() = "echo"
        override fun handle(message: JsMessage, navigator: WebViewNavigator?, callback: (String) -> Unit) {
            callback(message.params)
        }
    })
}
WebView(state, navigator = navigator, webViewJsBridge = bridge)

// Cookies
scope.launch {
    state.cookieManager.setCookie("https://example.com", Cookie(name = "session", value = "abc"))
    val cookies = state.cookieManager.getCookies("https://example.com")
}

// Desktop settings
val state = rememberWebViewState(url) {
    desktopWebSettings.dataDirectory = "/path/to/profile"
    desktopWebSettings.enableDevtools = true
}

// Errors of the current request
state.errorsForCurrentRequest.firstOrNull()?.let { error ->
    Text("Could not load the page: ${error.description} (${error.code})")
}
```

### Coming from the Wry line

On top of the package, these changed between the alpha / beta builds and 1.0, and so differ in
Nucleus:

| Alpha / beta | Nucleus |
| --- | --- |
| `WebView(…, onCreated: () -> Unit, onDispose: () -> Unit)` | One overload taking `(NativeWebView) -> Unit`. A lambda such as `{ log("created") }` still compiles; a reference to a function without parameters does not |
| `WebView(…, factory = …)` | Provide the factory through `LocalWebViewFactory` |
| No overlay slot | `WebView(…) { content }` draws Compose over the page |
| `desktopWebSettings.transparent = true` by default | `false` by default: the page sits on an opaque surface. Set it to `true` to see Compose content under the page |
| — | `androidWebSettings.domStorageEnabled` |
| `WryWebViewPanel` | Removed: use `WebView` |

### Removed APIs

| ComposeNativeWebview | Nucleus |
| --- | --- |
| `WindowsWebView2NativeWebView`, `MacOsWebKitNativeWebView`, `LinuxWebKitNativeWebView` (public on the JVM) | Internal. Use `NativeWebView`, which keeps its public methods, or a factory through `LocalWebViewFactory` |
| `IWebView.toAwtImage()` (desktop, `BufferedImage`) | `IWebView.captureImageBitmapOrNull()`, a Compose `ImageBitmap`, or `captureScreenshotOrNull()` for the bytes |
| `ComponentInfo`, `FocusSwitcher`, `Updater`, `LocalLayerContainer` (web) | Removed: Compose's `HtmlElementView` places the iframe |

### Behavior changes

- **Loading state.** `Finished` means the page exists: the desktop no longer reports a navigation
  that has a URL but has not loaded yet as finished, so page scripts and the bridge are not called
  too early. A `WebViewState` shown by a new WebView (moved, recreated) starts again from
  `Initializing`.
- **Data directories.** On Linux, cookies and storage now persist between runs by default, and
  views share them per data directory; set `desktopWebSettings.incognito = true` for the old
  throwaway behavior. On Windows, the default profile moved to `%LOCALAPPDATA%\<appId>\WebView2`:
  cookies and storage saved by a 1.0.x build in the old default folder are not read. Set
  `dataDirectory` to keep a folder of your own.
- **Backgrounds.** On macOS and Linux a page without a background shows the WebView's background
  colour instead of a forced white; a non-white or transparent background now applies on macOS.
  Windows still paints opaque pages white.
- **Navigation listeners** added with `NativeWebView.addNavigateListener` must all allow a
  navigation on Linux: one refusal blocks it (one approval was enough before). A listener that
  throws allows it.
- **Large HTML on Windows.** Past 2 MiB, `loadHtml` serves the page from memory under the
  `https://nucleus-webview.invalid` origin instead of an opaque `data:` origin. `baseUrl` is still
  ignored on Windows.
- **The web.** Moving the WebView with `movableContentOf` reloads its page (a browser reloads an
  iframe moved in the DOM). A same-origin page reports its real address and title after links and
  history moves.
- **Logging.** On the desktop, messages go to `java.util.logging` under the
  `dev.nucleusframework.webview` logger, whose level your app controls, instead of `println`.
  `webSettings.logSeverity` still filters them first. Android, iOS and the web still print, off by
  default.

## Platform requirements

| Platform | Engine | Needs |
| --- | --- | --- |
| Windows (x64, ARM64) | WebView2 | The [WebView2 Runtime](https://developer.microsoft.com/microsoft-edge/webview2/) (Evergreen), preinstalled on Windows 11; install it where it is missing. `WebView2Loader.dll` ships with the module |
| macOS (arm64, x64) | WKWebView | macOS 11 or later. A separate store per `dataDirectory` needs macOS 14; older systems use the default store |
| Linux (x64, aarch64) | WebKitGTK | WebKitGTK 4.1 (`libwebkit2gtk-4.1-0` on Debian and Ubuntu) and GTK 3 |
| Android | `android.webkit.WebView` | `minSdk` 21 |
| iOS | `WKWebView` | `iosArm64`, `iosSimulatorArm64` |
| Web | `<iframe>` | `wasmJs`. The page must allow being framed; scripts, history and cookies only reach a same-origin page |

When the desktop engine cannot be created (no runtime, no library), the WebView stays empty and
the reason is logged; it no longer takes the application down.

## Checklist

- Replace `composewebview` (either group) with `dev.nucleusframework:nucleus.webview`, and drop
  `wrywebview` and `decorated-window-tao` if you declared them.
- Move to Nucleus 3.0 and Compose Multiplatform 1.13.
- Desktop: run under `nucleusApplication(args)` with Nucleus windows, without the `backend`
  argument.
- Wry line: replace `io.github.kdroidfilter.webview` with `dev.nucleusframework.webview`, pass the
  factory through `LocalWebViewFactory`, and check `desktopWebSettings.transparent`.
- Replace `toAwtImage()` with `captureImageBitmapOrNull()`, and the platform `NativeWebView`
  classes with `NativeWebView`.
- Linux: install WebKitGTK 4.1. Windows: make sure the WebView2 Runtime is present.
- Check what depended on the old profile folders, the forced white background or a
  `Finished` state reached before the page loaded.
- Read `errorsForCurrentRequest` if you want load errors on the desktop.
