Debug a Capacitor Android WebView over CDP
Driving a Capacitor game on an Android emulator from the terminal over CDP: three ways adb forward attaches to the wrong page, and two stuck splash screens.
Contents
Echo Bat and Find the Brainrot are Capacitor games: a canvas inside an Android WebView. Most of
their code gets written in Claude Code sessions, and a terminal session cannot look at a phone.
What it can do is talk to the WebView over the Chrome DevTools Protocol (CDP), the same channel
chrome://inspect uses. Over a week of work on both games, the sessions on my machine did that
dozens of times a day.
The short version, four lines that forward the socket and count frames, is in how to make the Android emulator faster. This post is everything that went wrong after those four lines: attaching to the wrong page, connections that would not open, a test bridge that made the rest easier, and two launches that sat on the splash screen for different reasons.
The setup throughout: Capacitor 8, Android emulators on the API 36 image, debug and QA builds
(Capacitor turns WebView debugging on for debuggable builds), Node 24, and playwright-core
1.63 for connectOverCDP.
Three ways to attach to the wrong page
Each of these returned a page that looked fine and answered questions. The answers were about something else.
An ad's WebView. The debug socket lists every WebView in the process, and AdMob makes
several. On one Find the Brainrot launch, curl -s localhost:9333/json listed ten pages: nine
about:blank, and one https://localhost/, which is the game (Capacitor serves it from there with
androidScheme: "https"). In an Echo Bat session, a script that took
browser.contexts()[0].pages()[0] read this back as the page body:
<script>if (!window['AFMA_ReceiveMessage']) {window['AFMA_ReceiveMessage'] = function(message, opt_parameters) {...
That is Google's ad page. Pick the game by URL, every time:
const page = browser.contexts().flatMap((c) => c.pages())
.find((p) => p.url().startsWith('https://localhost'));
Another app's WebView. One script found its socket with
cat /proc/net/unix | grep webview_devtools_remote | head -1. That is the first debuggable
WebView on the device, whichever app owns it. The socket name ends in the process ID, so build
it from adb shell pidof <package> instead.
Another emulator. This one took a second transcript to explain. A Find the Brainrot session forwarded port 9333 correctly, worked for a while, and then a check returned this page text:
245 ECHO BAT: BRAINROT JUMP BEST 497 NIGHT FLYING ... PLAY
The session decided another app on its emulator had grabbed the connection. But the emulator
had only one debug socket, and it was Find the Brainrot's. The answer was in an Echo Bat session
running at the same time: 36 seconds before that check, it had run
adb -s emulator-5558 forward tcp:9333 ... for its own emulator. localhost:9333 is a port on
the computer, not on the device, so there is one of it, and the last session to forward it wins.
Nothing errors. Your next evaluate just runs in a different game.
When several sessions share a machine, give each device its own port. adb forward tcp:0 ...
asks adb for a free one and prints it, and adb forward --list shows who owns which. Before
trusting any result, read something from the page that only your app would have.
When connectOverCDP will not connect
Twice, connectOverCDP failed outright:
browserType.connectOverCDP: Protocol error (Browser.setDownloadBehavior): Browser context management is not supported.
Once, running pidof and the forward again fixed it. The process ID can change between two
commands when an app restarts, and the old socket name points nowhere. The other time the forward
was seconds old, and I never found out why. What worked was skipping Playwright. Node 24 has
fetch and WebSocket built in, and CDP is JSON over that socket:
// cdp.mjs: node cdp.mjs "<expression>"
const pages = await (await fetch('http://localhost:9333/json')).json();
const game = pages.find((p) => p.url.startsWith('https://localhost'));
if (!game) throw new Error('no game page: ' + pages.map((p) => p.url).join(' '));
const ws = new WebSocket(game.webSocketDebuggerUrl);
await new Promise((r) => ws.addEventListener('open', r));
let id = 0;
const waiting = new Map();
ws.addEventListener('message', (e) => {
const m = JSON.parse(e.data);
waiting.get(m.id)?.(m);
});
const send = (method, params = {}) => new Promise((r) => {
waiting.set(++id, r);
ws.send(JSON.stringify({ id, method, params }));
});
const r = await send('Runtime.evaluate', {
expression: process.argv[2], awaitPromise: true, returnByValue: true,
});
console.log(JSON.stringify(r.result.result?.value ?? r.result.exceptionDetails));
ws.close();
No dependencies, so it also dodges a smaller trap. Scripts written to a scratch folder failed
with ERR_MODULE_NOT_FOUND for playwright-core, because an ES module import resolves from the
script's own folder. NODE_PATH does not change that for ES modules; I tried. Importing the
package by its absolute path, .../node_modules/playwright-core/index.mjs, does.
A test bridge in QA builds
Tapping coordinates with adb shell input tap works until an ad shifts the layout or the
screen size changes. So every QA build of my games carries a small object on window with two
methods: state() returns the game as JSON (screen, run phase, score, wallet, consent, banner
height), and act(name, ...args) runs a named shortcut: start a run, turn on the autopilot,
crash on purpose, own ad removal, light the whole cave. A simplified version of the wiring:
// Only a build made with `vite build --mode qa` loads the bridge;
// a release bundle never contains the file.
if (import.meta.env.MODE === 'qa') await import('./qa-bridge.js');
With that, a script asks the game what it is doing instead of guessing from pixels. It also
made long unattended play easy. To fly Echo Bat for an hour, a loop reads state() once a
second, logs each run's score when the bat goes down, and starts the next. The one thing it
cannot do through the page is close a full-screen ad, because the ad is a separate Android
activity:
const top = adb('shell dumpsys activity activities | grep -m1 topResumedActivity');
if (/AdActivity/.test(top)) {
adb('shell input tap 1208 231'); // the ad's close button, at this screen size
await sleep(1500);
continue;
}
The first version pressed Back there. On the emulator, Back did not close an app-open ad or
an interstitial. The loop detected the ad, pressed Back, and sat behind it. Tapping the close
button did. With Google's Next-Gen ads SDK the activity is
com.google.android.libraries.ads.mobile.sdk.common.AdActivity.
Send real touches, not page-made events
adb shell input cannot do two fingers, and Find the Brainrot is pinch-to-zoom. CDP can:
Input.dispatchTouchEvent takes a list of touch points and delivers them as real input.
One script took a shortcut instead and built new PointerEvent('pointerdown', ...) inside the
page to tap stickers. It tapped the first sticker 40 times and the game never counted it. The
table calls setPointerCapture on each press, and capture is only allowed for a pointer that is
actually down; a made-up pointer ID never is. With setPointerCapture wrapped in a try for
that run, the same script found five stickers in five taps. The better route is not to make
events in the page at all: input sent through CDP arrives as a real pointer, which is what the
pinch tests used.
The screen lags, the page does not
On Find the Brainrot, zoom and fit seemed to need two taps. Instead of guessing, the session
logged every pointer event and click on window, then the table's transform at 0, 100 and 800
ms after each click:
LOG T0 game.fit translate(-427.078px, -568.813px) scale(2.24844)
LOG T100 game.fit translate(-266.602px, -355.142px) scale(1.65408)
LOG T800 game.fit translate(0.125174px, -2.84217e-14px) scale(0.666203)
Every tap reached its button and the zoom arrived within 800 ms. A screenshot taken two seconds after a tap still showed the old view, and one taken later showed the new one. The emulator's display was behind the page. I don't know why, and I have not checked it on a phone.
So I split the two jobs. Assertions read the page through CDP. Screenshots come from
adb exec-out screencap -p, because that is what a player would see. And
adb shell screenrecord only writes a frame when the screen changes, so one short recording
held 35 frames; resample it to a fixed rate before counting anything.
Two stuck splash screens, two causes
Twice, a fresh install of Echo Bat sat on the launch splash. Both times, reloading the page over CDP brought the home screen up. That reload was the mistake both times: it runs startup again, warm, and hides whatever held the cold one. The useful move was to attach and read, and change nothing.
The first time, the splash had been up over 45 seconds. After the reload, a second cold launch
hung too, and this time I read performance resource timing without touching anything. The
main JavaScript bundle was requested 22.6 seconds after the page started, and took 10.7 seconds
to arrive, from inside the APK. The first images started at 34.5. The
game had not finished loading its own files. top inside the emulator showed 177 MB free of
3 GB and 1 GB swapped, and soon after, Android killed the app with signal 9. That cause, and
the fix, are in the emulator post.
The console was full of Default FirebaseApp is not initialized in this process errors. They
were a false lead: my hand-built QA APK has no google-services.json, and the reload that
worked printed the same errors.
The second time, the splash stayed up for more than 20 seconds, then came down by itself. This time the read-only check gave a different answer:
{"screens":["home"],"vis":"visible","qa":{"screen":"home", ..., "status":"playing", ...}}
The page had finished. Home was rendered behind the native splash, so the hold was between "the game is ready" and "take the splash down". In my startup, two steps sit there: the launch app-open ad, then waiting for the first screen's pictures to be drawn. Logcat had the app-open ad finishing its load about 20 seconds after launch, which fits. But I never launched with that step switched off, so I can't say the ad held the splash. That is the next test, and the reason the claim stops here.
Beyond evaluate: what holds the memory
The Echo Bat renderer process sat around 400 MB while the JavaScript heap was 35 MB. Evaluating expressions cannot see the rest, but two other CDP calls can.
Runtime.queryObjects returns every live object with a given prototype, including canvases
no longer attached to the document:
const proto = await send('Runtime.evaluate', { expression: 'ImageBitmap.prototype' });
const all = await send('Runtime.queryObjects', {
prototypeObjectId: proto.result.result.objectId,
});
const sizes = await send('Runtime.callFunctionOn', {
objectId: all.result.objects.objectId,
functionDeclaration: 'function () { return this.map((b) => [b.width, b.height]); }',
returnByValue: true,
});
On the home screen it found 21 live ImageBitmaps, about 84 MB at four bytes a pixel. The
same call on HTMLImageElement.prototype cleared my first suspect: none of the splash images
were still alive. A memory dump through the Tracing domain, with the
disabled-by-default-memory-infra category and Tracing.requestMemoryDump, split the rest by
allocator, and listed 4.6 MB of CanvasGradient objects, which pointed at gradients created
every frame.
Before trusting a CDP session
- Forward by
pidof, and forward again after any reinstall or restart. - One host port per device when anything else might be forwarding.
- Pick the page by
https://localhost, never by index. - Read something only your app has before believing the answers.
- Send touches through CDP
Input, not events made in the page. - On a stuck launch, read state first. Reload last, if at all.