Skip to content

Windows WebView2 Facade and the DevTools Fork

The Windows platform support in zikzak_inappwebview is structured as a two-package stack: zikzak_inappwebview_windows serves as the federated platform-interface facade that adapts platform-agnostic InAppWebView contracts onto Windows, while zikzak_webview_windows is a maintained BSD-3-Clause fork of webview_windows 0.4.0 that adds the Chrome DevTools Protocol (CDP) API surface required for native cookie management, request interception, and navigation policy enforcement on Microsoft Edge WebView2.

Architectural Overview: Two Packages, One Native Process Environment

Section titled “Architectural Overview: Two Packages, One Native Process Environment”

Because Microsoft Edge WebView2 lacks a public off-screen rendering API, zikzak_webview_windows composes WebView2 into Flutter using Windows Graphics Capture (Windows.Graphics.Capture) over a shared Direct3D 11 device, exposing captured frames as a zero-copy shared DXGI texture (FlutterDesktopGpuSurfaceDescriptor) to the Flutter engine. On top of this native texture bridge, zikzak_webview_windows exposes a Dart WebviewController and Webview widget backed by per-instance MethodChannel and EventChannel streams (io.jns.webview.win/<textureId>), and extends upstream webview_windows with Chrome DevTools Protocol methods (callDevToolsProtocolMethod, addDevToolsProtocolEventListener, removeDevToolsProtocolEventListener, and devToolsProtocolEvent).

zikzak_inappwebview_windows implements InAppWebViewPlatform from zikzak_inappwebview_platform_interface and translates platform-agnostic lifecycle events, navigation policies, JavaScript handlers, user scripts, virtual host mappings, and CookieManager calls onto zikzak_webview_windows. Because WebView2 enforces a single process-wide browser environment (ICoreWebView2Environment3), both visible webviews and non-navigating background cookie controllers must share a single userDataPath, browserExecutableFolder, and additionalArguments configuration per process.

graph TD
App["Flutter Application (zikzak_inappwebview)"]
Facade["ZikzakInAppWebViewWindows (Platform Facade)"]
Widget["InAppWebViewWindowsWidget & State"]
Controller["InAppWebViewWindowsController"]
Env["WindowsWebViewEnvironment (Process Singleton)"]
Cookies["WindowsCookieManager (CDP)"]
Fork["zikzak_webview_windows (DevTools Fork)"]
WebviewCtl["WebviewController & Webview Widget"]
Plugin["ZikzakWebviewWindowsPlugin (C++)"]
Host["WebviewHost (ICoreWebView2Environment3)"]
Bridge["WebviewBridge (Texture & Channels)"]
Texture["TextureBridgeGpu (D3D11 / DXGI)"]
Native["Native WebView2 (ICoreWebView2CompositionController)"]
App --> Facade
Facade --> Widget
Facade --> Env
Facade --> Cookies
Widget --> Controller
Widget --> WebviewCtl
Controller --> WebviewCtl
Env --> WebviewCtl
Cookies --> Controller
Cookies --> WebviewCtl
WebviewCtl --> Plugin
Plugin --> Host
Plugin --> Bridge
Bridge --> Texture
Host --> Native
Native --> Texture

The table below summarizes the distinct responsibilities and versioning characteristics of the two Windows packages.

Package Role & Scope Native / Platform Binding Key Differentiator from Upstream
zikzak_inappwebview_windows Federated platform implementation for zikzak_inappwebview (implements: zikzak_inappwebview). Provides InAppWebViewWindowsPlatform, InAppWebViewWindowsController, WindowsWebViewEnvironment, and WindowsCookieManager. Dart-only package bridging zikzak_inappwebview_platform_interface to zikzak_webview_windows. Implements CDP Fetch interception, event-stream state mirroring, process-wide environment conflict checks, and user-script AST guards.
zikzak_webview_windows Low-level WebView2 plugin and widget (pluginClass: ZikzakWebviewWindowsPlugin). Renders WebView2 into a Flutter Texture via D3D11 shared surfaces. C++20 Win32/WinRT plugin (WebView2 1.0.1210.39, WIL 1.0.220914.1) + Dart WebviewController & Webview. Forks webview_windows 0.4.0 (ba0940e) to add the WebView2 CDP API from upstream PR #334 and widens SDK constraints to Dart >=3.8.0 <4.0.0.

Sources: pubspec.yaml, pubspec.yaml, README.md, CHANGELOG.md

