// Minimal Chrome DevTools Protocol client for the app's Android WebView // (exposed with `adb forward tcp:9333 localabstract:webview_devtools_remote_`). // Playwright can't drive an Android WebView's browser context, so this speaks CDP directly. /** The page the person sees: a WebView can list more than one page target while it is * replaced (a reload into a new bundle, a recreated activity) and the old one lingers * hidden/empty for a while; the first `page` in the list is not necessarily the live one. */ export async function liveTarget(port = 9333) { const targets = await fetch(`http://127.0.0.1:${port}/json`, { signal: AbortSignal.timeout(3000) }).then(r => r.json()) const pages = targets.filter(t => t.type === 'page') const info = t => { try { return JSON.parse(t.description || '{}') } catch { return {} } } return pages.find(t => info(t).visible && !info(t).empty) || pages.find(t => info(t).attached && !info(t).empty) || pages[0] || null } export async function connectWebView(port = 9333) { const target = await liveTarget(port) if (!target) throw new Error('no WebView page target') const ws = new WebSocket(target.webSocketDebuggerUrl) await new Promise((resolve, reject) => { const t = setTimeout(() => reject(new Error('DevTools connect timeout')), 5000) ws.onopen = () => { clearTimeout(t); resolve() } ws.onerror = e => { clearTimeout(t); reject(e) } }) let id = 0 let closed = false const pending = new Map() const logs = [] // a dead socket used to leave every later call waiting forever: fail them at once ws.onclose = () => { closed = true for (const { reject } of pending.values()) reject(new Error('DevTools socket closed')) pending.clear() } ws.onmessage = ev => { const msg = JSON.parse(ev.data) if (msg.id && pending.has(msg.id)) { const { resolve, reject } = pending.get(msg.id) pending.delete(msg.id) msg.error ? reject(new Error(msg.error.message)) : resolve(msg.result) } else if (msg.method === 'Runtime.consoleAPICalled') { logs.push(`[${msg.params.type}] ` + msg.params.args.map(a => a.value ?? a.description ?? '').join(' ').slice(0, 300)) } else if (msg.method === 'Runtime.exceptionThrown') { const d = msg.params.exceptionDetails logs.push('EXCEPTION ' + (d.exception?.description || d.text).slice(0, 400)) } } const send = (method, params = {}, timeoutMs = 20_000) => new Promise((resolve, reject) => { if (closed) return reject(new Error('DevTools socket closed')) const msgId = ++id const t = setTimeout(() => { pending.delete(msgId); reject(new Error(`DevTools ${method} timed out`)) }, timeoutMs) pending.set(msgId, { resolve: v => { clearTimeout(t); resolve(v) }, reject: e => { clearTimeout(t); reject(e) } }) ws.send(JSON.stringify({ id: msgId, method, params })) }) await send('Runtime.enable') await send('Page.enable') const evaluate = async expression => { const r = await send('Runtime.evaluate', { expression, awaitPromise: true, returnByValue: true }) if (r.exceptionDetails) { const e = new Error('eval failed: ' + (r.exceptionDetails.exception?.description || r.exceptionDetails.text)) e.pageError = true throw e } return r.result.value } return { targetId: target.id, send, evaluate, logs, isClosed: () => closed, close: () => { closed = true; ws.close() } } }