# Capacitor Architecture This document describes how the Capacitor core repository is put together: what the packages are, how the JavaScript runtime talks to the native runtimes, what each platform does under the hood, and how the whole thing is built and released. It describes the repository as it currently stands — last verified against `next` at 9.0.0-alpha.7. Where this document and the source disagree, the source wins; fix the document in the same PR. If you are about to change code, read [§12 Invariants and gotchas](#12-invariants-and-gotchas) first. This is a contributor-facing document — for end-user documentation see [capacitorjs.com/docs](https://capacitorjs.com/docs). --- ## Table of contents - [1. What Capacitor is, structurally](#1-what-capacitor-is-structurally) - [2. Repository layout](#2-repository-layout) - [3. Package boundaries](#3-package-boundaries) - [4. Native bridge lifecycle](#4-native-bridge-lifecycle) - [4.9 CapacitorHttp and cookie interception](#49-capacitorhttp-and-cookie-interception) - [5. iOS internals](#5-ios-internals) - [5.8 Permissions (iOS)](#58-permissions-ios) - [6. Android internals](#6-android-internals) - [6.6 Permissions (Android)](#66-permissions-android) - [6.7 Process-death restoration](#67-process-death-restoration) - [6.8 SystemBars and edge-to-edge](#68-systembars-and-edge-to-edge) - [7. Web and custom platforms](#7-web-and-custom-platforms) - [7.1 Cordova compatibility](#71-cordova-compatibility) - [8. Configuration flow](#8-configuration-flow) - [8.1 Remote content: `server.url` and the two URLs](#81-remote-content-serverurl-and-the-two-urls) - [9. Build pipeline](#9-build-pipeline) - [9.6 Migration tasks](#96-migration-tasks) - [10. Release process](#10-release-process) - [11. Testing and CI](#11-testing-and-ci) - [12. Invariants and gotchas](#12-invariants-and-gotchas) --- ## 1. What Capacitor is, structurally A Capacitor app is a web app running inside a platform web view (WKWebView on iOS, Android's `WebView` on Android), with a message channel to a native host process. The repository contains four shipped packages plus the project templates the CLI uses to scaffold native projects: | Package | Language | Ships as | | --- | --- | --- | | `@capacitor/core` | TypeScript | npm | | `@capacitor/cli` | TypeScript (Node) | npm | | `@capacitor/ios` | Swift + Objective-C | npm (sources), CocoaPods, SwiftPM | | `@capacitor/android` | Java | npm (sources), Maven Central | There are **two distinct JavaScript runtimes** in this repo, and conflating them is the single most common source of confusion: 1. **`@capacitor/core`** (`core/src/`) — the module app code imports. Ships to npm, bundled by the app's own bundler. It knows about platforms abstractly and is *platform-agnostic*: on the web it is the whole runtime; on native it is a thin façade over globals the native layer installed. 2. **`native-bridge.js`** (`core/native-bridge.ts`) — a standalone IIFE injected into the web view **by the native layer before any page script runs**. It is never imported by app code and is not part of the `@capacitor/core` module graph. It is compiled into `android/capacitor/src/main/assets/native-bridge.js` and `ios/Sources/Capacitor/assets/native-bridge.js` as generated, committed artifacts. ```mermaid graph TB subgraph WebView["Web view (one JS realm)"] APP["App code
import Camera from '@capacitor/camera'"] CORE["@capacitor/core
registerPlugin() → Proxy"] GLOBAL["window.Capacitor
global instance"] NB["native-bridge.js
injected at document-start"] SHIM["Per-plugin JS shims + PluginHeaders
generated by native JSExport"] end subgraph Native["Native host process"] BRIDGE["CapacitorBridge (iOS)
Bridge (Android)"] PLUGINS["Plugin instances"] end APP --> CORE CORE --> GLOBAL NB -.->|"defines toNative/fromNative on"| GLOBAL SHIM -.->|"defines Plugins.X + PluginHeaders on"| GLOBAL GLOBAL <-->|"postMessage / evaluateJavaScript"| BRIDGE BRIDGE --> PLUGINS ``` --- ## 2. Repository layout ``` capacitor/ ├── core/ @capacitor/core — JS runtime + native-bridge source ├── cli/ @capacitor/cli — `cap` command ├── ios/ @capacitor/ios — Swift/ObjC runtime ├── android/ @capacitor/android — Java runtime (2 Gradle modules) ├── android-template/ scaffold for `cap add android` ├── ios-spm-template/ scaffold for `cap add ios` (default, SwiftPM) ├── ios-pods-template/ scaffold for `cap add ios --packagemanager cocoapods` ├── capacitor-cordova-android-plugins/ Cordova compat scaffold (Android) ├── capacitor-cordova-ios-plugins/ Cordova compat scaffold (iOS) ├── Package.swift SwiftPM manifest for the iOS runtime ├── scripts/ repo tooling (asset packing, publishing, version sync) └── .github/workflows/ CI + publish workflows ``` The npm workspaces are exactly `android`, `ios`, `cli`, `core` (see the root `package.json`). The template directories are **not** workspaces — they are packed into tarballs and shipped inside `@capacitor/cli`. --- ## 3. Package boundaries ### 3.1 Dependency graph ```mermaid graph LR subgraph Published["Published packages"] CORE["@capacitor/core"] CLI["@capacitor/cli"] IOS["@capacitor/ios"] AND["@capacitor/android"] end subgraph Generated["Generated artifacts"] NBJS["native-bridge.js"] TARS["cli/assets/*.tar.gz"] end subgraph Templates["Templates (not published directly)"] TA["android-template"] TS["ios-spm-template"] TP["ios-pods-template"] TC["capacitor-cordova-*-plugins"] end CORE -->|"build:nativebridge"| NBJS NBJS -->|"committed into"| IOS NBJS -->|"committed into"| AND IOS -.->|peerDependency| CORE AND -.->|peerDependency| CORE TA & TS & TP & TC -->|"pack-cli-assets.mjs"| TARS TARS -->|bundled in| CLI CLI -.->|"reads from node_modules at sync time"| IOS CLI -.->|"reads from node_modules at sync time"| AND ``` Key properties: - **No package imports another at compile time.** `@capacitor/ios` and `@capacitor/android` declare `@capacitor/core` only as a `peerDependency`, and never import it — the coupling is the injected `native-bridge.js` and the shape of the messages on the wire. `scripts/sync-peer-dependencies.mjs` keeps those peer ranges pinned to core's major/minor on every `lerna version`. - **The CLI does not depend on the platform packages either.** It resolves them from the *app's* `node_modules` at `sync`/`update` time (`resolveNode(config.app.rootDir, '@capacitor/android', …)`), so a given CLI version can drive a range of runtime versions. - **The only hard cross-package artifact is `native-bridge.js`**, which flows `core → ios` and `core → android` as a committed generated file. ### 3.2 `@capacitor/core` — public vs internal Public surface is exactly what `core/src/index.ts` re-exports: - `Capacitor` (the global instance) and `registerPlugin` - `WebPlugin` — the base class every web implementation extends - `CapacitorException`, `ExceptionCode` - The built-in plugin objects: `CapacitorHttp`, `CapacitorCookies`, `WebView`, `SystemBars`, plus `buildRequestInit` - Types: `CapacitorGlobal`, `Plugin`, `PluginListenerHandle`, `PluginCallback`, `PluginImplementations`, `PermissionState`, `PluginResultData`, `PluginResultError`, and the built-in plugins' option/result types Internal (not exported from the package entry point, no compatibility guarantee): - `core/src/definitions-internal.ts` — `CapacitorInstance`, `CallData`, `MessageCallData`, `ErrorCallData`, `PluginResult`, `StoredCallback`, `PluginHeader`, `WindowCapacitor`. This file is the **wire-format contract** with the native layers. - `core/src/runtime.ts` — `createCapacitor`/`initCapacitorGlobal`, the `Proxy` factory. - `core/native-bridge.ts` — exports `initBridge` only so the Jest suite can drive it (`// Export only for tests`); the rollup build strips exports entirely. `CapacitorInstance` extends the public `CapacitorGlobal` with the low-level members the native layers call into: `toNative`, `fromNative`, `nativeCallback`, `nativePromise`, `triggerEvent`, `createEvent`, `logJs`, `withPlugin`, `Plugins`, `PluginHeaders`. These are documented as internal but are effectively frozen API, because compiled native code in the wild calls them by name. ### 3.3 `@capacitor/ios` — public vs internal `Package.swift` defines five targets across three products: | Target | Language | Depends on | Notes | | --- | --- | --- | --- | | `CapacitorObjC` | ObjC | — | `CAPPlugin`, `CAPPluginCall`, `CAPPluginMethod`, `CAPBridgedPlugin`, `CAPInstanceDescriptor/Configuration`. Public headers under `include/Capacitor`. | | `Capacitor` | Swift | `CapacitorObjC` | The bridge, view controller, web view handlers, JS types, built-in plugins. Carries `assets/native-bridge.js` as a resource. | | `CapacitorObjCShims` | ObjC | `Capacitor` | Module map + shims that need the generated `Capacitor-Swift.h`. | | `Cordova` | ObjC | — | `CDV*` compatibility layer. | | `CapacitorCordova` | Swift | `Capacitor`, `Cordova` | Glue plugin. | The ObjC-first split breaks a dependency cycle: Swift code needs the ObjC plugin base classes, and some ObjC code needs Swift symbols. `CAPPlugin.h` stores the bridge as an untyped `NSObject *bridgeRef` so the ObjC target never has to see the Swift-defined `CAPBridgeProtocol`; the typed `bridge` accessor is vended from Swift in `CAPPlugin+Bridge.swift`. Public (plugin authors and app integrators depend on these): - `CAPBridgeViewController` (`open`) — subclass hooks: `instanceDescriptor()`, `webViewConfiguration(for:)`, `webView(with:configuration:)`, `router()`, `capacitorDidLoad()`. - `CapacitorBridge` (`open`) conforming to `CAPBridgeProtocol`. - `CAPPlugin`, `CAPPluginCall`, `CAPBridgedPlugin`, the `CAP_PLUGIN`/`CAP_PLUGIN_METHOD` macros, `CAPPluginMethod`. - `JSValueContainer`/`JSObject`/`JSValue`, `JSValueEncoder`/`JSValueDecoder`. - `WebViewAssetHandler`, `WebViewDelegationHandler` (both `open` — subclassable), `Router`/`CapacitorRouter`, `WebViewListener`-equivalent notifications in `CAPNotifications.swift`. - `SceneDelegateProxy` / `ApplicationDelegateProxy`. Internal: `JSExport` (`internal class`), `JSCall`/`JSResult`/`JSResultError` (`internal struct`s — `JSCall` itself is `public` but only produced by the bridge), `JSResultSerialization`, `KeyValueStore`, `AppUUID`. Verified against `ionic-team/capacitor-plugins`: no official plugin references any of them. ### 3.4 `@capacitor/android` — public vs internal Two Gradle modules (`android/settings.gradle`): - `:capacitor-android` → `android/capacitor`, namespace `com.getcapacitor.android` - `:capacitor-cordova-android` → `android/capacitor-cordova` Public: `Bridge` (+ `Bridge.Builder`), `BridgeActivity`, `Plugin`, `PluginCall`, `JSObject`/`JSArray`/`JSValue`, `PluginResult`, the annotations (`@CapacitorPlugin`, `@PluginMethod`, `@Permission`, `@PermissionCallback`, `@ActivityCallback`), `CapConfig`/`PluginConfig`, `WebViewListener`, `Logger`, `PermissionState`, `RouteProcessor`/`ProcessedRoute`, `ServerPath`, and `PluginHandle` (returned by `Bridge.getPlugin(String)`; official plugins such as `local-notifications` and `push-notifications` use it to reach a plugin instance from a static context). Internal in practice (Java `public` for cross-package access inside the library, but not a stable contract): `MessageHandler`, `JSExport`, `JSInjector` (package-private), `WebViewLocalServer`, `AndroidProtocolHandler`, `UriMatcher`, `PluginMethodHandle`, `PluginManager`, `BridgeWebViewClient`, `BridgeWebChromeClient`. Verified against `ionic-team/capacitor-plugins`: no official plugin references any of them. ### 3.5 `@capacitor/cli` — public vs internal `cli/package.json` publishes `dist/**/*.js` plus **only** `dist/declarations.d.ts`. That is deliberate: the CLI's public API is the *configuration schema* (`cli/src/declarations.ts` — `CapacitorConfig`, `PluginsConfig`, platform-specific option types), which apps import in `capacitor.config.ts`. Everything else is a private implementation detail reachable only through the `cap` binary. Requires Node `>=24`; `bin/capacitor` checks `process.version` against `engines.node` before loading `dist/index.js`. --- ## 4. Native bridge lifecycle ### 4.1 Bootstrap order Everything hinges on scripts landing in the right order *before* app code runs. ```mermaid flowchart TB A["Native host starts
CAPBridgeViewController.loadView / BridgeActivity.onCreate"] B["Load config
capacitor.config.json (+ Info.plist / assets)"] C["Create web view + configure it"] D["Register plugins
iOS: packageClassList · Android: capacitor.plugins.json"] E["Inject script 1: window.Capacitor global stub
DEBUG, isLoggingEnabled, empty Plugins
plus window.WEBVIEW_SERVER_URL"] F["Inject script 2: native-bridge.js
defines toNative/fromNative/nativePromise/…"] G["Inject script 3: per-plugin shims
window.Capacitor.Plugins.X + window.Capacitor.PluginHeaders"] H["Load app URL"] I["App bundle runs
@capacitor/core sees a populated window.Capacitor"] A --> B --> C --> D --> E --> F --> G --> H --> I ``` On iOS these are three `WKUserScript`s added at `.atDocumentStart` to the `WKUserContentController` (`JSExport.exportCapacitorGlobalJS`, `exportBridgeJS`, `exportJS(for:)`). On Android the same three strings are concatenated by `JSInjector` and installed either via `WebViewCompat.addDocumentStartJavaScript` (preferred, when the `DOCUMENT_START_SCRIPT` feature is available) or, as a fallback, spliced into the `` of the HTML response by `WebViewLocalServer`. Because `native-bridge.js` has already defined `window.Capacitor.toNative` and friends by the time the app bundle executes, `@capacitor/core`'s `createCapacitor(win)` finds an existing `win.Capacitor` and **augments** it rather than replacing it (`core/src/runtime.ts`: `const cap = win.Capacitor || {}`). ### 4.2 Message format Web → native (`core/src/definitions-internal.ts`): ```ts // type: 'message' (the normal plugin call) interface MessageCallData { type?: 'message'; callbackId: string; // '-1' means "fire and forget, no stored callback" pluginId: string; // the plugin's JS name, e.g. 'Camera' methodName: string; // e.g. 'getPhoto' options: any; // the single catch-all options object } // type: 'js.error' (uncaught window error, only when Capacitor.DEBUG) interface ErrorCallData { type: 'js.error'; error: { message: string; url: string; line: number; col: number; errorObject: string }; } ``` Native → web: ```ts interface PluginResult { callbackId?: string; pluginId?: string; methodName?: string; success: boolean; data: PluginResultData; // present when success error?: PluginResultError; // present when !success; { message, code?, … } save?: boolean; // true ⇒ keep the callback registered (listeners, callbacks) } ``` Transport differs per platform but the payload does not: | Direction | iOS | Android | | --- | --- | --- | | Web → native | `window.webkit.messageHandlers.bridge.postMessage(obj)` — a real object; `type` defaulted to `'message'` | `window.androidBridge.postMessage(JSON.stringify(obj))` — a string | | Native → web | `webView.evaluateJavaScript("window.Capacitor.fromNative({…})")` | `JavaScriptReplyProxy.postMessage(json)` → `androidBridge.onmessage` → `returnResult(JSON.parse(e.data))`; legacy fallback is `evaluateJavascript("window.Capacitor.fromNative(…)")` | | Sync web → native | `prompt(JSON.stringify({ type: … }))` intercepted in `runJavaScriptTextInputPanelWithPrompt` | dedicated `@JavascriptInterface` objects (`CapacitorCookiesAndroidInterface`, `CapacitorHttpAndroidInterface`) | The synchronous `prompt()` channel on iOS serves `document.cookie` and the "is CapacitorHttp enabled?" check, both of which must answer synchronously; `WKWebView` offers no synchronous message handler. #### What can cross the bridge **Only JSON-representable data.** The channel is a JSON string on Android and a JSON-compatible object on iOS; class instances, functions, `Blob`s, typed arrays and anything else with custom serialisation must be converted first (the `CapacitorHttp` patches in `native-bridge.ts` do exactly this, base64-encoding `File`s and draining `ReadableStream`s before they reach the bridge). iOS makes the contract explicit as the `JSValue` protocol in `JSTypes.swift`, which exactly these types conform to: ``` String · Bool · Int · Float · Double · NSNumber · NSNull · Date Array · Dictionary where Key == String, Value == JSValue ``` with `JSObject = [String: JSValue]` and `JSArray = [JSValue]`. Two consequences: - **`Date` is a first-class native value but not a JSON one.** Dates are converted to ISO 8601 strings in both directions — inbound by `JSTypes.coerceDictionaryToJSObject(_:formattingDatesAsStrings:)`, outbound by `JSResultSerialization`, which walks nested dictionaries and arrays. A plugin can opt out of inbound stringification with `shouldStringifyDatesInCalls` on `CAPPlugin`. - **`NSNull`, not `nil`.** Objective-C collections cannot hold `nil`, so JS `null` arrives as `NSNull`. Check the value's type rather than testing for key presence; `Array+Capacitor.swift` provides `replacingNullValues()` / `replacingOptionalValues()` to convert between `[JSValue]` and `[JSValue?]`. ### 4.3 Callback identity and async modes `cap.toNative()` in `core/native-bridge.ts` owns callback registration: - A module-level `Map` (`callbacks`) holds `StoredCallback` entries keyed by id. - `callbackIdCount` starts at `Math.floor(Math.random() * 134217728)` rather than `0`, so that a late result from a *previous* page load cannot collide with an id from the current one. - If no callback/resolver is supplied, the id is the sentinel `'-1'` and nothing is stored. Three calling conventions are generated from the plugin's declared return type: | Return type | JS entry point | Native declaration | | --- | --- | --- | | `promise` | `Capacitor.nativePromise(plugin, method, options)` | iOS: `CAP_PLUGIN_METHOD(x, CAPPluginReturnPromise)` / `CAPPluginMethod(_:returnType: .promise)`; Android: `@PluginMethod` (default) | | `callback` | `Capacitor.nativeCallback(plugin, method, options, cb)` | `CAPPluginReturnCallback` / `@PluginMethod(returnType = RETURN_CALLBACK)` | | `none` | `Capacitor.nativeCallback(plugin, method, options)` | `CAPPluginReturnNone` / `@PluginMethod(returnType = RETURN_NONE)` | Which convention a given `Plugins.X.y()` call uses is decided **on the native side** and shipped to JS as `window.Capacitor.PluginHeaders` — an array of `{ name, methods: [{ name, rtype? }] }`. `registerPlugin()` in `core/src/runtime.ts` consults that header to decide, per method, whether to route to `nativePromise`, `nativeCallback`, or a JS implementation: ``` createPluginMethod(impl, prop): if pluginHeader has method `prop`: rtype === 'promise' → nativePromise otherwise → nativeCallback else if a JS implementation for this platform exists → impl[prop] else → throw CapacitorException(UNIMPLEMENTED) ``` Every plugin object returned by `registerPlugin()` is a `Proxy`, so methods are materialised lazily on property access and a plugin never needs a hand-written JS surface. The proxy also special-cases `$$typeof` (returns `undefined`, so React does not mistake the proxy for an element) and `toJSON`. ### 4.4 Keeping calls alive A plugin call is released after its first result unless it opts in: - iOS: `call.keepAlive` → `bridge.saveCall(call)` after `perform`; the outgoing result carries `save: true`. - Android: `call.setKeepAlive(true)` → `bridge.saveCall(call)`; `MessageHandler` writes `data.put("save", call.isKeptAlive())`. On the JS side, `returnResult()` deletes the stored callback when a *promise* resolves, and additionally deletes it whenever `result.save === false`. This is how `addListener` works: the listener registration is a `keepAlive` call whose callback is invoked once per event. Bridge state is reset on every navigation — iOS `didStartProvisionalNavigation` → `bridge.reset()`, Android `onPageStarted` → `bridge.reset()` — which clears saved calls and removes all plugin listeners so a new page cannot receive the previous page's callbacks. ### 4.5 Round trip: web → native → web ```mermaid sequenceDiagram participant App as App code participant Core as core Proxy participant NB as native-bridge.js participant Chan as Web view channel participant Br as Bridge participant Pl as Plugin App->>Core: Camera.getPhoto(options) Core->>Core: look up PluginHeaders → rtype 'promise' Core->>NB: nativePromise('Camera','getPhoto',opts) NB->>NB: callbackId = String(++counter)
store resolve + reject under that id NB->>Chan: postMessage with callbackId, pluginId, methodName, options Chan->>Br: userContentController(didReceive:) / MessageHandler.postMessage Br->>Br: resolve plugin + method
build PluginCall (options coerced to JSObject) Br->>Pl: dispatch on plugin queue/HandlerThread Pl-->>Br: call.resolve(data) or call.reject(msg, code, err, data) Br->>Chan: fromNative with callbackId, success, data or error, save Chan->>NB: returnResult(result) alt success NB->>Core: storedCall.resolve(result.data) Core-->>App: Promise resolves else failure NB->>NB: rehydrate error onto new Capacitor.Exception NB->>Core: storedCall.reject(result.error) Core-->>App: Promise rejects end NB->>NB: delete callback (promise), then delete result.data and result.error ``` ### 4.6 Events: native → web Listener registration is itself a bridge call, so events ride the same channel as results — there is no separate event bus for plugin events. ```mermaid sequenceDiagram participant App as App code participant Core as core Proxy participant NB as native-bridge.js participant Br as Bridge participant Pl as Plugin App->>Core: await Network.addListener('networkStatusChange', cb) Core->>NB: nativeCallback('Network', 'addListener', eventName, cb) NB->>Br: postMessage with callbackId N and methodName 'addListener' Br->>Pl: addListener(call) Pl->>Pl: call.setKeepAlive(true), store call under event name Note over Pl: If events were retained before any listener existed,
they are flushed now (retainUntilConsumed) Pl->>Pl: notifyListeners('networkStatusChange', data) loop for each stored listener call Pl->>Br: call.resolve(data) Br->>NB: fromNative with callbackId N, success true, save true NB->>Core: storedCall.callback(data) Core-->>App: cb(data) end App->>Core: handle.remove() Core->>NB: nativeCallback('Network', 'removeListener', callbackId N) NB->>Br: postMessage(…) Br->>Pl: removeEventListener + releaseCall(N) ``` Separately, the native layers can push *document/window DOM events* (not plugin events) by evaluating `window.Capacitor.triggerEvent(name, target, data)` — `triggerWindowJSEvent` / `triggerDocumentJSEvent` on both platforms. This is how app lifecycle transitions (`resume`, `pause`) reach the page, and it routes through `cordova.fireDocumentEvent` when Cordova compatibility is present. ### 4.7 Error propagation - **Native rejection → JS rejection.** `call.reject(message, code, error, data)` serialises to `{ success: false, error: { message, errorMessage, code, …data } }`. In `returnResult()`, the plain error object is copied key-by-key onto a fresh `new cap.Exception('')` so the rejection carries a real stack and `instanceof Error` holds. `CapacitorException` exposes `code` (`ExceptionCode.Unimplemented` / `Unavailable`) and a free-form `data` bag. - **Unimplemented methods.** Web implementations call `this.unimplemented()` / `this.unavailable()` from `WebPlugin`. When no implementation exists at all for the active platform, the proxy throws `".() is not implemented on "` with code `UNIMPLEMENTED` before anything reaches the bridge. - **Result with no stored callback.** If a result arrives for an unknown `callbackId` and it is an error, `native-bridge.js` logs it with `console.warn` rather than dropping it silently. - **Serialisation failures.** iOS `JSResult.jsonPayload()` catches `JSONSerialization` failures and emits `{}` plus a targeted log naming the plugin and method. - **Native-side routing failures are logged, not surfaced.** If the plugin id is unknown or the selector does not exist, iOS `handleJSCall` logs and `return`s — the JS promise never settles. Android's `callPluginMethod` is stricter: an unknown plugin calls `call.errorCallback(...)`, so the promise rejects. - **JS errors → native log.** When `Capacitor.DEBUG` is set (iOS/Android debug builds), `window.onerror` is wired to `cap.handleWindowError`, which posts a `{ type: 'js.error' }` message. iOS renders it as the "STARTUP JS ERROR" block; Android logs it through the `js.error` interceptor. - **Console bridging (iOS only).** `debug/error/info/log/trace/warn` on `window.console` are wrapped to also `toNative('Console', 'log', …)`, so web logs appear in Xcode. Android gets this for free from `BridgeWebChromeClient`. ### 4.8 Threading | | iOS | Android | | --- | --- | --- | | Inbound message received on | main thread (`WKScriptMessageHandler`) | the WebView/UI thread (`@JavascriptInterface` or `WebMessageListener`) | | Plugin method executes on | `bridge.dispatchQueue` — a **serial** `DispatchQueue(label: "bridge")` | `taskHandler`, a `Handler` on a **single** `HandlerThread("CapacitorPlugins")` | | Hop to main/UI | `DispatchQueue.main.async` (the bridge does this for you in `toJs`, `eval`, `triggerJSEvent`, `logToJs`) | `bridge.executeOnMainThread(Runnable)`; `eval()` posts to `context.getMainLooper()` | | Hop back to background | `bridge.getDispatchQueue()` | `bridge.execute(Runnable)` | | Result delivery | `evaluateJavaScript` on main | `replyProxy.postMessage` from the calling thread, or `webView.post(…)` for the legacy `evaluateJavascript` path | | Stored-call storage | `ConcurrentDictionary` (lock-guarded) | plain `HashMap` mutated from the plugin thread | **Both platforms run every plugin method on one shared serial queue.** A plugin method that blocks stalls every other plugin. Long work must be dispatched onward, and the `PluginCall` resolved from the completion. #### Why GCD and not Swift concurrency The iOS column above is entirely Grand Central Dispatch because **the runtime is still Swift 5 and has not adopted strict concurrency.** `Package.swift` declares `swift-tools-version: 6.0` but pins the language mode back with `swiftLanguageModes: [.v5]` at package level and `.swiftLanguageMode(.v5)` on every Swift target; `Capacitor.podspec` declares `swift_version = '5.1'`. Tools version 6 does not imply Swift 6 semantics here. Across `ios/Sources/` there is no `async func`, `await`, `actor`, `Sendable`, `nonisolated` or `@preconcurrency`. The single `@MainActor` is in a WebKit-imposed `WKNavigationDelegate` signature, not an adoption of actor isolation. Grepping for `async` in this codebase finds GCD (`DispatchQueue.main.async`, `dispatchQueue.async`), not Swift concurrency. Two consequences run through the design: - **Shared mutable state is guarded by hand, not by actor isolation.** The bridge's `storedCalls` uses `ConcurrentDictionary` (`KeyValueStore.swift`), an `NSLock` behind a `withLock` accessor. - **Asynchrony is expressed as escaping completion closures**, which is also what the `@objc`-exported plugin surface can represent — `CAPPluginCall` carries `successHandler`/`errorHandler` rather than returning a value, and that shape is what lets the same call be resolved once, repeatedly (`keepAlive`), or from any thread. Moving to Swift 6 language mode or enabling strict concurrency would be a deliberate, wide-reaching migration rather than an incremental cleanup. `AGENTS.md` carries the working rules for contributors. --- ### 4.9 CapacitorHttp and cookie interception The largest single body of code in `core/native-bridge.ts` is not the bridge itself — it is the optional interception of `fetch`, `XMLHttpRequest` and `document.cookie`. Both are **off by default** and gated on config: | Switch | Effect when `true` | | --- | --- | | `plugins.CapacitorHttp.enabled` | Patches `window.fetch` and `window.XMLHttpRequest` | | `plugins.CapacitorCookies.enabled` | Redefines the `document.cookie` property descriptor | The web layer must know the switch state *before* any app script runs, which is why the check is synchronous: on iOS via the `prompt()` channel (`{ type: 'CapacitorHttp' }`, `{ type: 'CapacitorCookies.isEnabled' }`), on Android via the `@JavascriptInterface` methods `CapacitorHttpAndroidInterface.isEnabled()` and `CapacitorCookiesAndroidInterface.isEnabled()`. Both interfaces are installed by the plugins themselves in `load()` — see `CapacitorHttp.java` and `CapacitorCookies.java`. Before patching, the originals are stashed on `window` as `CapacitorWebFetch` and `CapacitorWebXMLHttpRequest`, so the patched implementations can delegate. **Two routes for an intercepted request.** Which one a request takes depends on its method: - **`GET` / `HEAD` / `OPTIONS` / `TRACE`** are rewritten to a proxy URL at the app's own origin — `/_capacitor_http_interceptor_?u=` — and sent through the *original* `fetch`. The native asset handler recognises the path and performs the request natively: `WebViewAssetHandler.handleCapacitorHttpRequest` on iOS, `WebViewLocalServer.shouldInterceptRequest` on Android. Keeping these on the URL-loading path preserves streaming and the normal response pipeline. - **Everything else** goes over the bridge as an ordinary plugin call to `CapacitorHttp.request`, and the response is reassembled into a `Response` (or applied to the XHR instance) in JS. Request bodies are normalised first by `convertBody()`: `File` and `FormData` entries are base64-encoded, `ReadableStream`s are drained. Native ends: `CAPHttpPlugin` (`ios/Sources/Capacitor/Plugins/CapacitorHttp.swift`, `jsName` `CapacitorHttp`) with `CapacitorUrlRequest`/`HttpRequestHandler`, and `CapacitorHttp.java` with `CapacitorHttpUrlConnection`/`HttpRequestHandler`. Cookies are handled by `CAPCookiesPlugin`/`CapacitorCookieManager.swift` and `CapacitorCookies.java`/`CapacitorCookieManager.java`. **What enabling these bypasses.** A request made natively is not subject to the web view's CORS enforcement, and it does not use the web view's cookie jar — it uses the platform HTTP stack and `HTTPCookieStorage`/`CookieManager`. That is the point (it is how apps call APIs that do not serve CORS headers), but it means a request that works in the app will not necessarily work in a browser, and vice versa. Two platform-specific wrinkles: Android strips a caller-set `User-Agent`, so the patch forwards it as `x-cap-user-agent` ([crbug 40450316](https://issues.chromium.org/issues/40450316)); and Android cannot filter `httpOnly` cookies, so its `document.cookie` getter returns the original descriptor's value rather than a native-filtered list. The proxy path is also a navigation hazard: because it returns a *remote* body at the app's own origin, both platforms explicitly block navigating to it — see §5.6 and §6.4. --- ## 5. iOS internals ### 5.1 Hosting: SwiftUI front door, UIKit engine As of Capacitor 9 the generated app is a SwiftUI `App` struct. The templates ship: ```swift // App.swift @main struct CapacitorApp: App { @UIApplicationDelegateAdaptor(AppDelegate.self) var appDelegate var body: some Scene { WindowGroup { CapacitorView() .ignoresSafeArea() .onOpenURL { url in SceneDelegateProxy.shared.handle(openURL: url) } .onContinueUserActivity(NSUserActivityTypeBrowsingWeb) { activity in SceneDelegateProxy.shared.handle(userActivity: activity) } } } } // CapacitorView.swift public struct CapacitorView: UIViewControllerRepresentable { public func makeUIViewController(context: Context) -> CAPBridgeViewController { CAPBridgeViewController() } public func updateUIViewController(_ vc: CAPBridgeViewController, context: Context) {} } // SceneDelegate.swift — deliberately empty class SceneDelegate: UIResponder, UIWindowSceneDelegate {} ``` `SceneDelegate` carries no methods. It exists because `UISceneConfiguration.delegateClass` takes a type and UIKit instantiates it per scene, so there is no way to hand UIKit `SceneDelegateProxy.shared` — the app target has to own a concrete class for `AppDelegate` to name from `application(_:configurationForConnecting:options:)`. It is the install point for per-scene UIKit APIs SwiftUI does not surface, the first of which is `preferredWindowingControlStyle(for:)` for the iPadOS 26 window controls. It stays empty of routing on purpose: a scene delegate that implements `scene(_:openURLContexts:)` takes URL delivery away from `.onOpenURL` below. `AppDelegate` forwards `application(_:supportedInterfaceOrientationsFor:)` to `ApplicationDelegateProxy.shared`. The bridge is a child of SwiftUI's hosting controller rather than the window's root view controller, so UIKit never asks `CAPBridgeViewController` for `supportedInterfaceOrientations`, and a `ScreenOrientation.lock()` would only hold until the next device rotation. The proxy returns the bridge's orientations, unless a full-screen presentation is on top, in which case it returns the Info.plist orientations and lets the presented controller decide, as UIKit does when the bridge is the root. It does the same when a presented controller shares no orientation with the bridge (UIKit also asks `.custom` presentations, and no orientation in common crashes), and when the bridge's orientations are empty. `CapacitorView` lives in the app target, not the runtime. An app that needs its own `CAPBridgeViewController` subclass (custom `webViewConfiguration(for:)`, `router()`, `capacitorDidLoad()`) returns that subclass from `makeUIViewController`. This replaces the storyboard custom-class approach used in Capacitor 8 and earlier. The engine is still `CAPBridgeViewController`, a `UIViewController`. SwiftUI's `.onOpenURL` / `.onContinueUserActivity` do not surface a `UIScene`, so `SceneDelegateProxy.handle(openURL:scene:)` resolves the active foreground `UIWindowScene` from `UIApplication.shared.connectedScenes` when none is passed, then posts both the scene-aware notifications (`.capacitorSceneOpenURL`, `.capacitorSceneOpenUniversalLink`) and the Capacitor 8 back-compat ones (`.capacitorOpenURL`, `.capacitorOpenUniversalLink`). Plugins listening on either name keep working. On cold start, plugins are not yet registered when `scene(_:willConnectTo:)` fires, so queued URLs/activities are replayed on the first `.capacitorViewDidAppear`. ### 5.2 View controller lifecycle `CAPBridgeViewController.loadView()` (note: `final`) does the work, in order: 1. `instanceDescriptor()` → `InstanceConfiguration(with:isDebug:)`; set `CAPLog.enableLogging`; log config warnings. 2. Status bar and orientation defaults from `Info.plist`. 3. Build `WebViewAssetHandler(router: router())`, point it at the app location and server URL. 4. Build `WebViewDelegationHandler()` (which creates the `WKUserContentController` and registers itself as the `"bridge"` script message handler). 5. `prepareWebView(...)` — see below. 6. `view = webView`. 7. Construct `CapacitorBridge(with:delegate:assetHandler:delegationHandler:)`. 8. `capacitorDidLoad()` subclass hook, then `updateAppLocationIfNeeded()` (live-updates snapshot path). `viewDidLoad()` then calls `loadWebView()`, which `exit(1)`s with a diagnostic if `config.appStartFileURL` does not exist (a missing `npx cap copy`), otherwise loads `config.appStartServerURL`. ### 5.3 Web view configuration `webViewConfiguration(for:)` is `open` and intended to be overridden by calling `super` and mutating the result. Defaults set in the base implementation: - `websiteDataStore.httpCookieStore.add(CapacitorWKCookieObserver())` - `allowsInlineMediaPlayback = true`, `mediaTypesRequiringUserActionForPlayback = []`, `allowsAirPlayForMediaPlayback = true`, `suppressesIncrementalRendering = false` - `preferences.isElementFullscreenEnabled = true` - `limitsNavigationsToAppBoundDomains` from config - `applicationNameForUserAgent` appended from `appendedUserAgentString` - `defaultWebpagePreferences.preferredContentMode` from `preferredContentMode` (`mobile` / `desktop` / recommended) `prepareWebView(...)` then wires the pieces that must not be overridden loosely: - `setURLSchemeHandler(assetHandler, forURLScheme: localURL.scheme ?? "capacitor")` - `userContentController = delegationHandler.contentController` - `uiDelegate` and `navigationDelegate` = the delegation handler; `scrollView.delegate` too when zooming is disabled (that is how pinch-zoom is suppressed) - scroll bounce off, `contentInsetAdjustmentBehavior`, `allowsLinkPreview`, `isScrollEnabled`, custom user agent, background colour (falls back to `UIColor.systemBackground`), `setKeyboardShouldRequireUserInteraction(false)` - `HTTPCookieStorage.shared.cookieAcceptPolicy = .always` Web inspector: `webView.isInspectable = config.isWebDebuggable` on iOS 16.4+; older systems get a warning that the flag has no effect. ### 5.4 Plugin registration and the ObjC bridge Plugins are ObjC classes (or `@objc`-exposed Swift classes) conforming to `CAPBridgedPlugin`, which requires `identifier`, `jsName`, and `pluginMethods`. The `CAP_PLUGIN` macro generates that conformance as a category: ```objc CAP_PLUGIN(CAPCameraPlugin, "Camera", CAP_PLUGIN_METHOD(getPhoto, CAPPluginReturnPromise); ) ``` Swift plugins can build `pluginMethods` directly with `CAPPluginMethod(#selector(MyPlugin.getPhoto), returnType: .promise)`. At startup `registerPlugins()`: 1. Always registers the built-ins: `CAPHttpPlugin`, `CAPConsolePlugin`, `CAPWebViewPlugin`, `CAPCookiesPlugin`, `CAPSystemBarsPlugin`. 2. If `autoRegisterPlugins` (the default), reads `packageClassList` from the bundled `capacitor.config.json` and resolves each entry through `NSClassFromString`. The CLI populates that list during `cap copy`/`update` by scanning plugin sources for `@objc(Name)` and `CAP_PLUGIN(Name`. 3. Instantiates each, calls `plugin.load(on:)`, stores it in `plugins[jsName]`, and emits its JS shim via `JSExport.exportJS(for:in:)`. Apps that want explicit control set `autoRegisterPlugins = false` and call `registerPluginType(_:)` / `registerPluginInstance(_:)`. `CAPInstancePlugin` subclasses are skipped by auto-registration and must be registered as instances. ### 5.5 Dispatching a call `WebViewDelegationHandler.userContentController(_:didReceive:)` inspects `body["type"]`: - `"js.error"` → `logJSError` - `"message"` → build a `JSCall` and hand it to `bridge.handleJSCall` - anything else → look up `bridge.callInterceptors[type]` (registered via `registerCallInterceptor(_:handler:)`) — this is the extension point plugins use for custom synchronous-ish channels. `handleJSCall` resolves the plugin (falling back to `NSClassFromString(call.pluginId)` + `loadPlugin` for lazily-loaded plugins), computes the selector — `addListener`, `removeListener` and `removeAllListeners` get `NSSelectorFromString(method + ":")`, everything else comes from `plugin.getMethod(named:)` — checks `responds(to:)`, and only then hops to the serial `dispatchQueue`. Options are coerced with `JSTypes.coerceDictionaryToJSObject(_:formattingDatesAsStrings:)` before the `CAPPluginCall` is constructed, so plugins receive normalised `JSObject` values. Results go back through `toJs` / `toJsError`, both of which build a JS literal and `evaluateJavaScript` it on the main queue. ### 5.6 Assets, schemes and navigation `WebViewAssetHandler` is a `WKURLSchemeHandler` registered for the configured scheme (default `capacitor://localhost`). It: - Short-circuits paths starting with `/_capacitor_http_interceptor_` into `handleCapacitorHttpRequest`, which performs the request natively (this is the fast path for `GET`/`HEAD`/`OPTIONS`/`TRACE` when `CapacitorHttp` is enabled). - Otherwise maps the URL through the `Router` — `CapacitorRouter` rewrites any extension-less path to `/index.html`, which is what makes SPA client-side routing work. - Resolves MIME types and streams the file from `config.appLocation`. `decidePolicyFor navigationAction` enforces, in order: 1. Cancel anything under `/_capacitor_http_interceptor_` (the proxy returns a *remote* body at the app origin, so it must never become a document navigation). 2. Give every plugin a chance via `shouldOverrideLoad:` (`nil` = defer, `true` = cancel, `false` = allow). 3. Allow if the host matches `server.allowNavigation`. 4. For top-level navigations outside `serverURL`/`localURL`, cancel and hand the URL to `UIApplication.shared.open` — external links open in Safari, not in the app's web view. Also handled here: media-capture and device-motion permission prompts (auto-granted at the WebKit layer; the OS prompt still applies), `didFail`/`didFailProvisionalNavigation` → load `config.errorPathURL`, and `webViewWebContentProcessDidTerminate` → `reset()` + `reload()`. ### 5.7 Distribution shapes - **SwiftPM (default)**: the manifest vends `Capacitor`, `Cordova` and `CapacitorCordova`. The generated app carries a local `CapApp-SPM` package that depends on the installed `@capacitor/ios` by path (`../../../node_modules/@capacitor/ios`) and on each plugin's own `Package.swift`. - **CocoaPods**: `ios/Capacitor.podspec` and `ios/CapacitorCordova.podspec` point at `Sources/` (with an `ios/` prefix when `NATIVE_PUBLISH=true`, because trunk publishes from the repo root while apps consume the npm package). The `Capacitor` podspec excludes the SPM-only `Capacitor-Swift.h` shim, since CocoaPods generates the real one. ### 5.8 Permissions (iOS) iOS has no permission *framework* in Capacitor — the OS prompts are issued by whichever system API the plugin calls. What the bridge provides is the shape. `JSExport.createPluginHeader(for:)` adds `checkPermissions` and `requestPermissions` to every plugin's `PluginHeaders` entry as `promise` methods, whether or not the plugin declares them. That means `SomePlugin.checkPermissions()` always routes to native and always resolves. The defaults live in `CAPPlugin+Bridge.swift` and both simply resolve with no data: ```swift @objc extension CAPPlugin { open func checkPermissions(_ call: CAPPluginCall) { call.resolve() } open func requestPermissions(_ call: CAPPluginCall) { call.resolve() } } ``` They are `open`, so a plugin overrides them to report real state — conventionally a dictionary of alias → `PermissionState` (`'prompt' | 'prompt-with-rationale' | 'granted' | 'denied'`, the same string union `@capacitor/core` exports). A plugin that needs no permissions inherits the defaults and resolves empty. The consequence worth knowing: because the header entries are synthesised unconditionally, a missing override is indistinguishable from "no permissions required" at the JS boundary. There is no build-time check that a plugin requiring camera access actually reports it. --- ## 6. Android internals ### 6.1 Activity and bridge construction `BridgeActivity.onCreate` sets the theme, inflates `R.layout.capacitor_bridge_layout_main` (falling back to `R.layout.no_webview` if the system WebView is missing), loads plugin classes from `assets/capacitor.plugins.json` via `PluginManager`, and calls `Bridge.Builder.create()`. The `Bridge` constructor, in order: 1. Start `HandlerThread("CapacitorPlugins")`; create `taskHandler` on its looper. 2. Load `CapConfig` (default: `assets/capacitor.config.json`); init `Logger`. 3. `initWebView()` — `WebSettings`: JavaScript enabled, DOM storage, geolocation, `setMediaPlaybackRequiresUserGesture(false)`, `setJavaScriptCanOpenWindowsAutomatically(true)`, optional mixed content, user-agent append/override, background colour, zoom controls, `setWebContentsDebuggingEnabled`. Also computes `localUrl`/`appUrl` from scheme + hostname (default `https://localhost`, from `CapConfig.androidScheme`) or from `server.url`, and appends `server.startPath` if configured. 4. `setAllowedOriginRules()` — the origin allowlist used by the `WebMessageListener`. 5. Construct `MessageHandler`. 6. `registerAllPlugins()` — built-ins `CapacitorCookies`, `WebView`, `CapacitorHttp`, `SystemBars`, then app plugin classes and instances. 7. `loadWebView()` — install the document-start script, start `WebViewLocalServer`, set `BridgeWebChromeClient`/`BridgeWebViewClient`, optionally install a `ServiceWorkerClient`, apply any persisted live-update server path, verify the system WebView meets `minWebViewVersion` (default 60; Huawei 10), then `loadUrl(appUrl)`. `Bridge` is constructed only through `Bridge.Builder`, which also registers the two built-in message interceptors: ```java bridge.registerInterceptor("message", postData -> { … new PluginCall(…); bridge.callPluginMethod(…); }); bridge.registerInterceptor("js.error", postData -> Logger.error("JavaScript Error: " + postData)); ``` Additional interceptors can be registered by plugins for custom message types — the Android analogue of iOS's `registerCallInterceptor`. ### 6.2 The message channel `MessageHandler`'s constructor picks a transport: ```java if (WebViewFeature.isFeatureSupported(WEB_MESSAGE_LISTENER) && !config.isUsingLegacyBridge()) { WebViewCompat.addWebMessageListener(webView, "androidBridge", bridge.getAllowedOriginRules(), capListener); } else { webView.addJavascriptInterface(this, "androidBridge"); // legacy } ``` The modern path is origin-scoped and gives a `JavaScriptReplyProxy` for responses; it also rejects messages from sub-frames (`Plugin execution is allowed in Main Frame only`). The legacy `@JavascriptInterface` path is used when the feature is unavailable, when `addWebMessageListener` throws, or when the app opts into `android.useLegacyBridge`. Either way the JS side only ever sees `window.androidBridge.postMessage(...)`. Responses take the inverse path in `sendResponseMessage`: `replyProxy.postMessage(json)` when available (received by `androidBridge.onmessage` in `native-bridge.js`), otherwise `webView.post(() -> webView.evaluateJavascript("window.Capacitor.fromNative(" + json + ")", null))`. A call whose `callbackId` is the dangling sentinel `"-1"` is routed to `bridge.getApp().fireRestoredResult(data)` — that is the process-death restoration path, where a result arrives for a call whose JS callback no longer exists. ### 6.3 Plugin model ```java @CapacitorPlugin( name = "Camera", permissions = { @Permission(strings = { Manifest.permission.CAMERA }, alias = "camera") } ) public class CameraPlugin extends Plugin { @PluginMethod // returnType defaults to "promise" public void getPhoto(PluginCall call) { … call.resolve(result); } } ``` - `PluginHandle` indexes every `public` method annotated with `@PluginMethod` by name at registration time (`Class.getMethods()` + annotation scan), then invokes by reflection. - `@PermissionCallback` and `@ActivityCallback` mark the methods the AndroidX `ActivityResult`/permission flows call back into; `Bridge.registerForActivityResult` wires the launchers in `initializeActivityLaunchers()`. - `@CapacitorPlugin(requestCodes = …)` is the deprecated legacy path, kept so plugins wrapping third-party SDKs that still use `onActivityResult` request codes keep working. `BridgeActivity` tries the legacy route first and falls through to the AndroidX flow. - Events use `notifyListeners(eventName, data, retainUntilConsumed)`; retained events are flushed when the first listener for that event registers. ### 6.4 Asset serving and the local server `BridgeWebViewClient.shouldInterceptRequest` delegates everything to `WebViewLocalServer.shouldInterceptRequest`, which handles: - `/_capacitor_http_interceptor_?u=` → native HTTP fetch (the `CapacitorHttp` proxy) - `/_capacitor_file_` → a file on disk, `/_capacitor_content_` → a `content://` URI - ordinary asset paths, served by `AndroidProtocolHandler` from `app/src/main/assets/public`, with `html5mode` falling back to `index.html` - injecting the Capacitor bootstrap `