Upstream webview_windows 0.4.0 only exposed high-level navigation and script evaluation methods and lacked a Chrome DevTools Protocol bridge, which is mandatory for HttpOnly cookie access and fine-grained request interception in WebView2. Furthermore, upstream webview_windows carried an upper SDK bound of <3.0.0, preventing resolution in Dart 3 applications. zikzak_webview_windows addresses both constraints by forking webview_windows 0.4.0, renaming the Dart package and C++ plugin symbols to zikzak_webview_windows / ZikzakWebviewWindowsPlugin, widening the SDK constraint to >=3.8.0 <4.0.0, and integrating the DevTools protocol layer from PR #334.

Native C++ Composition and Rendering Pipeline

Section titled “Native C++ Composition and Rendering Pipeline”

In the native layer, ZikzakWebviewWindowsPlugin registers a global plugin MethodChannel (io.jns.webview.win) to manage process-wide environment initialization (initializeEnvironment, getWebViewVersion) and per-instance creation (initialize, dispose). Each call to initialize allocates a message-only Win32 window (HWND_MESSAGE), asks WebviewHost to create an ICoreWebView2CompositionController in off-screen mode (offscreen_only = true), wraps the resulting Webview in a WebviewBridge, registers a GPU texture with TextureRegistrar, and returns the assigned textureId to Dart.

Once initialized on the Dart side, WebviewController.initialize() creates per-instance channels io.jns.webview.win/<textureId> (methods) and io.jns.webview.win/<textureId>/events (events). On the C++ side, WebviewBridge instantiates TextureBridgeGpu, which captures the WebView2 visual via IDirect3D11CaptureFramePool, copies incoming frames into a shared ID3D11Texture2D (D3D11_RESOURCE_MISC_SHARED), and hands the DXGI shared handle to Flutter’s GpuSurfaceTexture callback.

Sources: zikzak_webview_windows_plugin.cc, webview_bridge.cc, texture_bridge_gpu.cc, webview.dart

CDP Method Invocation and Event Subscription Wire Format

Section titled “CDP Method Invocation and Event Subscription Wire Format”

At the C++ boundary (WebviewBridge::HandleMethodCall), CDP calls and event subscriptions are marshaled across the per-instance method channel:

  • callDevToolsProtocolMethod: Accepts a map containing method (string) and parameters (JSON-encoded string), invokes Webview::CallDevToolsProtocolMethod on ICoreWebView2, and returns the JSON response string to Dart (which jsonDecodes it in WebviewController.callDevToolsProtocolMethod).
  • addDevToolsProtocolEventListener / removeDevToolsProtocolEventListener: Accepts an event name string and registers or removes an ICoreWebView2DevToolsProtocolEventReceiver. If an event name is already registered in devtools_protocol_event_listeners_, AddDevToolsProtocolEventListener returns false, which WebviewBridge surfaces as a PlatformException(code: 'method_failed').
  • devToolsProtocolEvent: When a registered CDP event fires, WebviewBridge wraps the JSON payload as {"eventName": "<name>", "data": <json>} (except Security.securityStateChanged, which is emitted directly as securityStateChanged), sends it over the event channel, and WebviewController decodes and emits it on devToolsProtocolEvent.

Sources: webview.cc, webview_bridge.cc, webview_bridge.cc, webview.dart, webview.dart

Process-Wide WebView2 Environment and Profile Isolation

Section titled “Process-Wide WebView2 Environment and Profile Isolation”

WebView2 locks browser profile settings (userDataFolder, browserExecutableFolder, additionalBrowserArguments) at the moment CreateCoreWebView2EnvironmentWithOptions completes for a process. In zikzak_inappwebview_windows, WindowsWebViewEnvironment manages this constraint through a static shared initialization future (_initialization) and a dedicated non-navigating background controller (_cookieController).

When initializeShared(settings:) is called:

  1. If no environment has been created yet in the process, _initialize resolves userDataFolder (defaulting to <ApplicationSupportDirectory>/zikzak_webview2_data), ensures the directory exists, and calls WebviewController.initializeEnvironment.
  2. If an environment is already active and settings is null, it reuses the existing process profile.
  3. If settings specifies non-null options that conflict with the active environment (compared via null-safe, separator-tolerant p.equals), initializeShared throws a descriptive StateError naming both the active configuration and the conflicting requested options, rather than silently falling back to a different profile or proxy.

Sources: webview_environment.dart, webview_host.cc, windows_cookie_profile_test.dart

Section titled “CDP-Backed Cookie Management (WindowsCookieManager)”

