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 --> TextureThe 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
The DevTools Fork: zikzak_webview_windows
Section titled “The DevTools Fork: zikzak_webview_windows”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 containingmethod(string) andparameters(JSON-encoded string), invokesWebview::CallDevToolsProtocolMethodonICoreWebView2, and returns the JSON response string to Dart (whichjsonDecodes it inWebviewController.callDevToolsProtocolMethod).addDevToolsProtocolEventListener/removeDevToolsProtocolEventListener: Accepts an event name string and registers or removes anICoreWebView2DevToolsProtocolEventReceiver. If an event name is already registered indevtools_protocol_event_listeners_,AddDevToolsProtocolEventListenerreturnsfalse, whichWebviewBridgesurfaces as aPlatformException(code: 'method_failed').devToolsProtocolEvent: When a registered CDP event fires,WebviewBridgewraps the JSON payload as{"eventName": "<name>", "data": <json>}(exceptSecurity.securityStateChanged, which is emitted directly assecurityStateChanged), sends it over the event channel, andWebviewControllerdecodes and emits it ondevToolsProtocolEvent.
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:
- If no environment has been created yet in the process,
_initializeresolvesuserDataFolder(defaulting to<ApplicationSupportDirectory>/zikzak_webview2_data), ensures the directory exists, and callsWebviewController.initializeEnvironment. - If an environment is already active and
settingsisnull, it reuses the existing process profile. - If
settingsspecifies non-null options that conflict with the active environment (compared via null-safe, separator-tolerantp.equals),initializeSharedthrows a descriptiveStateErrornaming 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
CDP-Backed Cookie Management (WindowsCookieManager)
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
Navigation State Mirroring and Event Ordering
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 endSeveral critical edge cases are handled by InAppWebViewWindowsController:
- Pre-Pause Frame Tree Resolution (#449): Calling
Page.getFrameTreewhile aFetch.requestPausedevent is unsettled can deadlock WebView2._resolveMainFrameIdis therefore resolved once beforeFetch.enablepauses the document, and_isMainFramecomparesframeIdagainst_mainFrameIdso 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 DartURLRequestpreserves raw strings._canonicalRequestUrlnormalizes both sides before keying_pendingRequestHeadersand_pendingHtmlDocuments. - Listener Idempotency (#443): Native
AddDevToolsProtocolEventListenerthrowsPlatformExceptionon duplicate registration._ensureDevToolsListenertracks registered events in_registeredDevToolsEventsso repeated navigations do not crash. - Fail-Closed Request Settlement: If
Fetch.continueRequestfails, the controller issuesFetch.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”Lazy-Installed JavaScript Bridge
Section titled “Lazy-Installed JavaScript Bridge”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_ENDthrowUnsupportedError(validated across entire batches inaddUserScriptsbefore any script is registered). - Frame & Origin Narrowing:
_userScriptSourcewraps the script body in a guard block checkingwindow === window.top(whenforMainFrameOnlyistrue) and an anchored regular expression matchinglocation.hrefandlocation.originagainstallowedOriginRules. - Script Lifecycle Tracking:
_userScriptIdsmaps eachUserScriptto aList<ScriptID>so value-equal scripts registered multiple times are tracked individually and cleanly removed onremoveUserScriptordispose.
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:
_InAppWebViewWindowsWidgetStateImpl.dispose()cancels_loadingStateSubscriptionand calls_platformController?.dispose().InAppWebViewWindowsController.dispose()cancels_webMessageSubscription,_devToolsProtocolSubscription,_urlSubscription,_loadingStateSubscription, and_historyChangedSubscription, unregisters all active user scripts and CDP listeners, and disposes_controllerif!isKeepAliveand_controller.value.isInitialized.WindowsWebViewEnvironment.dispose()disposes_cookieController(unlessisKeepAliveistrue), 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.