Building an Android browser on GeckoView (Tokay)
geckoviewandroidkotlinjetpack-composebrowserwebextensionsublockkagigradledevtoolsautofilluserscripts
GeckoView is Mozilla's embeddable Firefox engine for Android: a library, not a fork, so an app gets Gecko rendering, WebExtensions and tracking protection without maintaining a browser. Justin's own browser Tokay (package io.jhampton.tokay, Kotlin + Jetpack Compose, about 3,200 lines, shipped 2026-10-13 through apps.jhampton.io and its F-Droid repo) is built on it. This article collects the toolchain facts and the GeckoView behaviors that cost time.
Toolchain (proven 2026-10)
- GeckoView 158 forces compileSdk 37.2, which forces AGP 9.4.1 and Gradle 9.6, with AGP's built-in Kotlin (no
kotlin.androidplugin), Compose compiler plugin 2.4.x, Compose BOM 2026.09; minSdk 29, targetSdk 36. - APK size:
libxul.sois about 150 MB per ABI. Ship arm64 only and store native libraries compressed (packaging { jniLibs.useLegacyPackaging = true }): 95 MB instead of about 180 MB. - An ABI switch property (e.g.
-Ptokay.abi=x86_64) lets you build a release for the emulator. The API 35 x86_64 emulator image also runs the real arm64 APK through ARM translation, which is a cheap check of the exact published binary. versionCode 0does not build. To test a self-updater, build a copy whose update URLs point at a local index offering a higher versionCode.
GeckoView behaviors that bite
- Emulator GPU: use
-gpu swangle_indirect. Withswiftshader_indirect, Gecko's GPU process wedges the emulator's gralloc/composer (blank page, "Killing GPU process due to IPC reply timeout",screencaphangs, survives force-stop; only an emulator restart clears it). - Site permissions: in
onContentPermissionRequest,perm.valueis 0, not the stored decision, and Gecko asks every time without remembering. Store the answer yourself (storageController.setPermission) and look it up withgetPermissions(uri, private)before prompting. Returningperm.valuebreaks geolocation. - File inputs:
FilePrompt.confirm(context, uri)fails on the picker'scontent://URIs (NS_ERROR_FILE_UNRECOGNIZED_PATH). Copy the file intocacheDir/uploads/and pass afile://URI. - uBlock Origin needs tab delegates: without
WebExtension.TabDelegateandSessionTabDelegate.onUpdateTabreturning ALLOW, its "page blocked" notice and dashboard cannot open, and a blocked navigation leaves the old page under the new address. GeckoView.coverUntilFirstPaint()belongs only where a new session is attached; calling it from every Composeupdateleaves the page covered.- Per-site request headers (e.g. a search provider's session token) are best added by a small built-in WebExtension limited to that host. Tokay sends Kagi's
X-Kagi-Authorizationonly on kagi.com this way, and it works in private tabs too. Prefer this over a?token=in the search URL, which lands in history, the address bar and anything copied from it.
WebExtensions
- Tell Gecko which tab is active: call
webExtensionController.setTabActive(session, true)whenever a tab is selected or created. Without it, an extension's toolbaraction.click()fails with "nativeTab is null". extensionsWebAPIEnabled(true)makes addons.mozilla.org's "Add to Firefox" button install straight into the app; also treat.xpiresponses as installs. The app supplies its own permission prompt (plain-English list plus an "also run in private tabs" choice) and update prompts.- Built-in extensions ship as plain assets and load with
ensureBuiltIn("resource://android/assets/<dir>/", id). A normal MV2 extension with no app-specific APIs also loads in desktop Firefox via about:debugging, which is a handy test bench. Hide "Remove" for built-ins; give them an off switch instead. runtime.onMessagelisteners must not beasync: an async listener answers every message withundefined, even ones meant for another listener. Return a Promise (ortrue+sendResponse) only for the messages you handle.- Userscripts can be supported without an extension store: deny any top-level load of a
*.user.jsURL and offer it as an install; parse the metadata block (@match/@include/@excludeconverted to JS regex sources, unit-testable in Kotlin); register each enabled script from a helper extension withbrowser.contentScripts.register. A GM shim covers most scripts:GM_getValue/setValue(snapshot embedded at registration, persisted instorage.local, re-registered on change),GM_addStyle,GM_xmlhttpRequestrelayed through the background page (<all_urls>),GM_setClipboard,GM_info, theGM.*promise API,unsafeWindow = wrappedJSObject.
Developer tools on a phone
- Eruda (MIT, a self-contained mobile devtools panel) injected into the page's MAIN world with
scripting.executeScript({world: "MAIN", injectImmediately: true})from a helper extension gives Elements, Console and Network. Re-inject on every top-framewebNavigation.onCommittedfor tabs that have tools on, and keep a per-tab panel state (open, which tool) in the background page so the panel reopens after reloads. Noteeruda.show(name)only switches tools; calleruda.show()first to open the panel. - Early console output: a small buffer script injected before Eruda captures
console.*,errorandunhandledrejectionand replays them once Eruda is up. - CSP on sites like GitHub blocks the panel's font and console
eval. For tabs with tools on, stripcontent-security-policy(and-report-only) response headers in a blockingwebRequest.onHeadersReceived. If a page had a CSP (or loaded before the listener existed, like restored tabs), reload it before opening the panel.<meta>CSPs are not affected. - Network tab completeness: Eruda only sees fetch/XHR made after it loads, so documents, scripts, CSS, images and fonts were missing. Record
webRequestevents in the background page per devtools tab (capped), flush batches into the page every 250 ms, and feed them to the panel; backfill fromperformancenavigation/resource entries when tools are turned on for a loaded page. That relies on Eruda 3.4.3 private network methods, so re-check on upgrade. webRequest rows have headers and status but no bodies; capturing bodies needsfilterResponseData(opt-in, size-capped). view-source:<url>renders natively in GeckoView (line numbers, highlighting): "View page source" is one line of code.- Remote debugging:
setRemoteDebuggingEnabled(true)opens the abstract socket@<package>/firefox-debugger-socket;adb forward tcp:6000 localabstract:<package>/firefox-debugger-socketthen reaches it from desktop Firefox's about:debugging.
Touch and pull to refresh
To decide whether a downward drag is a page scroll or a pull-to-refresh, feed ACTION_DOWN through GeckoView.onTouchEventForDetailResult and read the InputResultDetail: allow the pull only when the result is not HANDLED_CONTENT, the page is not scrollable upward (no SCROLLABLE_FLAG_TOP), and Gecko reports UNHANDLED or vertical overscroll. Pages with overscroll-behavior-y: none correctly report no overscroll and never pull. Once the drag passes touch slop downward, send Gecko an ACTION_CANCEL and take the gesture. Occasionally the detail for the first touch after a dialog never resolves; treat that as "no pull".
Tab thumbnails
GeckoView.capturePixels() captures only the session currently attached to the single engine view, asynchronously. Take it shortly after onPageStop for the current tab and when opening the tab switcher, and discard it if the view's session changed in between (a swap mixes pictures up). Scale to a small width, keep the top portion, store normal tabs as JPEG files and private tabs in memory only, and prune files for closed tabs at startup.
Saved passwords, cards and addresses
- One
Autocomplete.StorageDelegatereceives login, credit-card and address fetch/save calls; Gecko's form detection does the rest. Return an empty list from the fetch calls to turn a kind of autofill off (in GeckoView 158 Gecko's ownextensions.formautofill.*.enabledprefs default to on, and US addresses are supported). - Gecko only offers to save values the user typed. A form filled by page script (
input.value = …) and submitted produces no save prompt; drive tests withadb shell input text. - Do not save from private tabs. Suppress a dismissed picker for that tab until its URL changes.
- Gecko cannot fill card fields inside cross-origin payment iframes (Stripe Elements style) unless the field is in that frame; untested in practice.
- Storage and locking: see Storing saved passwords, cards and tokens in an Android app.
Importing from other browsers
- Firefox: the HTML bookmark export, the JSON backup, and the automatic
.jsonlz4backups (Mozilla's "mozLz40" header plus one LZ4 block; a hand-written block decoder is about 40 lines). Keep folder paths; keep the Toolbar / Other / Mobile roots as folders the way Firefox shows them; skipplace:URLs. - Chrome-family desktop profiles keep bookmarks in a
BookmarksJSON file (top-levelrootswithbookmark_bar,other,synced;date_addedis microseconds since 1601-01-01). Skipchrome:,edge:,brave:,chrome-extension:URLs. - Password CSVs (Chrome, Firefox about:logins, Bitwarden, Safari) differ in column names; keep only http(s) origins (Chrome exports
android://app logins, Firefox achrome://FirefoxAccountsrow).
Sync: the options and the recommendation
GeckoView has no built-in sync. Options weighed in 2026-10 (post #1779): - Own-server sync helps only someone with the same browser on two devices, and means holding other people's encrypted passwords on a small server with no backups. Not worth it. - Firefox Sync through Mozilla's android-components/application-services gives real two-way bookmarks, passwords, history and tabs with desktop Firefox, end-to-end encrypted. Costs: roughly 8 to 10 MB more per arm64 APK, Mozilla's telemetry library comes along (can be switched off), bookmarks/history move into Mozilla's Places storage (big rework), and Mozilla accounts only accept registered OAuth clients: small Firefox-based browsers (Iceraven, for example) sign in by reusing Firefox's client id, which works but is unofficial and blockable. - Chrome sync is closed to other browsers, so importers are the only help for Chrome users. Recommendation taken: skip sync; make first-day import easy instead (Chrome and Firefox files, and check that Android Autofill password managers fill in the browser).
Android integration
- "Search
" in every text-selection menu : an activity with anACTION_PROCESS_TEXTintent filter (text/plain) appears in the selection toolbar of every app that lists them (Flutter'sEditableTextdoes). Make it an invisible trampoline (translucent theme,noHistory, emptytaskAffinity, excluded from recents) that readsEXTRA_PROCESS_TEXT, starts the main activity with a search URL, returnsRESULT_CANCELEDand finishes. It must be separate because callers usestartActivityForResultand asingleTaskmain activity breaks that. - A "come back to where you were" detour (open a help page in a tab from Settings) needs an explicit return path: a parentless tab with no history makes Back exit the app. Tokay attaches a non-persisted
returnTo(label + screen stack) to the tab and shows a "Back to …" bar; Back after the page's own history closes the tab and resumes the screen. - Detecting installed apps (to hide promos for them) with
getLaunchIntentForPackagerequires a<queries>entry per package on Android 11+.
Desktop is a different project
GeckoView is Android only; there is no supported desktop Gecko embedding. Desktop paths are a customized official Firefox (policies.json, bundled extensions, Firefox's own UI), a full Firefox fork from mozilla-central (first Linux build about 45 to 90 minutes on a 16-thread machine, and the real cost is rebasing every 4-week release), or a different engine (Compose Desktop plus Chromium via JCEF).
Design choices worth copying
- "Customizable" meant hackable code, not a big settings UI: taste knobs in one
Config.kt, a README that maps every file. - Default search DuckDuckGo; a paid engine (Kagi) first-class but off until the user sets it up.
- Self-update from an F-Droid
index-v1.jsonthe app already publishes to; see A self-hosted F-Droid repository and APK catalog and In-app updates for sideloaded Android apps. - Deferred at first launch, then built a few days later: passwords and autofill, bookmark import, userscripts, extension-install UI. Sync stayed out (see above).
Gotchas
- Strict tracking protection breaks every Flutter web app.
ContentBlocking.AntiTracking.STRICTincludes theCONTENTcategory (the Disconnect "tracking content" list), which blockswww.gstatic.com(Flutter's CanvasKit renderer,canvaskit.js/.wasm) andfonts.gstatic.com(Roboto). A Flutter site then spins on its splash screen forever; logcat says the request "was blocked because Enhanced Tracking Protection is enabled". Tokay 0.3.8 usesSTRICT and CONTENT.inv(): ads, analytics, social, fingerprinting, cryptomining and email trackers stay blocked. Turning off uBlock does not help, since this is Gecko's own blocker. A site can protect itself by self-hosting CanvasKit (canvasKitBaseUrl) and its fonts, but that has to include the fonts, or the app boots with blank labels. - Known gaps: downloads stop if the app is killed, no web notifications.
- The debug build's package has a
.debugsuffix; launching the plain package runs the installed release (see Driving the Android emulator headlessly for QA). - Release builds under R8 need testing separately from debug.
- Never
pkill -fa pattern that also appears in your helper's own command line.
See also
- Driving the Android emulator headlessly for QA
- A self-hosted F-Droid repository and APK catalog
- Android app signing keys and why losing one is permanent
- Storing saved passwords, cards and tokens in an Android app
- The Tokay gecko (Gekko gecko): the animal the browser is named after