Standard WebView2 cookie stores include HttpOnly and session cookies that are inaccessible via document.cookie. WindowsCookieManager delegates all cookie operations directly to WebView2’s native CDP Network.* and Storage.* domains without reimplementing cookie storage in Dart.

When a PlatformInAppWebViewController is supplied to a cookie method, _call routes the CDP command through that visible controller’s callDevToolsProtocolMethod. When no controller is supplied (for headless cookie inspection before any view exists), _call awaits WindowsWebViewEnvironment.cookieController(), which lazily initializes a non-navigating WebviewController sharing the process environment.

PlatformCookieManager Method CDP Command(s) Issued Behavioral & Type-Serialization Details
setCookie Network.setCookie Converts maxAge or expiresDate (milliseconds) to CDP seconds; maps HTTPCookieSameSitePolicy to "Strict", "Lax", or "None".
getCookies Network.getCookies Queries by URL array; decodes expires (>= 0 converted from seconds to milliseconds, -1 mapped to null).
getAllCookies Storage.getCookies Retrieves the full profile cookie jar across all domains.
deleteCookie Network.getCookies + Network.deleteCookies Looks up _storedDomain first so cookies stored with a leading dot (e.g., .example.com) are matched and deleted accurately.
deleteCookies Network.getCookies + Network.deleteCookies Scopes URL by path, filters matching cookies by domain and path, and deletes each entry.
deleteAllCookies Network.clearBrowserCookies Clears the entire WebView2 browser cookie store.
removeSessionCookies Storage.getCookies + Network.deleteCookies Iterates all cookies, deletes those with session: true, and returns true if at least one was removed.

Sources: cookie_manager.dart, cookie_manager.dart, webview_environment.dart, webview.cc

Section titled “Navigation State Mirroring and Event Ordering”

Upstream webview_windows publishes navigation state exclusively through EventChannel streams (url, loadingState, historyChanged) and provides no synchronous getters, while loadingState only emits coarse states (none, loading, navigationCompleted) without granular progress percentages. Furthermore, WebviewController.url and WebviewController.historyChanged are single-subscription streams.

InAppWebViewWindowsController acts as the long-lived single listener for url and historyChanged (caching _currentUrl, _canGoBack, _canGoForward) and maps LoadingState.loading to 0% progress and LoadingState.navigationCompleted to 100% progress (while LoadingState.none preserves the last progress value). Simultaneously, _InAppWebViewWindowsWidgetStateImpl subscribes to the broadcast loadingState stream and reads controller.currentUrl inside dispatchLoadingStateChange. This ensures onWebViewCreated fires before any onLoadStart / onLoadStop event and prevents getUrl() from drifting out of sync with the URL delivered to load callbacks.

Sources: in_app_webview_windows_controller.dart, in_app_webview_windows_platform.dart, in_app_webview_windows_platform.dart, in_app_webview_windows_navigation_state_test.dart

CDP Fetch Interception and shouldOverrideUrlLoading

Section titled “CDP Fetch Interception and shouldOverrideUrlLoading”

Because WebView2 has no native navigation-delegate equivalent to decidePolicyForNavigationAction, InAppWebViewWindowsController implements shouldOverrideUrlLoading, custom request headers, and loadData(..., baseUrl: ...) using the CDP Fetch domain with a serialized operation queue (_withFetch).

sequenceDiagram
participant App as Flutter App
participant Ctl as InAppWebViewWindowsController
participant WV2 as WebView2 (CDP Fetch)
participant JS as Web Page / Iframe
App->>Ctl: loadUrl(urlRequest with headers / shouldOverrideUrlLoading)
Ctl->>Ctl: _withFetch: clear pending maps
opt Navigation callback present
Ctl->>WV2: Page.getFrameTree (resolve _mainFrameId before pausing)
end
Ctl->>WV2: addDevToolsProtocolEventListener('Fetch.requestPaused')
Ctl->>WV2: Fetch.enable (patterns: resourceType='Document', stage='Request')
Ctl->>WV2: loadUrl(url)
WV2-->>Ctl: emit Fetch.requestPaused (requestId, frameId, url)
Ctl->>Ctl: _continueRequest: match pending headers / HTML / policy
alt Policy == CANCEL
Ctl->>WV2: Fetch.failRequest (errorReason: 'Aborted')
else Pending HTML for baseUrl
Ctl->>WV2: Fetch.fulfillRequest (responseCode: 200, base64 body)
else Continue Navigation
Ctl->>WV2: Fetch.continueRequest (merged headers)
end
opt No pending headers, HTML, or callback
Ctl->>WV2: Fetch.disable
end

