/** * Decide whether this page is running inside the Even app. * * The Even app's WebView provides `window.flutter_inappwebview.callHandler` (per the SDK's * README). The simulator provides it before the page's script runs. Whether the real Even app * always does is NOT known: this wait is a precaution, not a fix for an observed problem. * (It was written on 2026-11-21 after a wrong diagnosis: a page that showed "Browser preview" * on a phone had simply been opened in Chrome, not in the Even app.) The page waits briefly * for the host, and listens for the WebView's own "platform ready" event, before concluding * it is in an ordinary browser. */ export interface HostWindow { flutter_inappwebview?: { callHandler?: unknown }; addEventListener(type: string, listener: () => void): void; removeEventListener(type: string, listener: () => void): void; } export interface HostDetection { found: boolean; /** How long the page waited before deciding. */ waitedMs: number; } /** Short, because in an ordinary browser this is pure delay before the preview appears. */ export const HOST_WAIT_MS = 2500; /** The event flutter_inappwebview dispatches on `window` once its JavaScript bridge is usable. */ export const PLATFORM_READY_EVENT = 'flutterInAppWebViewPlatformReady'; export function hostPresent(win: HostWindow): boolean { return typeof win.flutter_inappwebview?.callHandler === 'function'; } export function waitForEvenHost( win: HostWindow, options: { timeoutMs?: number; pollMs?: number; now?: () => number } = {}, ): Promise { const timeoutMs = options.timeoutMs ?? HOST_WAIT_MS; const pollMs = options.pollMs ?? 50; const now = options.now ?? Date.now; const started = now(); return new Promise((resolve) => { let done = false; const finish = (found: boolean) => { if (done) return; done = true; clearInterval(poll); clearTimeout(deadline); win.removeEventListener(PLATFORM_READY_EVENT, onReady); resolve({ found, waitedMs: now() - started }); }; const check = () => { if (hostPresent(win)) finish(true); }; // The event alone is not proof (anything can dispatch it); it only prompts a re-check. const onReady = () => check(); const poll = setInterval(check, pollMs); const deadline = setTimeout(() => finish(hostPresent(win)), timeoutMs); win.addEventListener(PLATFORM_READY_EVENT, onReady); check(); }); } /** * After the page has settled on browser-preview mode, keep watching: if the Even host turns * up after all, call `onLate` once (the page reloads itself into the real mode). */ export function watchForLateHost(win: HostWindow, onLate: () => void, pollMs = 500): () => void { let fired = false; const check = () => { if (fired || !hostPresent(win)) return; fired = true; stop(); onLate(); }; const timer = setInterval(check, pollMs); win.addEventListener(PLATFORM_READY_EVENT, check); const stop = () => { clearInterval(timer); win.removeEventListener(PLATFORM_READY_EVENT, check); }; return stop; }