
capacitor-features
Capacitor feature skills for deep links, keyboard handling, offline-first data, push notifications, splash screens, and App Intents (Siri, Shortcuts, Spotlight).
- version
- 1.1.0
- GitHub stars
- 79
Install
/plugin install capacitor-features@capgo-skillsRun it inside Claude Code after adding the marketplace with /plugin marketplace add Cap-go/capgo-skills.
Contents
Discovered from sourceSkills 6
App Intents for Capacitor Apps
Add native App Intents to the iOS project so system surfaces can run app actions, and connect them to the web layer. App Intents are Swift only. There is no JavaScript API for them, so every intent is native code in the App target or an extension, and the web layer is reached through a URL or a small local plugin.
When to Use
TRIGGER when:
- The user wants Siri phrases, Shortcuts actions, App Shortcuts, Spotlight actions, Action button or Apple Intelligence integration for a Capacitor app
- The user wants a widget button or a Control Center control to run an app action
- An intent opens the app, but the web view does not navigate, or it navigates only on warm launch
- A background intent crashes, times out, or tries to call JS
- Migrating
openAppWhenRuntosupportedModes, or adopting iOS 26/27 App Intents APIs - A plugin author wants to ship App Intents with a plugin
Do not use:
- JavaScript dispatch for Siri, Shortcuts, Spotlight, or Home Screen quick actions via
@capgo/capacitor-app-intents: usecapacitor-plugins(capgo-plugin-index.md, package@capgo/capacitor-app-intents). This skill is for native Swift App Intents (app target, extensions, or plugin native code), not that plugin API. - Universal Links / custom scheme /
appUrlOpensetup:capacitor-deep-linking - AppDelegate to SceneDelegate migration:
capacitor-uiscene-migration - Push notification actions:
capacitor-push-notifications - Live Activities or SVG widgets driven from JS:
capacitor-plugins(@capgo/capacitor-widget-kit) - Android app shortcuts and intents: not covered here
Facts that drive the design
- App Intents need iOS 16. Capacitor 8 deploys to iOS 15, so every intent type, entity, query and
AppShortcutsProviderneeds@available(iOS 16.0, *), or the user raises the deployment target. Capacitor 9 deploys to iOS 16, so the base API needs no gating. Newer APIs still do (tables in references/ios-26-27-apis.md). - A background intent has no WebView. iOS can launch the app process headless for
.backgroundintents.AppDelegate.application(_:didFinishLaunchingWithOptions:)runs, but no scene connects andCAPBridgeViewControllernever loads. Background intents must do native work only (network, storage, HealthKit, etc.). They cannot call JS or plugins through the bridge. perform()is not on the main actor, and it can run more than once. Hop explicitly (await MainActor.runor@MainActor func perform()) before you touch UIKit, the bridge or@MainActorstate. Do irreversible work last. Details: references/intent-traps.md.- With UIScene (Capacitor 8.5+) URL delivery moved. Universal Links and custom-scheme opens reach
SceneDelegateand are forwarded bySceneDelegateProxy, which posts the notifications@capacitor/applistens to. If the app still has custom URL code inAppDelegate, it no longer runs. Checkcapacitor-deep-linkingfirst ifappUrlOpendoes not fire for a normal link. An intent cannot fix a broken link pipeline. - On cold launch the JS listener does not exist yet. Any route an intent hands to the web layer must survive until JS asks for it: use
App.getLaunchUrl()for URLs, or a pending-route store plusnotifyListeners(..., retainUntilConsumed: true)for the local-plugin path. - Identifiers are a public contract. Intent type names,
AppEntity.idvalues,AppEnumraw values, URL formats and shipped phrases are stored in users' saved shortcuts. Add new ones; do not rename or remove shipped ones without telling the user.
References
Only load a reference when its topic is in play.
| File | Load when |
|---|---|
| references/project-setup.md | Creating files, target membership, extensions, App Groups, availability gating, build verification |
| references/web-bridge.md | Connecting an intent to the web layer: URL routing, the local AppIntentsBridge plugin, pending routes, shared data |
| references/intent-traps.md | Writing or reviewing any intent, entity, query, phrase, dependency, error or donation |
| references/ios-26-27-apis.md | supportedModes, foreground continuation, long-running/cancellable/undoable intents, execution targets, snippets, Spotlight indexing, schemas, testing |
| references/widgets-and-controls.md | Widget configuration intents, interactive widget buttons, Control Center controls |
Workflow
1. Inspect (read-only)
- Read
package.json(@capacitor/iosversion),ios/App/App/Info.plist(scene manifest present?),ios/App/App/AppDelegate.swift,ios/App/App/SceneDelegate.swift, the App target's deployment target, and any existing*.entitlements(Associated Domains, App Groups). - Check whether the app already handles deep links in JS (
App.addListener('appUrlOpen', ...),App.getLaunchUrl()) and which routes exist. - Search for existing intents:
grep -rn "AppIntent\|AppShortcutsProvider\|openAppWhenRun" ios/App. - List extension targets (widgets) in
ios/App/App.xcodeproj/project.pbxproj(PBXNativeTargetentries other thanApp).
2. Design with the user
For each action the user wants, decide and confirm:
| Question | Options |
|---|---|
| Does it need the UI? | No: background intent, native only. Yes: foreground intent that routes into the web app |
| How does it reach JS? | Universal Link via OpenURLIntent (iOS 18+, needs Associated Domains), or a local plugin with a pending-route store (works with custom schemes and iOS 16+) |
| What data does it need? | Fixed set: AppEnum. Dynamic, queryable: AppEntity + EntityQuery. Free text or number: plain @Parameter |
| Where must it run? | App target only, or also a widget / control (then the intent file needs both target memberships) |
| Which surfaces? | App Shortcut phrase (at most 10 App Shortcuts per app), Spotlight, widget, control |
Keep one intent per atomic task. Report the plan (files to add, targets, entitlements, JS changes) before editing.
3. Implement
- Create the Swift files in
ios/App/App/Intents/with the App target membership (references/project-setup.md). - Write the intents following references/intent-traps.md. Gate APIs by version.
- Add the web bridge (references/web-bridge.md): either reuse the deep-link router, or add the local plugin and register it in a
CAPBridgeViewControllersubclass. - Add an
AppShortcutsProviderwithshortTitle,systemImageNameand\(.applicationName)in every phrase. - Add entitlements only when needed (App Groups for shared data, Associated Domains for Universal Links), and on every target that uses them.
- JS side: handle the route on warm and cold start.
4. Verify
npx cap sync ios
xcodebuild -project ios/App/App.xcodeproj -scheme App \
-destination 'generic/platform=iOS Simulator' build
# CocoaPods projects: -workspace ios/App/App.xcworkspace
- The build log shows the App Intents metadata extraction step with no warnings about phrases. A phrase without
\(.applicationName)produces a build warning and is dropped at runtime. - Product > App Shortcuts Preview in Xcode shows the phrases matching.
- Run on a simulator or device: open the Shortcuts app, find the app's actions, run each one.
- Background intent: completes without the app coming to the foreground. Check the native logs (
ios-android-logs). - Foreground intent, app killed first (cold) and app running (warm): the web view lands on the right route both times.
- Background intent: completes without the app coming to the foreground. Check the native logs (
- Spotlight: search the shortcut title.
- If tests exist, add AppIntentsTesting coverage for iOS 27 test runners (references/ios-26-27-apis.md).
Error Handling
| Symptom | Cause | Fix |
|---|---|---|
'AppIntent' is only available in iOS 16.0 or newer | Capacitor 8 project deploys to iOS 15 | Add @available(iOS 16.0, *) to every App Intents type, or raise the deployment target with the user's approval |
| Intent missing from Shortcuts after install | File not in the App target, or metadata extraction failed | Check target membership. Read the build log for the App Intents metadata step. Reinstall the app |
| Phrase never triggers Siri; build warning about the application name | Phrase lacks \(.applicationName) | Add the token to every phrase |
| Build error about more than 10 App Shortcuts | Per-app cap | Merge actions or drop low-value ones |
Crash "...was not initialized prior to access" from @Dependency | Dependency registered too late (in a view controller) | Register in AppDelegate.application(_:didFinishLaunchingWithOptions:), which runs on headless launches too |
| Foreground intent opens the app but the web view stays on the home route on cold start | The route was posted before JS added its listener | Use the pending-route store + retainUntilConsumed, or App.getLaunchUrl() |
appUrlOpen never fires for OpenURLIntent | Universal Links not configured, or custom AppDelegate URL code under UIScene | Fix with capacitor-deep-linking. OpenURLIntent needs a real https Universal Link |
| Swift 6 error: main actor-isolated property cannot satisfy nonisolated requirement | The intent type is marked @MainActor | Remove @MainActor from the type. Put it on perform() or hop inside |
| Background intent killed after about 30 seconds | iOS limit for background intents | Shorten the work, or use LongRunningIntent on iOS 27 |
'openAppWhenRun' was deprecated in iOS 26.0 | iOS 26 SDK | Add a gated supportedModes (references/ios-26-27-apis.md). Keep openAppWhenRun while the deployment target is below 26 |
Related Skills
capacitor-deep-linking: Universal Links andappUrlOpenrouting the intents rely oncapacitor-uiscene-migration: required before Xcode 27; moves URL handling toSceneDelegatecapacitor-plugins:@capgo/capacitor-widget-kitfor Live Activities and JS-driven widgetscapacitor-testing: native unit tests and the device verification loopios-android-logs: logs from headless intent runs
Deep Linking in Capacitor
Route custom-scheme links, iOS Universal Links, and Android App Links into the web app.
When to Use
TRIGGER when:
- Adding
myapp://schemes, Universal Links, or App Links to a Capacitor app - Links open the browser instead of the app, or open the app but land on the home page
appUrlOpenfires on warm open but the URL is missing on cold launch (or the reverse)- Deep links broke after updating to Capacitor 8.5+ / adopting
SceneDelegate.swift - OAuth / magic-link / payment redirects must come back into the app
adb shell pm get-app-linksshowsnoneor1024instead ofverified
Do not use:
- Full AppDelegate -> SceneDelegate migration of an app:
capacitor-uiscene-migration - Notification tap routing:
capacitor-push-notifications - Native log capture while debugging:
ios-android-logs - Sign in with Apple / Google plugin config:
capacitor-plugins
Link Types
| Type | Platform | Format | Needs hosted file | Verified ownership |
|---|---|---|---|---|
| Custom scheme | both | myapp://product/123 | no | no (any app can claim it) |
| Universal Links | iOS | https://example.com/product/123 | /.well-known/apple-app-site-association | yes |
| App Links | Android 6+ | https://example.com/product/123 | /.well-known/assetlinks.json | yes |
Prefer verified https links for anything security-sensitive (OAuth, magic links). Custom schemes can be hijacked by another app.
Workflow
- Inspect first. Read
capacitor.config.*,ios/App/App/Info.plist,ios/App/App/*.entitlements,ios/App/App/AppDelegate.swift,ios/App/App/SceneDelegate.swift(if present),android/app/src/main/AndroidManifest.xml, and the@capacitor/appversion inpackage.json. - Decide the iOS lifecycle path.
UIApplicationSceneManifestpresent in Info.plist (Capacitor 8.5+ template or migrated app) -> URL events arrive inSceneDelegate. Any custom code in AppDelegateapplication(_:open:options:)orapplication(_:continue:restorationHandler:)is dead code. See references/ios-scene-delegate.md.- No scene manifest -> AppDelegate path still works on 8.5 core, but Xcode 27 / Capacitor 9 require the scene lifecycle. Hand the migration to
capacitor-uiscene-migration.
- Install
@capacitor/app(npm install @capacitor/app && npx cap sync). - Register the JS handler once, at app bootstrap (before the router renders), using both
appUrlOpenandgetLaunchUrl(). See below. - Configure platforms: custom scheme (Info.plist
CFBundleURLTypes, Android<intent-filter>), then verified links per platform:- iOS Universal Links: references/ios-universal-links.md
- Android App Links: references/android-app-links.md
- Route in the framework router: references/routing-patterns.md (React, Vue, Angular, OAuth callbacks, deferred links).
- Verify with the cold/warm matrix below on a real device.
Only load a reference when its topic is in play.
JS Handler (the part every app needs)
import { App, type URLOpenListenerEvent } from '@capacitor/app';
let lastHandled: string | undefined;
function route(rawUrl: string) {
if (rawUrl === lastHandled) return; // cold start can deliver the same URL to both paths
lastHandled = rawUrl;
const url = new URL(rawUrl);
// myapp://product/123 -> host "product", pathname "/123"
// https://example.com/product/123 -> pathname "/product/123"
const path = url.protocol.startsWith('http')
? url.pathname
: `/${url.host}${url.pathname}`;
router.navigate(path + url.search); // your router
}
export async function initDeepLinks() {
await App.addListener('appUrlOpen', (event: URLOpenListenerEvent) => route(event.url));
const launch = await App.getLaunchUrl(); // resolves undefined or { url }
if (launch?.url) route(launch.url);
}
Traps:
- Custom scheme URLs parse with the first segment as
host, notpathname. Normalize both forms as above. - Register the listener at bootstrap, not inside a lazily loaded page. A listener added after the event fired never sees it;
getLaunchUrl()is the fallback for cold start. - Wrap state updates from the listener in your framework's zone/run loop (Angular
NgZone.run) or navigation silently does nothing. - Dedupe: on cold start the URL can be reachable via both
getLaunchUrl()andappUrlOpen. - Validate and allow-list paths before navigating; a deep link is untrusted input.
Custom Scheme Config
iOS ios/App/App/Info.plist:
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string>com.example.app</string>
<key>CFBundleURLSchemes</key>
<array><string>myapp</string></array>
</dict>
</array>
Android AndroidManifest.xml, inside the existing MainActivity (keep the template's android:launchMode="singleTask" so warm opens reuse the activity):
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" />
</intent-filter>
Verification
Run every row on a physical device (Universal Links do not work reliably from the Simulator address bar; tap from Notes/Messages instead).
| Scenario | iOS | Android |
|---|---|---|
| Custom scheme, warm | xcrun simctl openurl booted "myapp://product/123" | adb shell am start -W -a android.intent.action.VIEW -d "myapp://product/123" com.example.app |
| Custom scheme, cold | kill app, then same command | adb shell am force-stop com.example.app, then same command |
| Verified link, warm | tap https://example.com/product/123 in Notes | adb shell am start -W -a android.intent.action.VIEW -c android.intent.category.BROWSABLE -d "https://example.com/product/123" |
| Verified link, cold | swipe app away, tap link | force-stop, then same command |
| Ownership check | curl -sI https://example.com/.well-known/apple-app-site-association (200, no redirect) | adb shell pm get-app-links com.example.app shows verified |
Pass criteria: each case lands on the right route, appUrlOpen logs once, and on cold start getLaunchUrl() returns the URL. After a Capacitor 8.5 scene migration, re-run the full matrix: cold launch takes a different native path (scene(_:willConnectTo:options:)) than warm open (scene(_:openURLContexts:) / scene(_:continue:)).
Grep for dead handlers after migration:
grep -n "open url: URL\|continue userActivity" ios/App/App/AppDelegate.swift
grep -n "SceneDelegateProxy" ios/App/App/SceneDelegate.swift
Error Handling
| Symptom / message | Cause | Fix |
|---|---|---|
| Link opens in Safari, app installed | AASA not fetched, wrong appID, entitlement missing, or user long-pressed and chose "Open in Safari" | Check AASA via Apple CDN, TEAMID.bundleId, applinks: entitlement; long-press link and choose "Open in App" to reset |
| Custom AppDelegate URL code stopped running after 8.5 update | Scene manifest exists; iOS calls SceneDelegate instead | Move logic to SceneDelegate (reference: ios-scene-delegate) |
| Warm opens work, cold launch lands on home | Listener registered late, or custom SceneDelegate code ignores connectionOptions | Call getLaunchUrl() at bootstrap; keep SceneDelegateProxy.shared.scene(_:willConnectTo:options:) |
Safari cannot open the page because the address is invalid | Custom scheme not registered in installed build | Add CFBundleURLTypes, rebuild (not just cap sync) |
Error: Activity not started, unable to resolve Intent | No intent-filter matches scheme/host | Fix <data> entries; reinstall app |
pm get-app-links shows 1024 or none | assetlinks.json unreachable, wrong package, or wrong SHA-256 (often the Play App Signing key) | Fix file, then adb shell pm verify-app-links --re-verify com.example.app |
| Android shows app chooser for https link | Domain not verified (autoVerify missing or failed) | Add android:autoVerify="true", re-verify |
| OAuth redirect returns to browser tab, not app | Redirect URI does not match registered scheme / verified domain | Register exact redirect URI; prefer verified https link |
Resources
- Capacitor deep links guide: https://capacitorjs.com/docs/guides/deep-links
- App plugin API: https://capacitorjs.com/docs/apis/app
- Updating to 8.5 (UIScene): https://capacitorjs.com/docs/updating/8-5
- Apple Universal Links: https://developer.apple.com/documentation/xcode/supporting-associated-domains
- Android App Links: https://developer.android.com/training/app-links/verify-android-applinks
Keyboard Handling in Capacitor
When to Use
TRIGGER when:
- Focused input is covered by the keyboard, or the page scrolls unexpectedly
- Chat composer / fixed footer does not stick to the keyboard
- White or black band above the keyboard (Android 15+ edge-to-edge, iOS backdrop)
100vh/dvhlayout collapses when the keyboard opens- iOS zooms into inputs, or the QuickType/accessory bar looks wrong
- Keyboard events never fire or fire twice
Do not use:
- Notch / home-indicator / status-bar padding:
safe-area-handling - Ionic
ion-input,ion-footerstyling:ionic-design - Labels, focus order, screen readers:
capacitor-accessibility
Platform model (the key decision)
| iOS | Android | |
|---|---|---|
| Who resizes | Plugin, per resize mode | OS + WebView; resize config is ignored |
| Events | keyboardWillShow before animation, keyboardDidShow after | Will/Did fire almost together |
| JS control | setResizeMode, getResizeMode, setScroll, setStyle, setAccessoryBarVisible (iPhone only) | show() (Android only), hide() |
iOS resize modes (KeyboardResize enum):
| Mode | Effect | Use when |
|---|---|---|
native (default) | Whole WebView shrinks; vh units change | Plain web apps; simplest |
body | Only <body> height changes; vh unchanged | Layouts that rely on stable vh |
ionic | Only ion-app resizes | Ionic Framework apps only |
none | Nothing resizes; you position with keyboard height | Custom chat UIs, full control |
Workflow
- Inspect:
capacitor.config.*plugins.Keyboard,@capacitor/keyboardversion (8.0.4+ includes iOS 26 and Android SystemBars fixes), whether Ionic is used,@capacitor/status-bar/ SystemBars config, and the failing screen's CSS (position: fixed,100vh). - Reproduce on a device (simulators often use a hardware keyboard: iOS Simulator -> I/O -> Keyboard -> Toggle Software Keyboard).
- Pick the iOS resize mode from the table; set it in config, not at runtime, unless one screen needs a different mode.
- Fix Android separately (below).
- Verify.
Config
// capacitor.config.ts
import { KeyboardResize, KeyboardStyle } from '@capacitor/keyboard';
plugins: {
Keyboard: {
resize: KeyboardResize.Body, // iOS only
style: KeyboardStyle.Default, // iOS only; JSON value is "DARK" | "LIGHT" | "DEFAULT"
// resizeOnFullScreen: omit on Capacitor 8+ (SystemBars handles insets; see Android notes)
autoBackdropColor: 'auto', // iOS, 8.0.4+: 'off' (default) | 'auto' | 'dom'
},
},
String values in JSON config are uppercase for style ("DARK"), lowercase for resize ("body").
Custom positioning (resize: none or chat UIs)
import { Capacitor } from '@capacitor/core';
import { Keyboard } from '@capacitor/keyboard';
if (Capacitor.isNativePlatform()) {
Keyboard.addListener('keyboardWillShow', ({ keyboardHeight }) => {
document.documentElement.style.setProperty('--kb', `${keyboardHeight}px`);
});
Keyboard.addListener('keyboardWillHide', () => {
document.documentElement.style.setProperty('--kb', '0px');
});
}
.composer {
position: fixed;
inset-inline: 0;
bottom: max(var(--kb, 0px), env(safe-area-inset-bottom));
}
Use max(), not +: while the keyboard is up the home-indicator inset is already covered.
Android notes
- Android 15+ (targetSdk 35) enforces edge-to-edge; Android 16 (targetSdk 36, Capacitor 8 default) removes the opt-out. The WebView now draws under system bars, so the keyboard inset must be handled.
@capacitor/keyboard7.0.2 fixed white space above the keyboard on Android 15+, and 8.0.3 fixed the interaction with the SystemBars core plugin. Update the plugin before writing workarounds. resizeOnFullScreen: truewas the Capacitor <= 7 workaround for fullscreen / overlaid status bar. On Capacitor 8+ the SystemBars core plugin handles IME insets and logsYou should omit `Keyboard.resizeOnFullScreen` in your `capacitor.config.json`. Other values can lead to unexpected behavior.unlessSystemBars.insetsHandlingisdisable. Remove it.- Do not add
android:windowSoftInputMode="adjustPan"to fix overlap; it pans the whole window and breaks fixed headers. The template omits it (default resize behavior). env(keyboard-inset-height)andinteractive-widgetviewport meta are Chromium features; test on the target Android System WebView version before relying on them, and never on iOS.
iOS notes
- Inputs with computed
font-size< 16px make iOS zoom on focus. Usefont-size: 16px(or larger) on inputs; do not disable user zoom globally (maximum-scale=1) as it hurts accessibility. setAccessoryBarVisible({ isVisible: false })hides the prev/next/done bar on iPhone; it has no effect on iPad.setScroll({ isDisabled: true })stops the WebView scroll view from bouncing when the keyboard opens; pair withresize: nonefor custom layouts.- iOS 26 keyboard regressions and the iPad Magic Keyboard black QuickType bar were fixed in
@capacitor/keyboard8.0.4. If a black/white band appears behind the keyboard, setautoBackdropColor: 'auto'(usesbackgroundColorfrom config, else the DOM body background) or'dom'.
Verification
npx cap syncand run on a physical iPhone and an Android 15+/16 device.- For each form screen: focus first and last input; the focused field stays visible; footer sits on the keyboard; no gap above the keyboard; rotating with the keyboard open keeps layout.
- Dismiss via swipe/back button:
keyboardWillHidefires and--kbreturns to 0. - iOS: confirm no zoom on focus; accessory bar state matches the design.
- Check versions:
npm ls @capacitor/keyboard @capacitor/core.
Error Handling
| Symptom / message | Cause | Fix |
|---|---|---|
"Keyboard" plugin is not implemented on web or "Keyboard.setAccessoryBarVisible()" is not implemented on android | Plugin/method unavailable on that platform | Guard with Capacitor.getPlatform() === 'ios' |
show() does nothing on iOS | show() is Android only | Focus an input from a user gesture instead |
| Footer floats in the middle after keyboard closes (Android) | WebView height not reset when keyboard hides without animation | Update to @capacitor/keyboard 8.0.4+ |
| White band above keyboard on Android 15+ | Edge-to-edge insets + old plugin | Update plugin (7.0.2+ / 8.0.3+); on Capacitor 8 remove resizeOnFullScreen |
Logcat SystemBars: You should omit `Keyboard.resizeOnFullScreen` ... | Legacy config fighting SystemBars inset handling | Delete resizeOnFullScreen from config |
vh-based screen shrinks on iOS | resize: native changes viewport | Switch to body or none |
| Ionic content jumps twice | resize: native/body plus Ionic's own handling | Use resize: 'ionic' |
| Listeners fire twice after navigation | Listener added per page mount, never removed | Keep the returned handle and await handle.remove() on unmount |
| Black QuickType bar on iPad with hardware keyboard | Pre-8.0.4 plugin bug | Update plugin |
Resources
- Keyboard plugin API: https://capacitorjs.com/docs/apis/keyboard
- Plugin changelog: https://github.com/ionic-team/capacitor-keyboard/blob/main/CHANGELOG.md
- System Bars (edge-to-edge): https://capacitorjs.com/docs/apis/system-bars
Offline-First Capacitor Apps
When to Use
TRIGGER when:
- The app must read and write while offline and sync later
- Choosing local storage (Preferences vs SQLite vs IndexedDB) for user data
- Writes are duplicated, lost, or overwritten during sync
- Cached data vanishes on iOS after low-storage events
- A service worker was added and native plugins stopped working (
Plugin not implemented)
Do not use:
- Replacing
@capacitor-community/sqlite/ Ionic secure storage:sqlite-to-fast-sql - Getting new web code to devices (OTA):
capgo-live-updates - Encryption key storage, SSL pinning:
capacitor-security - Query speed / bridge overhead tuning:
capacitor-performance
Decisions (make these before writing code)
| Question | Default answer |
|---|---|
| Where does UI read from? | Local DB only. Network writes into the DB; UI observes the DB. |
| Storage for records | SQLite via @capgo/capacitor-fast-sql |
| Storage for small settings / tokens | @capacitor/preferences (not for secrets; see capacitor-security) |
| localStorage / IndexedDB | Transient only: iOS can evict WebView storage under pressure |
| App shell offline | Already offline: Capacitor bundles web assets in the binary (or Capgo live-update bundle). No service worker needed. |
| Service worker in native builds | Avoid. Android SW blocks Capacitor plugin injection; iOS SW needs WKAppBoundDomains, which also blocks injection unless ios.limitsNavigationsToAppBoundDomains is set. Keep SW for the PWA build only. |
| IDs | Client-generated UUIDs (crypto.randomUUID()), so offline creates need no server round trip |
| Conflict policy | Ask the user/product owner: last-write-wins per record, per-field merge, or server-authoritative with user review |
| Deletes | Soft delete (tombstone) until the server acknowledges |
Workflow
- Inspect: current storage (
localStorage,@capacitor/preferences, other SQLite plugins), API shape (does it supportupdated_since/ version fields / idempotency keys?), auth refresh flow, existing service worker registration. - Report the plan (schema, outbox, conflict policy) to the user before invasive changes. For large apps, list each entity as a TODO.
- Install:
npm install @capgo/capacitor-fast-sql @capacitor/network && npx cap sync, then the platform setup in references/fast-sql-setup.md (required: iOS ATS local networking, Android localhost cleartext). - Schema + outbox: references/sync-engine.md.
- Triggers for sync: app start,
networkStatusChange-> connected, Appresume, after each local write (debounced), optional background task. - UI: show pending count / last synced time; never block a write on the network.
- Verify (below).
Only load a reference when its topic is in play.
Minimal shape
import { FastSQL } from '@capgo/capacitor-fast-sql';
import { Network } from '@capacitor/network';
import { App } from '@capacitor/app';
const db = await FastSQL.connect({ database: 'app' });
await db.execute(`CREATE TABLE IF NOT EXISTS outbox (
id TEXT PRIMARY KEY, entity TEXT NOT NULL, op TEXT NOT NULL,
payload TEXT NOT NULL, created_at INTEGER NOT NULL, attempts INTEGER NOT NULL DEFAULT 0
)`);
export async function saveTodo(todo: Todo) {
await db.transaction(async (tx) => {
await tx.run('INSERT OR REPLACE INTO todos (id, text, done, updated_at, dirty) VALUES (?, ?, ?, ?, 1)',
[todo.id, todo.text, todo.done ? 1 : 0, Date.now()]);
await tx.run('INSERT INTO outbox (id, entity, op, payload, created_at) VALUES (?, ?, ?, ?, ?)',
[crypto.randomUUID(), 'todo', 'upsert', JSON.stringify(todo), Date.now()]);
});
void sync(); // fire and forget; sync() is single-flight
}
Network.addListener('networkStatusChange', (s) => { if (s.connected) void sync(); });
App.addListener('resume', () => void sync());
The data row and its outbox entry are written in one transaction so a crash cannot leave one without the other.
Traps
Network.getStatus().connected === truedoes not mean the API is reachable (captive portals, VPN, server down). Treat fetch failures as offline; useconnectedonly as a hint to retry.networkStatusChangecan fire several times in a row; makesync()single-flight.- Send an idempotency key (the outbox row id) with every mutation; retries after a timeout otherwise duplicate records.
- Process the outbox in order per entity; a delete must not overtake its create.
- Advance the pull cursor using the server's timestamp/version from the response, never the device clock.
- Auth tokens expire while offline: refresh before draining the outbox, and keep entries on 401 instead of dropping them.
- Do not store large blobs in SQLite rows; save files with
@capacitor/filesystemand keep the path in the DB. - iOS background execution is opportunistic. Background tasks help but cannot guarantee sync timing; foreground sync on
resumeis the reliable path.
Verification
- Airplane mode on device: create, edit, delete records; kill and relaunch the app; data is still there.
- Turn network back on: outbox drains to 0, server reflects all changes once (no duplicates).
- Conflict test: edit the same record on two devices offline, reconnect both; result matches the chosen policy.
- Flaky network: Android emulator network throttling / iOS Network Link Conditioner (Settings -> Developer); retries back off, no data loss.
- Native checks:
grep -rn "serviceWorker.register" src/ | grep -v "isNativePlatform" # should be empty or web-guarded
/usr/libexec/PlistBuddy -c "Print :NSAppTransportSecurity:NSAllowsLocalNetworking" ios/App/App/Info.plist
grep -n "networkSecurityConfig\|usesCleartextTraffic" android/app/src/main/AndroidManifest.xml
- Inspect the DB:
SELECT COUNT(*) FROM outboxexposed in a debug screen, or pull the file (adb exec-out run-as com.example.app ls databases/).
Error Handling
| Error / symptom | Cause | Fix |
|---|---|---|
"CapgoCapacitorFastSql" plugin is not implemented on android / Plugin not implemented | Service worker or WKAppBoundDomains blocking injection, or missing npx cap sync | Remove SW from native build / set ios.limitsNavigationsToAppBoundDomains; run npx cap sync |
iOS: The resource could not be loaded because the App Transport Security policy requires the use of a secure connection | Fast SQL localhost transport blocked by ATS | Add NSAllowsLocalNetworking |
Android: CLEARTEXT communication to localhost not permitted by network security policy | Cleartext to localhost blocked | Add network_security_config.xml localhost exception |
SQLITE_CONSTRAINT: UNIQUE constraint failed during pull | Server row id already exists locally | Use INSERT ... ON CONFLICT(id) DO UPDATE |
database is locked | Parallel writers / long transaction | Serialize writes; keep transactions short; single-flight sync |
| Data gone after iOS storage pressure | Stored in localStorage / IndexedDB | Move to SQLite |
| Duplicate server records after reconnect | Retried POST without idempotency key | Send outbox id as Idempotency-Key; server dedupes |
Resources
- Fast SQL plugin: https://capgo.app/docs/plugins/fast-sql/
- Capacitor storage guide: https://capacitorjs.com/docs/guides/storage
- Network API: https://capacitorjs.com/docs/apis/network
- Background task plugin: https://capgo.app/docs/plugins/background-task/
- iOS troubleshooting (WKAppBoundDomains): https://capacitorjs.com/docs/ios/troubleshooting
Push Notifications in Capacitor
When to Use
TRIGGER when:
- Adding remote push (FCM / APNs) to a Capacitor app
registration/registrationErrornever fire, or the token works on one platform only- iOS token is a 64-hex APNs token but the backend expects an FCM token
- Notifications arrive in background but not in foreground (or vice versa)
- Android 13+ shows no prompt and nothing is delivered
- Upgrading to Capacitor 8.5 (UIScene) or 9 (
alertpresentation option removed)
Do not use:
- Opening the app from
https:///myapp://links:capacitor-deep-linking - Moving AppDelegate code to SceneDelegate:
capacitor-uiscene-migration - Device log capture:
ios-android-logs - Choosing other native plugins:
capacitor-plugins
Choose the plugin first (ask the user if unclear)
| Need | Plugin |
|---|---|
| Official plugin; APNs token on iOS, FCM token on Android | @capacitor/push-notifications |
| FCM token on both platforms, topics, Firebase-first backend | @capgo/capacitor-firebase-messaging |
| Capgo-managed delivery (dashboard campaigns, badges, silent live-update checks, no own push server) | @capgo/capacitor-notifications |
| Local notifications only, rich layouts | @capgo/capacitor-rich-notifications or @capacitor/local-notifications |
The rest of this file covers @capacitor/push-notifications. For Capgo plugins follow https://capgo.app/docs/plugins/firebase-messaging/ or https://capgo.app/docs/plugins/notifications/getting-started/.
Workflow
- Inspect:
package.jsonversions (@capacitor/core,@capacitor/push-notifications),capacitor.config.*plugins.PushNotifications,ios/App/App/AppDelegate.swift,ios/App/App/*.entitlements,android/app/google-services.json,android/variables.gradle,AndroidManifest.xml. - Install:
npm install @capacitor/push-notifications && npx cap sync. - iOS: capability + APNs key + AppDelegate forwarding. Details: references/ios-setup.md.
- Android:
google-services.json, channel, icon, permission. Details: references/android-setup.md. - JS: listeners first, then permission, then
register()(below). - Backend: send a test message. Payload shapes: references/sending.md.
- Verify with the checklist below on physical devices.
Only load a reference when its topic is in play.
JS registration (order matters)
import { PushNotifications } from '@capacitor/push-notifications';
export async function initPush() {
// 1. Listeners before register(), or the first token is missed
await PushNotifications.addListener('registration', ({ value }) => sendTokenToServer(value));
await PushNotifications.addListener('registrationError', (err) => console.error('push reg', err.error));
await PushNotifications.addListener('pushNotificationReceived', (n) => {
// foreground only (and Android data-only while app is alive)
});
await PushNotifications.addListener('pushNotificationActionPerformed', ({ notification, actionId }) => {
routeFromNotification(notification.data); // tap handling
});
// 2. Permission (required on iOS and Android 13+ / targetSdk 33+)
let perm = await PushNotifications.checkPermissions();
if (perm.receive === 'prompt' || perm.receive === 'prompt-with-rationale') {
perm = await PushNotifications.requestPermissions();
}
if (perm.receive !== 'granted') return; // explain + link to settings, do not loop prompts
// 3. Register
await PushNotifications.register();
}
Traps:
- Call
initPush()at bootstrap sopushNotificationActionPerformedfrom a cold-start tap is captured. - Tokens rotate. Send every
registrationvalue to the server and upsert by user + device. - On iOS the plugin reports the raw APNs token unless AppDelegate swaps in the FCM token (see ios-setup). Sending an APNs token to FCM fails with
messaging/invalid-registration-token. - Ask permission after a user action that explains the value; iOS shows the system prompt only once.
Foreground presentation
// capacitor.config.ts
plugins: {
PushNotifications: {
presentationOptions: ['badge', 'sound', 'banner', 'list'],
},
},
banner+listreplace the deprecated iOSalert. Capacitor 9 removesalerton iOS; replace it when upgrading.badgeis iOS only.- Empty array = nothing shown in foreground; handle
pushNotificationReceivedyourself.
Capacitor version notes
| Version | Change |
|---|---|
| 7 | firebaseMessagingVersion default 24.1.0 |
| 8 | firebaseMessagingVersion default 25.0.1 |
| 8.5 | UIScene lifecycle. Remote-notification callbacks (didRegisterForRemoteNotificationsWithDeviceToken, didFailToRegister...) stay in AppDelegate and keep working. Do not move them to SceneDelegate. Tap routing that used AppDelegate application(_:open:) must move (see capacitor-deep-linking). |
| 9 | iOS alert presentation option removed; iOS 16 min; @main replaces @UIApplicationMain; google-services Gradle plugin 4.5.0 |
Verification
- iOS:
codesign -d --entitlements :- path/to/App.app | grep aps-environmentshowsdevelopment(debug) orproduction(TestFlight/App Store). - Android:
adb shell dumpsys package com.example.app | grep POST_NOTIFICATIONSshowsgranted=trueafter accepting the prompt. - App logs a
registrationtoken on a real device (iOS Simulator on Apple silicon can receive pushes viaxcrun simctl push, but test real APNs on device). - Send a test from Firebase Console (Messaging -> "Send test message") or your backend to that token.
- Check all three states: foreground (presentation +
pushNotificationReceived), background (system tray), killed (tap ->pushNotificationActionPerformedroutes correctly). - iOS simulator smoke test without a server:
cat > /tmp/push.apns <<'EOF'
{ "Simulator Target Bundle": "com.example.app", "aps": { "alert": { "title": "Test", "body": "Hello" } }, "route": "/inbox" }
EOF
xcrun simctl push booted com.example.app /tmp/push.apns
(aps.alert in the APNs payload is the message content and is unaffected by the presentationOptions change.)
Error Handling
| Error / symptom | Cause | Fix |
|---|---|---|
no valid "aps-environment" entitlement string found for application | Push Notifications capability missing or profile not regenerated | Add capability in Xcode, re-sign, rebuild |
registration never fires on iOS, no error | AppDelegate does not post .capacitorDidRegisterForRemoteNotifications | Add forwarding methods to AppDelegate |
Default FirebaseApp is not initialized in this process (Android) | google-services.json missing/empty, so google-services plugin was not applied (google-services.json not found, google-services plugin not applied. Push Notifications won't work) | Put file in android/app/, rebuild |
messaging/registration-token-not-registered | Token stale (app reinstalled / data cleared) | Delete token server-side; rely on next registration |
messaging/invalid-registration-token / BadDeviceToken | APNs token sent to FCM, or sandbox token sent to production APNs | Use FCM token on iOS (ios-setup) or match APNs environment |
messaging/third-party-auth-error | APNs key not uploaded to Firebase, wrong Key ID / Team ID | Upload .p8 under Firebase Project Settings -> Cloud Messaging |
| Android 13+: nothing shown, no prompt | requestPermissions() never called | Call it; manifest permission is added by the plugin |
| Android shows white square icon | No monochrome notification icon | Set default_notification_icon meta-data |
| Android notification silent / wrong importance | Channel created with low importance (importance is immutable after creation) | Create a new channel id; delete the old one |
| Data-only message ignored when app killed (Android) | Plugin only delivers while app process lives | Native FirebaseMessagingService (android-setup) |
| iOS silent / background push not delivered to JS | Plugin does not support iOS silent push | Native handling, or @capgo/capacitor-notifications silent update checks |
| Duplicate class errors with Firebase after Capacitor 9 | Old core-ktx / Kotlin stdlib pins | See capacitor-app-upgrade-v8-to-v9 |
Resources
- Plugin API: https://capacitorjs.com/docs/apis/push-notifications
- Firebase guide: https://capacitorjs.com/docs/guides/push-notifications-firebase
- Updating to 9.0: https://capacitorjs.com/docs/updating/9-0
- Capgo Firebase Messaging: https://capgo.app/docs/plugins/firebase-messaging/
- Capgo Notifications: https://capgo.app/docs/plugins/notifications/
Splash Screen in Capacitor
When to Use
TRIGGER when:
- Configuring or regenerating splash / icon assets (
npx capacitor-assets generate) - Splash never disappears, disappears too early, or flashes white/black before the web app paints
- Android 12+ shows a small cropped icon on a solid color instead of the full image
- Upgrading to Capacitor 9 and the Android fade-out animation vanished
- iOS shows a black screen after adding
SceneDelegate.swift(8.5+)
Do not use:
- Status bar / navigation bar styling and edge-to-edge insets:
safe-area-handling - Migrating AppDelegate to SceneDelegate:
capacitor-uiscene-migration - Slow first paint / bundle size:
capacitor-performance - Icon requirements for store submission:
capacitor-app-store
How launch works (decide what to edit)
| Phase | iOS | Android 12+ | Android <= 11 |
|---|---|---|---|
| OS launch screen (before any code) | LaunchScreen.storyboard (UILaunchStoryboardName), image Splash in Assets.xcassets/Splash.imageset | System SplashScreen API: theme AppTheme.NoActionBarLaunch with Theme.SplashScreen parent - icon + background color only | androidx.core:core-splashscreen compat, or android:background drawable |
Plugin splash (until hide()) | Plugin overlay on the bridge view | Same system splash held via the API | Plugin ImageView / Dialog (androidSplashResourceName, androidScaleType) |
Most androidScaleType, showSpinner, splashFullScreen, layoutName, useDialog, backgroundColor options do not apply on Android 12+ launch (the OS draws it). They only affect show() and pre-12 devices.
Workflow
- Inspect:
capacitor.config.*plugins.SplashScreen,android/app/src/main/res/values/styles.xml,android/variables.gradle(coreSplashScreenVersion),ios/App/App/Info.plist,ios/App/App/SceneDelegate.swift,assets/orresources/folder. - Install:
npm install @capacitor/splash-screen && npx cap sync. - Assets: put sources in
assets/(icon-only.png,icon-foreground.png,icon-background.png,splash.png,splash-dark.png; splash >= 2732x2732, icons >= 1024x1024), thennpm install -D @capacitor/assets && npx capacitor-assets generate(--ios,--android,--pwato scope). Keep the logo inside the center ~1/3 so Android 12+ circular masking does not crop it. - Hide deliberately: set
launchAutoHide: falseand callhide()after the first meaningful render (below). - Android 12+ tuning if needed: references/android-12-splash.md.
- Verify (below).
Recommended config
// capacitor.config.ts
plugins: {
SplashScreen: {
launchAutoHide: false, // hide from JS when the UI is ready
launchFadeOutDuration: 200, // explicit: Capacitor 9 default on Android is 0
backgroundColor: '#ffffff', // match the first web paint to avoid a flash
},
},
import { SplashScreen } from '@capacitor/splash-screen';
// after the router's first view has rendered (e.g. in a root component's mounted/useEffect)
await SplashScreen.hide(); // optional: { fadeOutDuration: 300 }
Traps:
- With
launchAutoHide: false, a JS crash beforehide()leaves the app stuck on the splash. Add a fallback:setTimeout(() => SplashScreen.hide(), 8000). - Default when auto-hiding is 500 ms (
launchShowDuration). Long fixed durations hurt perceived startup; hide on readiness instead. - Set
<body>/ root background to the splash background color, or the gap between native splash and first web paint flashes white (dark mode: black). - Live updates (
capgo-live-updates): callnotifyAppReady()independently ofhide(); do not gate one on the other.
Version notes
| Version | Change |
|---|---|
| 4 | Android uses the Android 12 SplashScreen API + compat library |
| 7 | SplashScreenShowOptions / SplashScreenHideOptions types removed -> ShowOptions / HideOptions |
| 8 | coreSplashScreenVersion = '1.2.0' |
| 8.5 (iOS) | UIScene template creates the window and CAPBridgeViewController in SceneDelegate; Main.storyboard no longer supplies the root view controller. LaunchScreen.storyboard is unchanged and still required. |
| 9 | Android launchFadeOutDuration default 200 -> 0 (the old default could block UI changes right after hide()). Set 200 explicitly to keep the fade. |
iOS notes (Capacitor 8.5+ scenes)
- Keep
UILaunchStoryboardName = LaunchScreenin Info.plist. Apple requires a launch storyboard; deleting it causes letterboxed / wrong-size rendering. - Do not add views or a custom view controller to
Main.storyboardexpecting them to show: the 8.5 SceneDelegate setswindow.rootViewController = CAPBridgeViewController()in code. Put a customCAPBridgeViewControllersubclass there instead. - Black screen right after launch with a scene manifest = SceneDelegate creates no window (missing
window = UIWindow(windowScene:)+makeKeyAndVisible()) orUISceneDelegateClassNamepoints to a missing class. Fix withcapacitor-uiscene-migration. - The storyboard is cached by iOS. After changing it, delete the app from the device/simulator and reinstall.
- On resizable windows / iPad / foldables the launch storyboard must use Auto Layout constraints, not fixed frames (see
capacitor-ios-resizabilityif present).
Verification
npx cap syncthen a clean native build (Product > Clean Build Folderin Xcode;./gradlew cleaninandroid/).- Delete and reinstall the app (both platforms cache launch screens).
- Cold launch on: iOS device light + dark mode, Android 12+ device, Android <= 11 emulator (if minSdk allows; Capacitor 9 minSdk is 26).
- Confirm: no white/black flash, splash hides once the first screen is visible, fade matches the configured duration.
- Grep for leftovers:
grep -rn "launchFadeOutDuration\|launchAutoHide" capacitor.config.*
grep -n "Theme.SplashScreen\|postSplashScreenTheme" android/app/src/main/res/values/styles.xml
/usr/libexec/PlistBuddy -c "Print :UILaunchStoryboardName" ios/App/App/Info.plist
Error Handling
| Symptom / message | Cause | Fix |
|---|---|---|
| Splash stays forever | launchAutoHide: false and hide() never runs (JS error, wrong import, called before plugin load) | Check web console; add timeout fallback |
| Fade-out gone after Capacitor 9 upgrade (Android) | Default launchFadeOutDuration is now 0 | Set launchFadeOutDuration: 200 |
UI changes right after hide() not visible (Android, pre-9) | 200 ms fade blocked updates | Set launchFadeOutDuration: 0 |
| Android 12+ shows small icon, image cropped | OS splash is icon-only by design | Provide adaptive icon-safe artwork; tune windowSplashScreenAnimatedIcon |
| Android 12/12L no splash from third-party launchers or Android Studio | Platform bug fixed in Android 13 | Test from the stock launcher |
error: resource drawable/splash not found | androidSplashResourceName or styles reference a missing drawable | Regenerate assets or fix the name in both config and styles.xml |
AAPT: error: style attribute 'attr/windowSplashScreenAnimatedIcon' not found | core-splashscreen dependency missing | Restore implementation "androidx.core:core-splashscreen:$coreSplashScreenVersion" |
| iOS black screen after 8.5 scene adoption | No window created in SceneDelegate | See iOS notes / capacitor-uiscene-migration |
| Old splash still shows on iOS | Launch screen cache | Delete app, reboot device if needed, reinstall |
Resources
- Plugin API: https://capacitorjs.com/docs/apis/splash-screen
- Splash screens and icons guide: https://capacitorjs.com/docs/guides/splash-screens-and-icons
- Updating to 9.0: https://capacitorjs.com/docs/updating/9-0
- Android SplashScreen API: https://developer.android.com/develop/ui/views/launch/splash-screen
Sponsors
Details
- Marketplace
- Cap-go/capgo-skills
- Source
- plugins/capacitor-features
- Author
- Capgo
- Category
- Development
- License
- MIT
- Keywords
- capacitor, push-notifications, deep-linking, offline, keyboard, app-intents, siri