Several critical edge cases are handled by InAppWebViewWindowsController:

  • Pre-Pause Frame Tree Resolution (#449): Calling Page.getFrameTree while a Fetch.requestPaused event is unsettled can deadlock WebView2. _resolveMainFrameId is therefore resolved once before Fetch.enable pauses the document, and _isMainFrame compares frameId against _mainFrameId so subframe navigations are not misreported as main-frame navigations.
  • Chromium URL Canonicalization: Chromium canonicalizes URLs in Fetch.requestPaused (adding / to empty paths and stripping fragments), whereas Dart URLRequest preserves raw strings. _canonicalRequestUrl normalizes both sides before keying _pendingRequestHeaders and _pendingHtmlDocuments.
  • Listener Idempotency (#443): Native AddDevToolsProtocolEventListener throws PlatformException on duplicate registration. _ensureDevToolsListener tracks registered events in _registeredDevToolsEvents so repeated navigations do not crash.
  • Fail-Closed Request Settlement: If Fetch.continueRequest fails, the controller issues Fetch.failRequest (and calls _controller.stop() if the CDP channel itself fails) rather than leaving a paused request hanging.

Sources: in_app_webview_windows_controller.dart, in_app_webview_windows_controller.dart, in_app_webview_windows_controller.dart, windows_navigation_test.dart

JavaScript Bridge, User Scripts, and Virtual Host Mappings

Section titled “JavaScript Bridge, User Scripts, and Virtual Host Mappings”

On the first call to addJavaScriptHandler, _ensureJavaScriptHandlerBridge installs an idempotent script via addScriptToExecuteOnDocumentCreated that exposes window.zikzak_inappwebview.callHandler(handlerName, ...args) using window.chrome.webview.postMessage. Incoming messages on WebviewController.webMessage are routed by _dispatchWebMessage to registered Dart handlers (rejecting reserved platform handler names in _JAVASCRIPT_HANDLER_FORBIDDEN_NAMES), and return values or errors are resolved back into the page via window._zikzakInAppWebViewResolveHandler.

Native Constraints on UserScript Injection

Section titled “Native Constraints on UserScript Injection”

WebView2’s native AddScriptToExecuteOnDocumentCreated API runs unconditionally after global object creation and before document parsing (AT_DOCUMENT_START) across all frames with no native filtering options. InAppWebViewWindowsController bridges this gap in Dart:

  • Injection Time: Scripts with UserScriptInjectionTime.AT_DOCUMENT_END throw UnsupportedError (validated across entire batches in addUserScripts before any script is registered).
  • Frame & Origin Narrowing: _userScriptSource wraps the script body in a guard block checking window === window.top (when forMainFrameOnly is true) and an anchored regular expression matching location.href and location.origin against allowedOriginRules.
  • Script Lifecycle Tracking: _userScriptIds maps each UserScript to a List<ScriptID> so value-equal scripts registered multiple times are tracked individually and cleanly removed on removeUserScript or dispose.

Sources: in_app_webview_windows_controller.dart, in_app_webview_windows_controller.dart, in_app_webview_windows_controller.dart

Teardown, Disposal Invariants, and Verification

Section titled “Teardown, Disposal Invariants, and Verification”

Disposal across the Windows stack requires careful sequencing because WebviewController.dispose() cancels the native event stream subscription and disposes the native WebviewBridge (unregistering the Flutter texture), but does not close its Dart StreamControllers:

  1. _InAppWebViewWindowsWidgetStateImpl.dispose() cancels _loadingStateSubscription and calls _platformController?.dispose().
  2. InAppWebViewWindowsController.dispose() cancels _webMessageSubscription, _devToolsProtocolSubscription, _urlSubscription, _loadingStateSubscription, and _historyChangedSubscription, unregisters all active user scripts and CDP listeners, and disposes _controller if !isKeepAlive and _controller.value.isInitialized.
  3. WindowsWebViewEnvironment.dispose() disposes _cookieController (unless isKeepAlive is true), while keeping the native process environment alive for the lifetime of the process.

Verification is split between host-runnable unit/widget tests in zikzak_inappwebview_windows/test/ (mocking io.jns.webview.win channels and extending WebviewController via _FakeWebviewController) and on-device integration tests in zikzak_inappwebview_windows/integration_test/. For broader architectural context on the federated plugin model, see Monorepo Layout and the Federated Plugin Model and The Platform Interface: The Contract Seam; for cross-platform comparisons, see Apple Native Layer (Swift and Swift Package Manager) and Linux WPE WebKit Backend.