Content Blockers, Proxy, and Tracing
Three capabilities in this monorepo sit deliberately outside the per-widget controller surface: declarative request filtering through InAppWebViewSettings.contentBlockers, runtime proxy redirection through the process-wide ProxyController, and WebView performance tracing through TracingController. They share one architectural shape — a thin app-facing facade in zikzak_inappwebview, an abstract contract in zikzak_inappwebview_platform_interface, and a per-platform implementation that talks to the native engine — but they diverge sharply in where the work happens: content blockers are evaluated by the native engine before a request starts (or, on Android, inside shouldInterceptRequest), proxy overrides mutate a native session or data store, and tracing is a single Android-only API. Understanding those three execution models is the difference between a rule that silently does nothing and one that blocks a request before it leaves the process.
Sources: content_blocker.dart, platform_proxy_controller.dart, platform_tracing_controller.dart
The Shared Three-Layer Shape
Section titled “The Shared Three-Layer Shape”Every capability below is wired the same way, which means the same mental model transfers across all three. The app-facing object is a singleton facade that forwards to a platform object; the platform object is created through a factory on InAppWebViewPlatform; and each platform package either overrides that factory or inherits the interface’s UnimplementedError default.
flowchart TB subgraph APP["App code — package: zikzak_inappwebview"] CB["InAppWebViewSettings.contentBlockers"] PC["ProxyController.instance()"] TC["TracingController.instance()"] end subgraph PI["zikzak_inappwebview_platform_interface"] CBM["ContentBlocker / Trigger / Action"] PIF["PlatformProxyController + ProxySettings"] TIF["PlatformTracingController + TracingSettings"] end subgraph IMPL["Platform packages"] A1["Android — Java: ContentBlockerHandler, ProxyManager, TracingControllerManager"] I1["iOS — Swift: WKContentRuleListStore, ProxyManager"] M1["macOS — Swift: WKContentRuleListStore, ProxyManager"] L1["Linux — C: WebKitUserContentFilterStore, WebKitNetworkProxySettings"] end CB --> CBM --> A1 PC --> PIF --> A1 PC --> PIF --> I1 PC --> PIF --> M1 PC --> PIF --> L1 TC --> TIF --> A1The matrix below is the single most important table on this page: it tells you, per capability, which native engine actually runs and what happens on the platforms that do not implement it.
| Capability | Android | iOS | macOS | Linux (WPE) | Windows / Web / OHOS |
|---|---|---|---|---|---|
| Content blockers | Custom ContentBlockerHandler in shouldInterceptRequest |
WKContentRuleListStore + userContentController |
Same as iOS | WebKitUserContentFilterStore |
Setting decoded but never consumed |
| Proxy override | androidx.webkit.ProxyController |
WKWebsiteDataStore.proxyConfigurations (iOS 17+) |
Same API (macOS 14+) | WebKitNetworkProxySettings on the default session |
Factory not overridden |
| Tracing | androidx.webkit.TracingController |
Factory not overridden | Factory not overridden | Factory not overridden | Factory not overridden |
Sources: inappwebview_platform.dart, inappwebview_platform.dart, proxy_controller.dart
Content Blockers: The Rule Model
Section titled “Content Blockers: The Rule Model”A content blocker is a trigger/action pair. The trigger decides when the rule applies; the action decides what happens. ContentBlockerTrigger requires urlFilter (a regular expression matched against the URL) and treats everything else as an optional narrowing clause: ifFrameUrl, urlFilterIsCaseSensitive, resourceType, ifDomain, unlessDomain, loadType, ifTopUrl, unlessTopUrl, loadContext. The constructor’s own documentation marks several of these as iOS/macOS-only, and the wire encoder simply drops empty lists and nulls, so the JSON that reaches native code contains only the clauses you actually set.
Sources: content_blocker.dart, content_blocker.dart
One asymmetry is worth knowing before you write your first rule set: ContentBlockerActionType has five members, but the Android native enum only declares three. block-cookies and ignore-previous-rules exist in the shared Dart model and on Apple platforms, while Android’s ContentBlockerActionType is limited to BLOCK, CSS_DISPLAY_NONE and MAKE_HTTPS — an Android build receiving the other two has no constant to map them onto.
| Action | Wire value | Android | Apple / Linux | Notes |
|---|---|---|---|---|
BLOCK |
block |
Yes | Yes | Android returns an empty WebResourceResponse |
CSS_DISPLAY_NONE |
css-display-none |
Yes | Yes | Requires selector; on Android JavaScript must be enabled |
MAKE_HTTPS |
make-https |
Yes | Yes | Android re-fetches the resource over HTTPS itself |
BLOCK_COOKIES |
block-cookies |
No | Yes | Strips cookies from the request header |
IGNORE_PREVIOUS_RULES |
ignore-previous-rules |
No | Yes | Skips all previously triggered actions |
Sources: content_blocker_action_type.dart, ContentBlockerActionType.java, content_blocker.dart
A debug-build caveat follows directly from the constructor source: the guard clauses read assert(!(ifDomain.isEmpty || unlessDomain.isEmpty) == false) and the same shape for ifTopUrl/unlessTopUrl, which as written demands that at least one of each pair be non-empty. Since Dart asserts are compiled out of release and profile builds, a minimal urlFilter-only rule behaves correctly in a shipped app but trips the assertion in a debug run.
Sources: content_blocker.dart
Content Blockers: Three Native Engines
Section titled “Content Blockers: Three Native Engines”The setting itself is a plain list on InAppWebViewSettings, deserialized through _deserializeContentBlockers and serialized back with toMap(). What happens next is entirely platform-local, and the three engines differ in when they evaluate a rule and how they persist compiled state.
| iOS / macOS | Android | Linux (WPE) | |
|---|---|---|---|
| Engine | WKContentRuleListStore.default().compileContentRuleList |
Hand-written matcher over ContentBlocker objects |
webkit_user_content_filter_store_save |
| Evaluation point | WebKit, before the request starts | shouldInterceptRequest in the WebViewClient |
WebKit user content filter |
| Compiled-state identifier | iOS: SHA-256 hex of the rule JSON; macOS: fixed "ContentBlockingRules" |
None (in-memory rule list) | Fixed zikzak_inappwebview_content_rules under the XDG cache dir |
| Concurrency guard | Monotonic compile token + pending-load closure | CopyOnWriteArrayList snapshot per check |
pending_compiles_ set with lifetime flag |
| Empty list | Removes all rule lists, compiles nothing | Clears the rule list | Removes all filters, reports success |
Sources: InAppWebView.swift, InAppWebView.swift, content_blocker_handler.cc, ContentBlockerHandler.java
The Apple implementations are intentionally near-identical: both funnel creation-time settings and runtime setSettings updates through a single applyContentBlockers function that first calls removeAllContentRuleLists(), returns early on an empty list, then compiles asynchronously and adds the result on the main thread. The divergence is the store identifier — iOS derives it from the rule content so a changed ruleset gets a fresh store slot, while macOS still uses the fixed identifier. That difference is the residue of two separate bug fixes and is documented in the changelog rather than hidden.
Sources: InAppWebView.swift, InAppWebView.swift, CHANGELOG.md, CHANGELOG.md
Content Blockers: The Compile Gate
Section titled “Content Blockers: The Compile Gate”Content-rule compilation is asynchronous, and the first navigation must not outrun it — otherwise the initial page load obeys no rules at all. Both Apple platforms solve this with the same two-part mechanism: a boolean isCompilingContentRuleLists plus a single-slot pendingContentRuleListLoad closure, exposed through loadAfterContentRuleLists. Every initial-load path — headless makeInitialLoad, FlutterWebViewController, and InAppBrowserWebViewController.viewDidLoad — routes through that gate.
sequenceDiagram participant App participant WebView as InAppWebView (Swift) participant Store as WKContentRuleListStore App->>WebView: setSettings(contentBlockers: rules) WebView->>WebView: removeAllContentRuleLists() WebView->>Store: compileContentRuleList(identifier, json) Note over WebView: token += 1<br/>isCompiling = true App->>WebView: loadAfterContentRuleLists(load) Note over WebView: isCompiling → store closure, return Store-->>WebView: completion(ruleList, error) WebView->>WebView: token still current? isCompiling = false alt error WebView->>WebView: print(error) — no rule added else ruleList WebView->>WebView: userContentController.add(ruleList) end WebView->>App: pendingLoad() — navigation startsThe critical property is that the pending load fires on success and on error alike, and that a stale completion (an older compile finishing after a newer settings update) is discarded by the token check rather than re-adding rules the consumer just removed. This is the fix for the class of bug where a compile error or an undelivered completion left the WebView permanently blank with no onLoadStart, no onLoadError, and no logs.
Sources: InAppWebView.swift, InAppWebView.swift, FlutterWebViewController.swift, InAppBrowserWebViewController.swift
Android needs no gate because nothing is compiled: the rule list is rebuilt synchronously whenever settings change, and each request is matched against a snapshot copy of that list inside shouldInterceptRequest. Linux occupies a middle position — setContentBlockers compiles asynchronously and the initial load is issued from the completion callback, guarded by a lifetime flag so a WebView disposed mid-compile never dereferences freed state.
Sources: InAppWebView.java, InAppWebViewClient.java, in_app_webview.cc, content_blocker_handler.cc
Content Blockers: How Android Fakes It
Section titled “Content Blockers: How Android Fakes It”Because Android’s WebView has no content-rule engine, ContentBlockerHandler.checkUrl is a hand-written matcher that runs on the resource-request path. It resolves the request URI (falling back to a scheme-rewritten URL when the URI parser rejects it), compiles the url-filter regex once per trigger, and then evaluates resourceType, ifDomain, unlessDomain, loadType, ifTopUrl and unlessTopUrl in that order — returning null (no opinion) as soon as any clause fails to match. When the rule list is empty the whole check is skipped, and when a BLOCK action matches, the handler returns an empty WebResourceResponse which the client then decorates with security headers.
Two Android-specific behaviours surprise people. First, resource types are not known from the request alone: getResourceTypeFromUrl issues an HTTP HEAD request to read Content-Type, and getResourceTypeFromContentType maps MIME types onto ContentBlockerTriggerResourceType — so a rule scoped to image can cost an extra network round trip. Second, CSS_DISPLAY_NONE is implemented by injecting a <style> element plus inline display: none !important via evaluateJavascript after an 800 ms delay, which is why the action requires JavaScript to be enabled; MAKE_HTTPS is implemented by re-issuing the request with HttpURLConnection against the https:// URL and returning that response body.
Sources: ContentBlockerHandler.java, ContentBlockerHandler.java, ContentBlockerHandler.java, ContentBlockerHandler.java
Note also that Android’s native ContentBlockerTrigger has no ifFrameUrl or loadContext fields at all, and that when resource-type is absent the parser adds every resource type — meaning the rule matches any resource rather than being ignored.
Sources: ContentBlockerTrigger.java, ContentBlockerTrigger.java
Proxy: One API, Four Dialects
Section titled “Proxy: One API, Four Dialects”ProxyController is a process-wide singleton with exactly two operations — setProxyOverride(settings:) and clearProxyOverride(profileId:) — and a single ProxySettings value object that carries either androidProxySettings or iOSProxySettings, plus an optional profileId. The platform implementation picks the branch it understands; the other is silently ignored. That is the whole contract, and it is why the same Dart call site can drive four different native APIs.
Sources: proxy_controller.dart, platform_proxy_controller.dart
| Field group | Type | Android | iOS / macOS | Linux |
|---|---|---|---|---|
bypassRules |
List<String> |
ProxyConfig.Builder.addBypassRule |
excludedDomains |
ignore_hosts array |
directs |
List<String> |
addDirect |
— | — |
proxyRules |
List<ProxyRule> |
addProxyRule(url, schemeFilter) |
proxyUrl (single) |
proxyRules → default + per-scheme |
bypassSimpleHostnames |
bool? |
bypassSimpleHostnames() |
— | — |
removeImplicitRules |
bool? |
removeImplicitRules() |
— | — |
reverseBypassEnabled |
bool |
setReverseBypassEnabled (feature-gated) |
— | — |
allowFailover / matchDomains |
— | — | ProxyConfiguration |
— |
profileId |
String? |
ignored | per-profile registry key | ignored |
Sources: platform_proxy_controller.dart, ProxyManager.java, wire.dart
On Apple platforms the URL is the single source of truth: resolveProxyConfiguration normalizes a missing scheme to http, validates host and port (explicit port required, 1–65535), and then branches on scheme — socks/socks5 builds a ProxyConfiguration(socksv5Proxy:), while http/https builds httpCONNECTProxy with tlsOptions: NWProtocolTLS.Options() only for https. Credentials embedded as user:pass@host:port are read from URLComponents (already percent-decoded, so no second decoding pass) and applied via applyCredential on both legs. Failures surface as FlutterErrors with codes INVALID_PROXY_URL or UNSUPPORTED_PROXY_SCHEME rather than as silent no-ops.
Sources: ProxyManager.swift, ProxyManager.swift
The subtlety that costs the most debugging time is per-profile routing. A WebView created with a persistentStoreIdentifier uses a custom WKWebsiteDataStore, and proxyConfigurations written to the default store never reach it. Both Apple ProxyManagers therefore keep a static profileProxies registry keyed by the trimmed identifier plus a weak table of live stores: setProxyOverride with a profileId writes the configuration into the registry and onto every live store of that profile, and applyProxy(forIdentifier:to:) is called at data-store creation time so a store that already exists still gets its route.
sequenceDiagram participant App participant Dart as IosProxyController participant PM as ProxyManager (static) participant Store as WKWebsiteDataStore App->>Dart: setProxyOverride(settings, profileId: "work") Dart->>PM: profileProxies["work"] = config PM->>PM: applyProxyToLiveStores("work", config) PM-->>Store: proxyConfigurations = [config] (existing stores) Note over Store: WebKit applies this only to content<br/>processes created after the write App->>Dart: new InAppWebView(persistentStoreIdentifier: "work") Dart->>PM: applyProxy(forIdentifier: "work", to: newStore) PM-->>Store: proxyConfigurations = [config]Two consequences follow. First, a page that is already loading keeps its previous route until its content process is recreated, so a consumer that wants an immediate switch must reload or recreate the tab. Second, clearProxyOverride is symmetric: a non-empty profileId removes only that profile’s entry and clears its live stores, while a bare call wipes the registry, clears every live store, and resets the default store — the shared store is never touched by a per-profile write, so a profile route cannot leak onto identifier-less profiles.
Sources: ProxyManager.swift, ProxyManager.swift, InAppWebView.swift, ProxyManager.swift
Android is the most literal port: ProxyManager.init() only acquires ProxyController.getInstance() when WebViewFeature.PROXY_OVERRIDE is supported, and every builder call is mirrored one-to-one from ProxySettings. The reverseBypassEnabled flag is additionally gated on PROXY_OVERRIDE_REVERSE_BYPASS, and both setProxyOverride and clearProxyOverride complete asynchronously through an executor, resolving the Dart future only in the completion runnable — which is why the interface documentation insists you await the call before loading a page.
Sources: ProxyManager.java, ProxyManager.java, platform_proxy_controller.dart
Linux translates the same ProxySettings into WebKitNetworkProxySettings on the default network session: the first rule with no scheme filter (or *) becomes the default proxy URI, remaining http/https/socks/socks4/socks5 rules become per-scheme proxies, and bypassRules become the ignore_hosts array. An empty proxyRules list is treated as a clear, and clearProxyOverride sets WEBKIT_NETWORK_PROXY_MODE_DEFAULT. The Dart-side proxySettingsToWire helper is what makes this work: it maps AndroidProxySettings directly, and falls back to IOSProxySettings.proxyUrl as the default proxy with excludedDomains as the bypass list — the fields with no WPE equivalent (directs, bypassSimpleHostnames, removeImplicitRules, reverseBypassEnabled) are simply dropped.
Sources: proxy_manager.cc, proxy_manager.cc, wire.dart, proxy_controller.dart
One security note that applies to every platform: the proxy password travels inside the URL, and IOSProxySettings.toJson() serializes it verbatim. Do not log or persist that JSON — the same object is what crosses the method channel.
Sources: platform_proxy_controller.dart
Tracing: Android Only, and Deliberately So
Section titled “Tracing: Android Only, and Deliberately So”TracingController is the narrowest of the three: start(settings:), stop(filePath:), isTracing(). Only the Android package overrides createPlatformTracingController; on iOS, macOS, Linux, Windows, Web and OHOS the inherited factory throws UnimplementedError, so calling TracingController.instance().start(...) on those platforms fails loudly rather than silently doing nothing.
Sources: tracing_controller.dart, platform_tracing_controller.dart, inappwebview_platform.dart
The native side is a thin TracingConfig builder over androidx.webkit.TracingController, gated on WebViewFeature.TRACING_CONTROLLER_BASIC_USAGE at both init() and every method call — if the feature is missing, start and stop resolve false and isTracing resolves false instead of throwing. stop(filePath:) wraps the path in a FileOutputStream and flushes through a single-thread executor; the resulting JSON is a Chromium trace event stream, loadable in chrome://tracing.
Sources: TracingControllerManager.java, TracingControllerChannelDelegate.java, tracing_controller.dart
TracingSettings has two fields: categories (a mixed list of TracingCategory values and raw strings, where strings may contain wildcards such as blink*) and tracingMode. The category enum is the one place in this page where the wire format is deliberately non-obvious — its values are 1, 2, 64, 8, 32, 0, 16, 4, not 0..7, so tracingCategoryToJson performs a lookup by value rather than using .index. Hand-rolled JSON that assumes sequential indices will silently select the wrong category set.
| Mode | Buffer behaviour | Typical capacity |
|---|---|---|
RECORD_CONTINUOUSLY (default) |
Ring buffer, overwrites oldest events | ~64k events |
RECORD_UNTIL_FULL |
Records until the buffer fills, then stops | ~256k events, larger memory |
Sources: tracing_settings.dart, tracing_category.dart, tracing_mode.dart
Lifecycle and Channel Wiring
Section titled “Lifecycle and Channel Wiring”All three controllers are singletons with no-op dispose on the platform side, because the native objects are process-scoped: the proxy override applies to all WebViews in the app, and the tracing controller traces all WebViews. dispose exists to satisfy the shared Disposable interface, not because there is per-instance state to release. The channel names are stable and identical across platforms, which is what lets one Dart call site work everywhere.
| Controller | Method channel | Platform singleton accessor |
|---|---|---|
ProxyController |
wtf.zikzak/zikzak_inappwebview_proxycontroller |
AndroidProxyController.instance(), IosProxyController.instance(), MacOSProxyController.instance(), LinuxProxyController.instance() |
TracingController |
wtf.zikzak/zikzak_inappwebview_tracingcontroller |
AndroidTracingController.instance() |
Sources: proxy_controller.dart, tracing_controller.dart, proxy_controller.dart, proxy_controller.dart, ProxyManager.java
How These Paths Are Tested
Section titled “How These Paths Are Tested”Because most of the interesting logic lives in Swift, Java and C++ that a Dart test cannot execute, the repo leans on source-scan contract tests: host-runnable Dart tests that strip comments from the native source and assert the presence of the exact code shape that constitutes a fix. They prove shape, not compilation — the build-ios / build-macos CI jobs remain the layer that type-checks. The behavioural layer is a fake-platform test that verifies the core facades forward arguments and propagate results unchanged.
| Test | What it pins |
|---|---|
proxy_tracing_controllers_test.dart |
Core facade passthrough for ProxySettings, TracingSettings, filePath, plus wire JSON for both settings types |
content_blockers_initial_load_test.dart (iOS) |
The applyContentBlockers + loadAfterContentRuleLists gate and SHA-256 identifier (#349) |
content_blockers_parity_test.dart (macOS) |
macOS reaches the same funnel from creation and update paths (#338) |
ios_proxy_profile_registry_contract_test.dart |
profileId is forwarded and the registry is applied at store creation (#410) |
proxy_manager_tls_auth_contract_test.dart |
https:// gets tlsOptions:, URL userinfo becomes applyCredential (#387) |
Sources: proxy_tracing_controllers_test.dart, content_blockers_initial_load_test.dart, content_blockers_parity_test.dart, ios_proxy_profile_registry_contract_test.dart, proxy_manager_tls_auth_contract_test.dart
Where to Go Next
Section titled “Where to Go Next”Content blockers are a setting, so the full construction and update path lives with the widget and its settings object — see InAppWebView Widget and InAppWebViewController and the settings section of Domain Controller Facades: Navigation, JavaScript, Cookies, Settings. The per-profile proxy registry only makes sense alongside persistent data stores, covered in Cookies, Web Storage, and Credential Management and Disposal Lifecycle and KeepAlive Patterns. For the native engines themselves, continue to Android Native Layer (Java), Apple Native Layer (Swift and Swift Package Manager) and Linux WPE WebKit Backend; for how the contract tests above are run per package, see Testing Strategy and Per-Package Commands.