Headless WebView and the Live-Instance Cap
A headless WebView is an InAppWebViewController that runs a full browser engine with no visible widget — no PlatformView, no surface in the widget tree. You create it, call run(), drive it entirely through the controller API, and dispose() it when done. This makes headless WebViews the substrate for background automation: scrapers, per-domain sessions, prefetching, and the WebView Pool that underpins recorded sessions. Because every live headless instance owns a real renderer (Android) or WebContent (Apple) process, the framework enforces a process-wide live-instance cap so a runaway loop cannot exhaust device memory. This page explains the two enforcement tiers — the Dart-side registry and the native manager — and how to raise the cap safely before the first run().
Sources: platform_headless_in_app_webview.dart headless_in_app_webview.dart
Why a Cap Exists at All
Section titled “Why a Cap Exists at All”Each headless WebView is not a lightweight object — it owns an entire rendering process and its own navigation queue. A per-domain scraper that spins up one headless view per host will grow memory without bound until the OS kills the app. The cap is the framework’s structural answer: a hard ceiling on how many headless instances may be live (running or idle-but-registered) at once, enforced redundantly at two layers so neither the Dart isolate nor the native side can drift past it.
The design deliberately splits responsibility. The native manager holds the authoritative hard stop, because native instances outlive a Dart hot restart — the dead isolate cannot dispose them, so a purely Dart-side cap would leak. The Dart-side registry provides the cooperative, higher-level policy (evict-the-oldest-idle, fail-loudly, or queue FIFO) that keeps the process comfortably under the native ceiling before it is ever reached.
Sources: HeadlessInAppWebViewManager.java headless_webview_registry.dart
The Two Enforcement Tiers
Section titled “The Two Enforcement Tiers”The following diagram shows how a run() call and the configured cap flow through both tiers. The Dart HeadlessInAppWebView registers itself as live, lazily pushes the configured ceiling to the native manager, then delegates to the platform run() where the native manager applies its LRU-or-refuse policy.
flowchart TD A["HeadlessInAppWebView.maxLiveWebViews = N"] -->|"setter (pre-run only)"| B["_configureNativeCap"] B -->|"setHeadlessMaxLiveWebViews"| C["Native manager cap"] D["headless.run()"] -->|"add to _liveInstances"| E{"native cap configured?"} E -->|"no / failed"| B E -->|"yes"| F["platform.run()"] F --> G{"native: liveCount >= cap?"} G -->|"iOS / Android"| H["LRU eviction, then re-check"] G -->|"macOS"| I["refuse: headless_cap_exceeded"] H -->|"still full"| I D -.->|"registry.track / acquire"| J["HeadlessWebViewRegistry (Dart policy)"]The cap value itself is a single process-wide integer, HeadlessInAppWebView.maxLiveWebViews. Its getter returns the configured value if the setter has run, otherwise a platform-aware default. The setter validates value >= 1, refuses to run once any headless instance is live, and eagerly kicks off the native propagation.
Sources: headless_in_app_webview.dart headless_in_app_webview.dart
Platform-Aware Defaults
Section titled “Platform-Aware Defaults”Before you configure anything, the cap already matches each engine’s memory profile. Mobile engines hold a whole render process per instance and get a tighter ceiling; desktop and the fallback get more headroom.
| Platform | Default cap | Enforcement on overflow |
|---|---|---|
| iOS | 3 | LRU eviction, else headless_cap_exceeded |
| Android | 3 | LRU eviction, else headless_cap_exceeded |
| macOS | 5 | Full-cap refusal (headless_cap_exceeded) |
| Linux / Windows / Web | 8 | No new native cap policy (registry-only) |
These defaults live in a single Dart getter and are mirrored by the native managers’ static initializers (maxLiveWebViews = 3 on iOS and Android, = 5 on macOS), keeping the Dart and native ceilings synchronized out of the box.
Sources: headless_in_app_webview.dart HeadlessInAppWebViewManager.swift HeadlessInAppWebViewManager.swift
Configuring the Cap Safely
Section titled “Configuring the Cap Safely”The cap is process-wide, not per view, and it is immutable once any headless view is live. This ordering constraint is the single most important rule: raise the cap once, at startup, before the first run().
// Correct: configure before any headless view starts.HeadlessInAppWebView.maxLiveWebViews = 6;
final view = HeadlessInAppWebView(initialUrlRequest: URLRequest(url: WebUri('https://example.com')));await view.run(); // native ceiling of 6 is applied first, then run proceedsIf you attempt to change the cap while a view is live, the setter throws a StateError directing you to dispose all live headless WebViews first. A value below one throws ArgumentError. Both guards are covered by the cap test suite, which also verifies the transient-failure retry path — a channel error during propagation leaves the cap unapplied so the next run() re-attempts rather than caching the failure for the process lifetime.
Sources: headless_in_app_webview.dart headless_cap_test.dart
Propagation and the Lazy Retry
Section titled “Propagation and the Lazy Retry”The setter does not assume the platform is registered. When InAppWebViewPlatform.instance is still null (the setter ran before the engine attached plugins), _configureNativeCap returns null without marking the cap as requested, so a later run() — which always executes after plugins are up — retries the propagation. This is why a run() issued immediately after the setter reliably observes the new native ceiling.
The run() method wires this together: it adds itself to the live set, ensures the native cap is configured (awaiting the in-flight propagation future rather than firing a duplicate), and only then calls platform.run(). A configuration error resets the requested flag and rethrows, keeping the retry semantics intact.
Sources: headless_in_app_webview.dart headless_in_app_webview.dart
Native Overflow Policy: LRU Eviction vs. Refusal
Section titled “Native Overflow Policy: LRU Eviction vs. Refusal”When a create reaches the cap, iOS and Android recycle the least-recently-used live instance rather than failing — this reaps instances orphaned by a Dart hot restart, whose dead isolate can never dispose them. If the LRU eviction cannot free a slot, the create fails with headless_cap_exceeded. macOS retains a stricter full-cap refusal: it never silently evicts, it simply rejects the create. Both native managers read channel arguments defensively and validate that maxLiveWebViews is an integer >= 1 before accepting it.
| Behavior | iOS | Android | macOS |
|---|---|---|---|
| Overflow at cap | LRU evict, then re-check | LRU evict, then re-check | Refuse (headless_cap_exceeded) |
| Setter method | setMaxLiveWebViews |
setMaxLiveWebViews |
setMaxLiveWebViews |
| Validation | integer >= 1 |
integer in [1, Integer.MAX_VALUE] |
integer >= 1 |
Sources: HeadlessInAppWebViewManager.java HeadlessInAppWebViewManager.swift HeadlessInAppWebViewManager.swift
The Dart-Side Registry: Cooperative Policy
Section titled “The Dart-Side Registry: Cooperative Policy”For consumers who depend on zikzak_inappwebview alone, HeadlessWebViewRegistry provides the higher-level primitives a multi-session headless transport needs: live-instance tracking, cap enforcement, idle-TTL eviction, and dispose-all. Its HeadlessWebViewRegistryConfig.platformDefaults() reads HeadlessInAppWebView.maxLiveWebViews directly, so the Dart ceiling and the native hard stop never diverge.
The registry offers two registration strategies. track() evicts the oldest idle instance when the cap is reached and fails loudly with HeadlessWebViewCapExceededException if every instance is active. acquire() is the queue counterpart: it parks FIFO-style until a slot frees, bounded by an absolute per-call slotAcquireTimeout so a permanently jammed pool fails rather than accumulating parked registrations. A failed native dispose keeps the entry registered, keeping the Dart count honest against the native one.
Sources: headless_webview_registry.dart headless_webview_registry.dart headless_webview_registry.dart
Eviction Notification and Lifecycle Settling
Section titled “Eviction Notification and Lifecycle Settling”Because the native manager can evict an instance at any later run() — long after construction — the Dart owner must learn about it. The factory wires an onEvicted closure that calls _handleNativeEviction(), which flips the instance’s lifecycle to released and removes it from the live set. This makes a subsequent dispose() the documented no-op instead of a second teardown of a dead per-instance channel. The dispose() method itself is KeepAlive-aware and only removes the instance from the live set on a clean, non-KeepAlive release, so the live count tracks reality.
Sources: headless_in_app_webview.dart headless_in_app_webview.dart headless_in_app_webview.dart
Module-Tier Alignment
Section titled “Module-Tier Alignment”The module package’s WebViewPoolConfig.platformDefaults() also reads HeadlessInAppWebView.maxLiveWebViews, so a pool created after the global cap changes inherits the new ceiling. The pool enforces its own live cap by evicting the oldest idle instance and refusing acquisition (WebViewPoolExhaustedException) when nothing is evictable — the same cooperative policy as the core registry, layered above the native hard stop.
Sources: webview_pool.dart webview_pool.dart
Operational Guidance and Cautions
Section titled “Operational Guidance and Cautions”Treat the cap as a memory-safety budget, not a tuning knob to maximize. Every live headless instance owns a renderer or WebContent process; raising the cap on a low-memory device can trigger out-of-memory termination of the whole app. Configure once at startup, prefer the registry’s idle eviction over pushing the native ceiling higher, and dispose promptly. On Web, Windows, and Linux there is no new native cap policy — the Dart registry is the only cooperative ceiling there.
Sources: spec.md HeadlessInAppWebViewManager.java
Where to Go Next
Section titled “Where to Go Next”- Learn how headless instances feed recorded sessions in Session Recording and Replay (Recipes) and VCR Cassettes and the WebView Pool.
- Understand the KeepAlive-aware teardown that the cap relies on in Disposal Lifecycle and KeepAlive Patterns.
- See the controller API a headless view exposes in InAppWebView Widget and InAppWebViewController.