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 first. This is a
contributor-facing document — for end-user documentation see
capacitorjs.com/docs.
- 1. What Capacitor is, structurally
- 2. Repository layout
- 3. Package boundaries
- 4. Native bridge lifecycle
- 5. iOS internals
- 6. Android internals
- 7. Web and custom platforms
- 8. Configuration flow
- 9. Build pipeline
- 10. Release process
- 11. Testing and CI
- 12. Invariants and gotchas
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:
@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.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/coremodule graph. It is compiled intoandroid/capacitor/src/main/assets/native-bridge.jsandios/Sources/Capacitor/assets/native-bridge.jsas generated, committed artifacts.
graph TB
subgraph WebView["Web view (one JS realm)"]
APP["App code<br/><i>import Camera from '@capacitor/camera'</i>"]
CORE["@capacitor/core<br/><i>registerPlugin() → Proxy</i>"]
GLOBAL["window.Capacitor<br/><i>global instance</i>"]
NB["native-bridge.js<br/><i>injected at document-start</i>"]
SHIM["Per-plugin JS shims + PluginHeaders<br/><i>generated by native JSExport</i>"]
end
subgraph Native["Native host process"]
BRIDGE["CapacitorBridge (iOS)<br/>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
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.
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/iosand@capacitor/androiddeclare@capacitor/coreonly as apeerDependency, and never import it — the coupling is the injectednative-bridge.jsand the shape of the messages on the wire.scripts/sync-peer-dependencies.mjskeeps those peer ranges pinned to core's major/minor on everylerna version. - The CLI does not depend on the platform packages either. It resolves them from the
app's
node_modulesatsync/updatetime (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 flowscore → iosandcore → androidas a committed generated file.
Public surface is exactly what core/src/index.ts re-exports:
Capacitor(the global instance) andregisterPluginWebPlugin— the base class every web implementation extendsCapacitorException,ExceptionCode- The built-in plugin objects:
CapacitorHttp,CapacitorCookies,WebView,SystemBars, plusbuildRequestInit - 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, theProxyfactory.core/native-bridge.ts— exportsinitBridgeonly 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.
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 toCAPBridgeProtocol.CAPPlugin,CAPPluginCall,CAPBridgedPlugin, theCAP_PLUGIN/CAP_PLUGIN_METHODmacros,CAPPluginMethod.JSValueContainer/JSObject/JSValue,JSValueEncoder/JSValueDecoder.WebViewAssetHandler,WebViewDelegationHandler(bothopen— subclassable),Router/CapacitorRouter,WebViewListener-equivalent notifications inCAPNotifications.swift.SceneDelegateProxy/ApplicationDelegateProxy.
Internal: JSExport (internal class), JSCall/JSResult/JSResultError
(internal structs — 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.
Two Gradle modules (android/settings.gradle):
:capacitor-android→android/capacitor, namespacecom.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.
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.
Everything hinges on scripts landing in the right order before app code runs.
flowchart TB
A["Native host starts<br/>CAPBridgeViewController.loadView / BridgeActivity.onCreate"]
B["Load config<br/>capacitor.config.json (+ Info.plist / assets)"]
C["Create web view + configure it"]
D["Register plugins<br/>iOS: packageClassList · Android: capacitor.plugins.json"]
E["Inject script 1: window.Capacitor global stub<br/>DEBUG, isLoggingEnabled, empty Plugins<br/>plus window.WEBVIEW_SERVER_URL"]
F["Inject script 2: native-bridge.js<br/>defines toNative/fromNative/nativePromise/…"]
G["Inject script 3: per-plugin shims<br/>window.Capacitor.Plugins.X + window.Capacitor.PluginHeaders"]
H["Load app URL"]
I["App bundle runs<br/>@capacitor/core sees a populated window.Capacitor"]
A --> B --> C --> D --> E --> F --> G --> H --> I
On iOS these are three WKUserScripts 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 <head>
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 || {}).
Web → native (core/src/definitions-internal.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:
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.
Only JSON-representable data. The channel is a JSON string on Android and a
JSON-compatible object on iOS; class instances, functions, Blobs, typed arrays and
anything else with custom serialisation must be converted first (the CapacitorHttp
patches in native-bridge.ts do exactly this, base64-encoding Files and draining
ReadableStreams 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:
Dateis a first-class native value but not a JSON one. Dates are converted to ISO 8601 strings in both directions — inbound byJSTypes.coerceDictionaryToJSObject(_:formattingDatesAsStrings:), outbound byJSResultSerialization, which walks nested dictionaries and arrays. A plugin can opt out of inbound stringification withshouldStringifyDatesInCallsonCAPPlugin.NSNull, notnil. Objective-C collections cannot holdnil, so JSnullarrives asNSNull. Check the value's type rather than testing for key presence;Array+Capacitor.swiftprovidesreplacingNullValues()/replacingOptionalValues()to convert between[JSValue]and[JSValue?].
cap.toNative() in core/native-bridge.ts owns callback registration:
- A module-level
Map(callbacks) holdsStoredCallbackentries keyed by id. callbackIdCountstarts atMath.floor(Math.random() * 134217728)rather than0, 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.
A plugin call is released after its first result unless it opts in:
- iOS:
call.keepAlive→bridge.saveCall(call)afterperform; the outgoing result carriessave: true. - Android:
call.setKeepAlive(true)→bridge.saveCall(call);MessageHandlerwritesdata.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.
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)<br/>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<br/>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
Listener registration is itself a bridge call, so events ride the same channel as results — there is no separate event bus for plugin events.
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,<br/>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.
- Native rejection → JS rejection.
call.reject(message, code, error, data)serialises to{ success: false, error: { message, errorMessage, code, …data } }. InreturnResult(), the plain error object is copied key-by-key onto a freshnew cap.Exception('')so the rejection carries a real stack andinstanceof Errorholds.CapacitorExceptionexposescode(ExceptionCode.Unimplemented/Unavailable) and a free-formdatabag. - Unimplemented methods. Web implementations call
this.unimplemented()/this.unavailable()fromWebPlugin. When no implementation exists at all for the active platform, the proxy throws"<Plugin>.<method>() is not implemented on <platform>"with codeUNIMPLEMENTEDbefore anything reaches the bridge. - Result with no stored callback. If a result arrives for an unknown
callbackIdand it is an error,native-bridge.jslogs it withconsole.warnrather than dropping it silently. - Serialisation failures. iOS
JSResult.jsonPayload()catchesJSONSerializationfailures 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
handleJSCalllogs andreturns — the JS promise never settles. Android'scallPluginMethodis stricter: an unknown plugin callscall.errorCallback(...), so the promise rejects. - JS errors → native log. When
Capacitor.DEBUGis set (iOS/Android debug builds),window.onerroris wired tocap.handleWindowError, which posts a{ type: 'js.error' }message. iOS renders it as the "STARTUP JS ERROR" block; Android logs it through thejs.errorinterceptor. - Console bridging (iOS only).
debug/error/info/log/trace/warnonwindow.consoleare wrapped to alsotoNative('Console', 'log', …), so web logs appear in Xcode. Android gets this for free fromBridgeWebChromeClient.
| 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<CAPPluginCall> (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.
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
storedCallsusesConcurrentDictionary(KeyValueStore.swift), anNSLockbehind awithLockaccessor. - Asynchrony is expressed as escaping completion closures, which is also what the
@objc-exported plugin surface can represent —CAPPluginCallcarriessuccessHandler/errorHandlerrather 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.
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/TRACEare rewritten to a proxy URL at the app's own origin —/_capacitor_http_interceptor_?u=<encoded url>— and sent through the originalfetch. The native asset handler recognises the path and performs the request natively:WebViewAssetHandler.handleCapacitorHttpRequeston iOS,WebViewLocalServer.shouldInterceptRequeston 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 aResponse(or applied to the XHR instance) in JS. Request bodies are normalised first byconvertBody():FileandFormDataentries are base64-encoded,ReadableStreams 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); 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.
As of Capacitor 9 the generated app is a SwiftUI App struct. The templates ship:
// 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.
CAPBridgeViewController.loadView() (note: final) does the work, in order:
instanceDescriptor()→InstanceConfiguration(with:isDebug:); setCAPLog.enableLogging; log config warnings.- Status bar and orientation defaults from
Info.plist. - Build
WebViewAssetHandler(router: router()), point it at the app location and server URL. - Build
WebViewDelegationHandler()(which creates theWKUserContentControllerand registers itself as the"bridge"script message handler). prepareWebView(...)— see below.view = webView.- Construct
CapacitorBridge(with:delegate:assetHandler:delegationHandler:). capacitorDidLoad()subclass hook, thenupdateAppLocationIfNeeded()(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.
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 = falsepreferences.isElementFullscreenEnabled = truelimitsNavigationsToAppBoundDomainsfrom configapplicationNameForUserAgentappended fromappendedUserAgentStringdefaultWebpagePreferences.preferredContentModefrompreferredContentMode(mobile/desktop/ recommended)
prepareWebView(...) then wires the pieces that must not be overridden loosely:
setURLSchemeHandler(assetHandler, forURLScheme: localURL.scheme ?? "capacitor")userContentController = delegationHandler.contentControlleruiDelegateandnavigationDelegate= the delegation handler;scrollView.delegatetoo when zooming is disabled (that is how pinch-zoom is suppressed)- scroll bounce off,
contentInsetAdjustmentBehavior,allowsLinkPreview,isScrollEnabled, custom user agent, background colour (falls back toUIColor.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.
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:
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():
- Always registers the built-ins:
CAPHttpPlugin,CAPConsolePlugin,CAPWebViewPlugin,CAPCookiesPlugin,CAPSystemBarsPlugin. - If
autoRegisterPlugins(the default), readspackageClassListfrom the bundledcapacitor.config.jsonand resolves each entry throughNSClassFromString. The CLI populates that list duringcap copy/updateby scanning plugin sources for@objc(Name)andCAP_PLUGIN(Name. - Instantiates each, calls
plugin.load(on:), stores it inplugins[jsName], and emits its JS shim viaJSExport.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.
WebViewDelegationHandler.userContentController(_:didReceive:) inspects body["type"]:
"js.error"→logJSError"message"→ build aJSCalland hand it tobridge.handleJSCall- anything else → look up
bridge.callInterceptors[type](registered viaregisterCallInterceptor(_: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.
WebViewAssetHandler is a WKURLSchemeHandler registered for the configured scheme
(default capacitor://localhost). It:
- Short-circuits paths starting with
/_capacitor_http_interceptor_intohandleCapacitorHttpRequest, which performs the request natively (this is the fast path forGET/HEAD/OPTIONS/TRACEwhenCapacitorHttpis enabled). - Otherwise maps the URL through the
Router—CapacitorRouterrewrites 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:
- Cancel anything under
/_capacitor_http_interceptor_(the proxy returns a remote body at the app origin, so it must never become a document navigation). - Give every plugin a chance via
shouldOverrideLoad:(nil= defer,true= cancel,false= allow). - Allow if the host matches
server.allowNavigation. - For top-level navigations outside
serverURL/localURL, cancel and hand the URL toUIApplication.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().
- SwiftPM (default): the manifest vends
Capacitor,CordovaandCapacitorCordova. The generated app carries a localCapApp-SPMpackage that depends on the installed@capacitor/iosby path (../../../node_modules/@capacitor/ios) and on each plugin's ownPackage.swift. - CocoaPods:
ios/Capacitor.podspecandios/CapacitorCordova.podspecpoint atSources/(with anios/prefix whenNATIVE_PUBLISH=true, because trunk publishes from the repo root while apps consume the npm package). TheCapacitorpodspec excludes the SPM-onlyCapacitor-Swift.hshim, since CocoaPods generates the real one.
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:
@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.
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:
- Start
HandlerThread("CapacitorPlugins"); createtaskHandleron its looper. - Load
CapConfig(default:assets/capacitor.config.json); initLogger. initWebView()—WebSettings: JavaScript enabled, DOM storage, geolocation,setMediaPlaybackRequiresUserGesture(false),setJavaScriptCanOpenWindowsAutomatically(true), optional mixed content, user-agent append/override, background colour, zoom controls,setWebContentsDebuggingEnabled. Also computeslocalUrl/appUrlfrom scheme + hostname (defaulthttps://localhost, fromCapConfig.androidScheme) or fromserver.url, and appendsserver.startPathif configured.setAllowedOriginRules()— the origin allowlist used by theWebMessageListener.- Construct
MessageHandler. registerAllPlugins()— built-insCapacitorCookies,WebView,CapacitorHttp,SystemBars, then app plugin classes and instances.loadWebView()— install the document-start script, startWebViewLocalServer, setBridgeWebChromeClient/BridgeWebViewClient, optionally install aServiceWorkerClient, apply any persisted live-update server path, verify the system WebView meetsminWebViewVersion(default 60; Huawei 10), thenloadUrl(appUrl).
Bridge is constructed only through Bridge.Builder, which also registers the two
built-in message interceptors:
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.
MessageHandler's constructor picks a transport:
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.
@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); }
}PluginHandleindexes everypublicmethod annotated with@PluginMethodby name at registration time (Class.getMethods()+ annotation scan), then invokes by reflection.@PermissionCallbackand@ActivityCallbackmark the methods the AndroidXActivityResult/permission flows call back into;Bridge.registerForActivityResultwires the launchers ininitializeActivityLaunchers().@CapacitorPlugin(requestCodes = …)is the deprecated legacy path, kept so plugins wrapping third-party SDKs that still useonActivityResultrequest codes keep working.BridgeActivitytries 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.
BridgeWebViewClient.shouldInterceptRequest delegates everything to
WebViewLocalServer.shouldInterceptRequest, which handles:
/_capacitor_http_interceptor_?u=<url>→ native HTTP fetch (theCapacitorHttpproxy)/_capacitor_file_→ a file on disk,/_capacitor_content_→ acontent://URI- ordinary asset paths, served by
AndroidProtocolHandlerfromapp/src/main/assets/public, withhtml5modefalling back toindex.html - injecting the Capacitor bootstrap
<script>into HTML documents, whenaddDocumentStartJavaScriptwas unavailable
shouldOverrideUrlLoading → Bridge.launchIntent(url), which mirrors the iOS policy:
block the interceptor path, ask plugins (shouldOverrideLoad), allow data:/blob:,
allow same-origin or allowNavigation-matched hosts (via HostMask), otherwise fire an
ACTION_VIEW intent and cancel.
BridgeWebChromeClient covers file chooser, permission requests, geolocation prompts,
JS dialogs and console forwarding. WebViewListener lets apps hook
onPageLoaded, onPageStarted, onReceivedError, onRenderProcessGone,
onPageCommitVisible.
The library's own android/capacitor/src/main/AndroidManifest.xml is empty — the
runtime declares no permissions or components of its own; everything comes from the app
or from plugins via manifest merging.
The app template (android-template/app/src/main/AndroidManifest.xml) declares:
MainActivity(launchMode="singleTask",exported="true", a broadconfigChangeslist so rotation and locale changes do not recreate the web view)- an
androidx.core.content.FileProviderwith authority${applicationId}.fileproviderand@xml/file_paths— the shared provider plugins use to hand outcontent://URIs android.permission.INTERNET
Cordova plugins' manifest fragments are merged into
capacitor-cordova-android-plugins by the CLI (writeCordovaAndroidManifest).
Module build settings (android/capacitor/build.gradle): AGP, compileSdk and minSdk
are pinned there and move every major — read the file for current values. Java 21
source/target, lintOptions with
abortOnError = true and warningsAsErrors = true against a checked-in
lint-baseline.xml. Dependencies are limited to AndroidX (appcompat, core,
activity, fragment, coordinatorlayout, webkit) — consistent with the project's
policy of minimising third-party dependencies.
android-template/app/build.gradle applies the generated capacitor.build.gradle and
conditionally applies the Google Services plugin if google-services.json exists.
Unlike iOS, Android has a real permission framework in the runtime, built on the AndroidX Activity Result APIs.
Declaration. Permissions are declared on the plugin class and grouped under an alias, so JS never sees Android permission strings:
@CapacitorPlugin(
name = "Camera",
permissions = {
@Permission(strings = { Manifest.permission.CAMERA }, alias = "camera")
}
)A @Permission with no strings is an auto-grant alias — used for capabilities that
need no runtime grant on Android but exist on another platform, so the JS interface stays
uniform. requestPermissions reports those as GRANTED without prompting.
Wiring. PluginHandle.loadInstance calls Plugin.initializeActivityLaunchers(),
which scans the plugin for @PermissionCallback and @ActivityCallback methods and
registers one ActivityResultLauncher per callback name through
Bridge.registerForActivityResult (delegating to the Fragment when Capacitor is
embedded, otherwise the AppCompatActivity). Registration must happen before the
activity is STARTED, which is why it runs at plugin load.
The round trip. A plugin requests with requestPermissionForAlias,
requestPermissionForAliases or requestAllPermissions, naming the callback method:
- The call is stashed via
bridge.savePermissionCall(call)— it must outlive the system dialog, which can take the activity throughonStop. - The launcher fires the OS prompt.
- On result,
Plugin.triggerPermissionCallbackretrieves the call withbridge.getPermissionCall(pluginId)and invokes the@PermissionCallbackmethod. - The callback resolves the original
PluginCall.
The default requestPermissions (Plugin.java) implements the whole pattern generically:
it reads the aliases from the annotation, honours an optional permissions array in the
call to request a subset, separates auto-grant aliases, and routes the result through
checkPermissions as its callback. Note that checkPermissions is itself annotated both
@PluginMethod and @PermissionCallback — it serves as the result reporter as well as a
callable method. Most plugins therefore need no permission code at all.
getPermissionStates() delegates to Bridge.getPermissionStates(plugin), which maps each
alias to a PermissionState, consulting SharedPreferences (PluginPermStates) to
distinguish "never asked" from "denied", since Android cannot report that directly.
Android may kill the hosting process while a plugin is waiting on another activity — a camera capture, a file picker. On return the web view reloads from scratch, so the JS callback the original call belonged to no longer exists. Capacitor preserves the native half of that call and delivers the result through a side channel.
Bridge.saveInstanceState(Bundle) persists pluginCallForLastActivity — the call that
started an activity — as four entries: the plugin id, method name, the options JSON, and
a plugin-supplied Bundle from Plugin.saveInstanceState(). BridgeActivity calls it
from onSaveInstanceState.
Bridge.restoreInstanceState(Bundle) (invoked from Bridge.Builder.create when an
instance state was supplied) rebuilds a PluginCall from those entries and hands the
plugin's own Bundle back via Plugin.restoreState(Bundle).
The rebuilt call is given PluginCall.CALLBACK_ID_DANGLING — the literal "-1" — because
there is no JS callback to resolve. MessageHandler.sendResponseMessage branches on that
id and routes the result to bridge.getApp().fireRestoredResult(data) instead of the web
view, which surfaces it through App.AppRestoredListener. The @capacitor/app plugin
exposes this to JS as the appRestoredResult event.
So the "-1" sentinel means two different things depending on direction: outbound from
JS it means "fire and forget, no callback stored" (§4.3); inbound from native it means
"this result has no live callback, route it to the restored-result listener".
SystemBars is a built-in plugin on both platforms (jsName SystemBars), registered
unconditionally in CapacitorBridge.registerPlugins() and Bridge.registerAllPlugins().
Its JS interface lives in core/src/core-plugins.ts, with core/system-bars.md as the
committed docgen output.
The two platforms carry different weight:
- iOS (
Plugins/SystemBars.swift) exposessetStyle,setAnimation,show,hideand defers toUIViewControllerstatus-bar appearance. Safe areas are already handled by WebKit'senv(safe-area-inset-*). - Android (
plugin/SystemBars.java) additionally owns inset handling, because Android has no equivalent guarantee.
The Capacitor 9 default is insetsHandling: 'native'. Android 15 (API 35) made
edge-to-edge mandatory for apps targeting it, so the app template's MainActivity calls
EdgeToEdge.enable(this) and migrate-edge-to-edge adds it to existing apps (§9.6).
Once the window draws behind the system bars, something must tell the web layer where
the safe region is.
plugins.SystemBars.insetsHandling (typed in cli/src/declarations.ts) selects how,
and reaches the plugin through the normal config path (§8) as
getConfig().getString("insetsHandling", …). Three values, Android-only:
| Value | Behaviour |
|---|---|
native (default) |
Let the WebView apply insets itself, so env(safe-area-inset-*) works as it does on iOS. |
css |
Capacitor reads WindowInsetsCompat (system bars ∪ display cutout), converts px → dp, and sets --safe-area-inset-top/right/bottom/left custom properties on document.documentElement from an inset listener. For WebView versions where env() is unreliable. |
disable |
Capacitor does nothing; the app handles insets itself. Also makes migrate-edge-to-edge skip the project. |
Under css, Capacitor must zero the bottom inset manually while the IME is visible —
the native path gets that correction from newer WebViews for free. The companion
initialViewportFitValueHint only exists to avoid a layout jump before the real
viewport-fit is detected.
On the web there is no native-bridge.js and no PluginHeaders. getPlatformId()
returns 'web' (nothing defined androidBridge or webkit.messageHandlers.bridge), so
registerPlugin resolves methods purely from the PluginImplementations map:
export const Camera = registerPlugin<CameraPlugin>('Camera', {
web: () => import('./web').then((m) => new m.CameraWeb()),
});Implementations may be a value or a lazy factory; factories are awaited once and cached
in loadPluginImplementation(), which keeps web-only code out of the initial bundle.
WebPlugin (core/src/web-plugin.ts) provides the event machinery that mirrors the
native side: addListener/removeAllListeners, notifyListeners with
retainUntilConsumed, registerWindowListener for bridging DOM events into plugin
events, and unimplemented()/unavailable() helpers.
A third-party host can present itself as a non-web, non-native platform by defining
window.CapacitorCustomPlatform = { name, plugins } before @capacitor/core loads.
getPlatform() then returns that name, and loadPluginImplementation falls back to the
web implementation when the custom platform has no entry of its own — this is how
Electron-style platforms are supported without changes to core.
Existing Cordova plugins run inside a Capacitor app unmodified. The compatibility layer
is opt-in by presence: the CLI enables it when the app has at least one Cordova plugin
installed, or when the top-level forceCordovaInclusion config key is set.
Native hosting. On iOS the Cordova target carries the CDV* classes
(CDVPlugin, CDVPluginManager, CDVViewController, CDVInvokedUrlCommand,
CDVPluginResult); the CapacitorCordova target bridges them into Capacitor with a
single Swift class, CordovaPlugin in ios/Sources/CapacitorCordova/Plugin.swift. It is
an ordinary Capacitor plugin (jsName __CordovaPlugin, no bridged methods) whose
load() parses the app's config.xml with CDVConfigParser, builds a
CDVPluginManager against the Capacitor web view and view controller, and instantiates
every plugin listed as a startup plugin. Android mirrors this with
android/capacitor-cordova — MockCordovaWebViewImpl and MockCordovaInterfaceImpl
present a Cordova-shaped host over Capacitor's WebView.
CapacitorBridge.registerPlugins() notices the CordovaPlugin entry in
packageClassList and sets cordovaIsPresent, which suppresses Capacitor's own
resume/pause notification wiring so Cordova's lifecycle events are not doubled.
JS. core/cordova.js (shipped inside @capacitor/core) provides the
cordova.exec shim, and the CLI writes cordova_plugins.js plus each plugin's JS into
the app's web assets — see handleCordovaPluginsJS in cli/src/cordova.ts. On Android
these are concatenated into the document-start script by JSInjector; on iOS they are
injected as additional WKUserScripts. native-bridge.ts also installs the legacy
surface the shims expect: a window.cordova object, navigator.app.exitApp, and a
deviceready/backbutton interception in document.addEventListener.
Scaffolds. capacitor-cordova-android-plugins/ and capacitor-cordova-ios-plugins/
are the per-app staging projects the CLI materialises; plugin sources are copied in by
copyPluginsNativeFiles. On Android, writeCordovaAndroidManifest (cli/src/cordova.ts)
merges each plugin's config.xml <config-file> and <edit-config> entries into that
project's AndroidManifest.xml. On iOS the CLI generates either podspecs
(generateCordovaPodspecs) or a Package.swift per plugin
(generateCordovaPackageFiles), depending on the package manager.
flowchart LR
SRC["capacitor.config.ts / .js / .json<br/>(typed by cli/src/declarations.ts)"]
CLI["cap copy"]
A["android/app/src/main/assets/capacitor.config.json"]
I["ios/App/App/capacitor.config.json<br/>(+ packageClassList)"]
AC["CapConfig.loadDefault(context)"]
IC["InstanceDescriptor → InstanceConfiguration"]
AR["Bridge / plugins<br/>getConfig().getPluginConfig(name)"]
IR["CapacitorBridge / plugins<br/>bridge.config.getPluginConfig(name)"]
SRC --> CLI --> A --> AC --> AR
CLI --> I --> IC --> IR
- The source of truth is the app's
capacitor.config.*, typed by the CLI'sdeclarations.d.ts.loadExtConfigprefers.ts, then.js, then.json. cap copyserialises the evaluated config tocapacitor.config.jsoninside each native project (strippingandroid.buildOptions/ios.buildOptions, which are build-time only and must not ship in the app bundle).- On iOS the same file also carries
packageClassList, written bygenerateIOSPackageJSON;CapacitorBridge.registerPlugins()reads it back. - On Android the plugin list lives in a separate
assets/capacitor.plugins.json({ pkg, classpath }entries) read byPluginManager. - Per-plugin configuration reaches plugins as
PluginConfigon both platforms, keyed by the plugin's JS name. - A handful of settings are read directly from the platform instead of the JSON —
UIStatusBarHidden/UIStatusBarStyle/UISupportedInterfaceOrientationsfromInfo.pliston iOS,FLAG_DEBUGGABLEfor dev-mode detection on Android.
By default the app is served locally from the custom scheme (§5.6, §6.4). Setting
server.url points the web view at a remote origin instead — the mechanism behind
live-reload (cap run --live-reload, which sets it to the dev server on the LAN) and
behind apps that ship a hosted front end.
This is the one case where the bridge's two URLs diverge. Both platforms track them separately:
| Local scheme | With server.url |
|
|---|---|---|
localUrl / config.localURL |
capacitor://localhost (iOS), https://localhost (Android) |
unchanged — still the local origin |
appUrl / config.serverURL |
same as local | the remote URL |
Bridge.initWebView computes both and adds the remote authority to authorities;
CAPInstanceConfiguration does the equivalent on iOS. The distinction matters because
navigation policy (§5.6, §6.4) allows a top-level navigation that starts with either,
and because WEBVIEW_SERVER_URL — which Capacitor.getServerUrl() and convertFileSrc
rely on — is the local one. Plugins that build asset URLs keep working against the local
origin even while the page is remote.
Related settings, all under server in capacitor.config:
allowNavigation— extra hosts the web view may navigate to. Anything else is handed to the OS browser. On Android the list also feedsBridge.setAllowedOriginRules(), which scopes theWebMessageListenerchannel (§6.2), so a host not on the list cannot reach the bridge even if it loads.cleartext— Android blocks plaintext HTTP from API 28 onward; this re-enables it. Intended for live-reload against a plain-HTTP dev server.android.allowMixedContent— allows a secure page to pull insecure subresources (WebSettings.MIXED_CONTENT_ALWAYS_ALLOW); same use case.hostname,iosScheme,androidScheme— change the local origin itself. Changing a scheme changes the origin, so it invalidates everything the previous origin stored:localStorage, IndexedDB, cookies.errorPath— a local page loaded when a navigation fails, which is the main reason a remote-URL app still needs local assets copied.
Development-only settings should not ship. cleartext, allowMixedContent and a LAN
server.url all widen the app's network posture, and a release build that still carries
them is the common failure here.
npm workspaces (android, ios, cli, core) + Lerna (versioning/publishing) + Nx
(task graph and build caching; build is cacheable and depends on ^build).
Root scripts:
| Script | What it does |
|---|---|
npm run lint |
eslint . --ext ts + prettier --check (with prettier-plugin-java, so Java is formatted too) + swiftlint lint |
npm run fmt |
the same three with --fix / --write |
npm run build:nativebridge |
lerna run build:nativebridge → regenerates the injected bridge for both platforms |
npm run sync-peer-dependencies |
rewrites @capacitor/core peer ranges in the platform packages; runs automatically on the npm version lifecycle |
npm run build = clean → docgen → transpile → rollup
- docgen (
@capacitor/docgen) regeneratescookies.md,http.mdandsystem-bars.mdfrom the built-in plugin interfaces. These are shipped in the package. - transpile —
tscwithcore/tsconfig.json:files: ["src/index.ts"], targetes2017, modulees2015, emit tobuild/, declarations totypes/.importHelpers+noEmitHelpersmeans helpers come from thetslibruntime dependency. - rollup (
rollup.config.js) takesbuild/index.jsand emits three bundles:
| Output | Format | Consumer |
|---|---|---|
dist/index.js |
ESM | bundlers (module) |
dist/index.cjs.js |
CJS | Node / require (main), dynamic imports inlined |
dist/capacitor.js |
IIFE, minified | <script> tag / unpkg |
Tree-shaking is load-bearing: global.ts marks initCapacitorGlobal(...) with
/*#__PURE__*/, and core/src/tests/build-treeshaking.js (npm run test.treeshaking)
rolls up a module that side-effect-imports the built package entry and fails unless the
resulting bundle is completely empty. Any accidental top-level side effect in core/src
breaks that test.
flowchart LR
TS["core/native-bridge.ts"]
B["core/build/native-bridge.js<br/><i>tsc --target es2017</i>"]
R["rollup.bridge.config.js<br/>format: iife<br/>@rollup/plugin-replace strips exports"]
A["android/capacitor/src/main/assets/native-bridge.js"]
I["ios/Sources/Capacitor/assets/native-bridge.js"]
TS --> B --> R --> A
R --> I
Run npm run build:nativebridge after any change to core/native-bridge.ts and
commit the two generated files — they are checked in, banner-marked
/* Generated File. Do not edit. */, and listed in .eslintignore/.prettierignore.
The replace plugin rewrites module.exports, exports.__esModule and
exports.initBridge to the unused dummy variable, which is why native-bridge.ts
declares let dummy = {} at the top.
Android ships the file as an asset; iOS ships it as an SPM .copy("assets") resource and
as s.resources in the podspec, and JSExport.exportBridgeJS resolves it from
Bundle.module (SwiftPM) or Bundle(for:) (CocoaPods).
npm run build = clean → assets → tsc
assets runs scripts/pack-cli-assets.mjs, which tars each template directory
(android-template, ios-pods-template, ios-spm-template,
capacitor-cordova-android-plugins, capacitor-cordova-ios-plugins) into
cli/assets/*.tar.gz. It uses git ls-files as the file list, so anything untracked in
a template is silently excluded — a new template file must be git added before it will
ship. cli/assets/ is generated and not committed.
Commands are registered eagerly with commander but their implementations are loaded
with await import() inside the action, keeping cap --help fast.
This is what cap sync (= copy + update) actually produces:
Android
| Generated file | Written by | Contents |
|---|---|---|
android/app/src/main/assets/public/** |
copy |
the built web app |
android/app/src/main/assets/capacitor.config.json |
copy |
evaluated config |
android/app/src/main/assets/capacitor.plugins.json |
update |
{ pkg, classpath } for every discovered plugin |
android/capacitor.settings.gradle |
update |
include ':capacitor-android' + one include per plugin, each pointed at its node_modules path |
android/app/capacitor.build.gradle |
update |
implementation project(':…') per plugin, Cordova framework dependencies, Java 21 compile options |
Both Gradle files start with // DO NOT EDIT THIS FILE! IT IS GENERATED EACH TIME "capacitor update" IS RUN.
Plugin classes are discovered by scanning each plugin's android/src/main for
/^@CapacitorPlugin[\s\S]+?class (\w+)/ plus the preceding package declaration.
iOS, SwiftPM (default)
update regenerates ios/App/CapApp-SPM/Package.swift with a .package entry per
plugin that ships its own Package.swift. Plugins without one are reported as
"not compatible with SPM". The CLI also checks each plugin's declared Capacitor
dependency major against the installed @capacitor/ios and either warns or rewrites it
so SPM resolves a single Capacitor package identity.
iOS, CocoaPods
update rewrites the def capacitor_pods … end block in ios/App/Podfile with
pod 'Capacitor', :path => … plus one pod line per plugin (path-relative into
node_modules), then runs pod install (or bundle exec pod install) and
xcodebuild clean.
Both
copy writes packageClassList into the iOS capacitor.config.json by scanning plugin
sources for @objc(Name) (Swift) and CAP_PLUGIN(Name (ObjC).
A major release usually requires edits inside the app's own native projects — files
Capacitor does not own and cannot regenerate. Those edits ship as migrators in
cli/src/tasks/. They parse and patch existing files, skip work already done, and warn
rather than fail when a project has been customised beyond recognition.
| Task | Command | What it rewrites |
|---|---|---|
migrate.ts |
cap migrate |
The umbrella migrator. Bumps @capacitor/* and known official plugins in package.json and installs them; updates the Gradle wrapper, root and app build.gradle, gradle.properties and variables.gradle; removes jcenter(); patches AndroidManifest.xml and AppDelegate.swift; checks the JDK major; prints the breaking-change list. Delegates to the two below. |
migrate-swiftui.ts |
(from cap migrate) |
Converts a storyboard iOS app to the SwiftUI App-struct layout: rewrites AppDelegate.swift into a @UIApplicationDelegateAdaptor (keeping or adding configurationForConnecting), writes App.swift, CapacitorView.swift and SceneDelegate.swift, repoints Info.plist at the SwiftUI scene setup, and registers the new files with the Xcode App target via addSwiftFileToAppTarget (cli/src/util/xcode.ts). A stock 8.x SceneDelegate.swift is replaced with the 9.0 one; a customised one is kept with a warning. Detects partial state and skips rather than half-applying. |
migrate-edge-to-edge.ts |
(from cap migrate) |
Adds EdgeToEdge.enable(this) / enableEdgeToEdge() plus the needed imports to the app's MainActivity (Java or Kotlin). Skips when plugins.SystemBars.insetsHandling is 'disable' or the activity already opts in; warns with manual instructions if it cannot patch the file. |
migrate-spm.ts |
cap spm-migration-assistant |
Moves an iOS app from CocoaPods to SwiftPM: extracts the CapApp-SPM package directory from the bundled template and deletes Podfile, Podfile.lock and App.xcworkspace. |
These are the one place in the CLI that edits files by pattern-matching rather than
regenerating them, so they are the most fragile code in the package and the best covered
by tests — see cli/test/migrate-*.spec.ts and cli/test/xcode.spec.ts.
Versioning and npm publishing are Lerna-driven from the repo root. lerna.json sets
conventionalCommits: true, tagVersionPrefix: "" (tags are bare versions like
9.0.0, not v9.0.0), createRelease: "github", and message Release %s. It also
pins command.version.allowBranch to the release branch, so a version can only be cut
from there. All four packages are force-published together, so their versions stay in
lockstep.
Root scripts map to release channels:
| Script | Effect |
|---|---|
ci:publish:nightly |
prerelease nightly-<timestamp>, no changelog/tag/push, npm tag nightly |
ci:publish:dev |
prerelease dev-<timestamp>, npm tag dev |
ci:publish:alpha / beta / rc |
prerelease with that preid, npm tag next |
ci:publish:latest |
normal version bump, npm tag latest |
ci:publish:latest-from-pre |
--conventional-graduate a prerelease to stable, npm tag latest |
All publish with --provenance. npm version triggers
scripts/sync-peer-dependencies.mjs so the platform packages' @capacitor/core peer
range tracks the new version.
Native artefacts are published after npm, from main:
flowchart TB
D["workflow_dispatch: Publish Latest"]
N["publish-npm-latest<br/>lerna version + npm publish --tag latest"]
A["publish-android<br/>scripts/publish-android.sh"]
I["publish-ios<br/>scripts/native-podspec.sh publish"]
M["Maven Central<br/>com.capacitorjs:core"]
C["CocoaPods trunk<br/>Capacitor, CapacitorCordova"]
S["SwiftPM<br/>consumers resolve the git tag"]
D --> N
N --> A --> M
N --> I --> C
N -.->|"tag created by lerna"| S
- Android (
scripts/publish-android.sh): reads the version fromandroid/package.json, compares it against the<latest>in Maven Central'smaven-metadata.xml, and skips if already published. Otherwise runs:capacitor-android:publishReleasePublicationToSonatypeRepository closeAndReleaseSonatypeStagingRepositorywithCAP_PUBLISH=true(which is what activates thepublish-root.gradle/publish-module.gradlescripts and the signing plugin). - iOS (
scripts/native-podspec.sh publish):pod trunk pushforCapacitorCordovathenCapacitor, withNATIVE_PUBLISH=trueso the podspecs prefix their source globs withios/. - SwiftPM needs no publish step of its own. Apps resolve the Swift package out of the
@capacitor/iosnpm, which carriesios/Package.swiftalongside the sources, so it ships on the npm publish above. A git URL still resolves the rootPackage.swiftat the tag Lerna created.
| Suite | Location | Runner |
|---|---|---|
| Core JS | core/src/tests/*.spec.ts |
Jest (ts-jest preset, jest-jasmine2 runner, jsdom) |
| Core tree-shaking | core/src/tests/build-treeshaking.js |
plain node, npm run test.treeshaking |
| CLI | cli/test/*.spec.ts |
Jest, serial (jest -i) |
| iOS unit | ios/Tests/CapacitorTests, ios/Tests/CapacitorObjCTests |
xcodebuild test -scheme Capacitor-Package |
| Android unit | android/capacitor/src/test |
gradlew :capacitor-android:test |
| Android instrumented | android/capacitor/src/androidTest |
connected-device Gradle tasks |
.github/workflows/ci.yml runs on PRs to any branch and on pushes to main:
lint (macOS, so SwiftLint runs) gates test-cli, test-core, test-ios (macOS and
Xcode versions are pinned in that job's matrix) and test-android (JDK 21).
npm run verify is the per-platform entry point — xcodebuild build + xcodebuild test
for iOS, and clean lint build test scoped to :capacitor-android for Android.
Notable coverage worth keeping green when touching the bridge: core/src/tests/bridge.spec.ts
(drives initBridge directly), plugin.spec.ts / runtime.spec.ts (proxy and header
resolution), ios/Tests/CapacitorTests/JSExportTests.swift (the generated shim text),
HttpInterceptorNavigationTests.swift and HttpInterceptorNavigationTest.java (the
navigation block on the proxy path).
Things that will bite you when changing this codebase:
native-bridge.jsis generated and committed. Editingcore/native-bridge.tswithout runningnpm run build:nativebridgechanges nothing at runtime, and the two platform copies will silently drift.ios/Package.swiftis generated and committed too —npm run build:package-swiftderives it from the rootPackage.swift, andnpm run lintfails if the committed copy is stale. Edit the root manifest, not it.- The wire format is a cross-repo contract.
callbackId/pluginId/methodName/options/success/data/error/saveare read by third-party plugins and by older runtimes. Add fields; do not rename or repurpose them. Capacitor.toNative/fromNative/nativePromise/nativeCallback/triggerEvent/logJs/withPluginare called by name from compiled native code. They are marked internal but cannot be renamed without a coordinated release.- Injection order is load-bearing. The global stub must precede
native-bridge.js, which must precede the plugin shims, all at document-start. Anything that defers a script breaks apps that call plugins during module evaluation. - One serial queue per platform for all plugin work. Blocking it blocks every
plugin. Dispatch onward and resolve the
PluginCallfrom the completion handler. - Only
keepAlivecalls survive their first result, and every saved call is dropped on navigation (bridge.reset()). A plugin that stores a call across a page reload must re-establish it. - iOS silently drops calls it cannot route. An unknown selector logs and returns without settling the JS promise; Android rejects instead. When adding routing paths, prefer rejecting.
@objcis mandatory on iOS plugin methods. Dispatch isperformSelector-based; a method missing@objccompiles fine and fails at runtime with the "does not respond to method call" log.- Plugin discovery is regex-based, not AST-based. The CLI matches
@CapacitorPlugin … class X,@objc(X)andCAP_PLUGIN(X. Unusual formatting in a plugin's sources means it never reachescapacitor.plugins.json/packageClassList, and the plugin is simply absent at runtime. capacitor.settings.gradle,app/capacitor.build.gradle,CapApp-SPM/Package.swiftand thePodfile'scapacitor_podsblock are regenerated on everyupdate. Hand edits are lost.- Templates are packed from
git ls-files. An untracked new template file will not ship in the CLI tarball. - The Android library manifest is intentionally empty. Permissions and components belong to the app or to plugins; adding anything there affects every Capacitor app.
- Android lint runs with
warningsAsErrors = trueagainst a checked-in baseline — new warnings fail CI. - Third-party dependencies are restricted by policy (see
CONTRIBUTING.md): no new CocoaPods or Gradle dependencies without team approval, and no third-party web libraries in@capacitor/coreat all. - Breaking changes target the pre-release branch, not the stable one — see
CONTRIBUTING.mdfor the current branch map.lerna.jsonenforces this by pinningallowBranch, so versioning only runs from the branch it names.