Repository navigation
feat(webview): Implement CoreWebView2Environment and CoreWebView2Profile on Skia Win32 (backport #24062) - #24249
Merged
kazo0 merged 10 commits intoAug 28, 2026
Conversation
…PI surface Replaces the generated NotImplemented stubs for CoreWebView2Environment, CoreWebView2Profile and CoreWebView2ProcessInfo with hand-written partials, and adds CoreWebView2.Environment, .Profile and .BrowserProcessId. The members split across two seams because they have different lifetimes. The statics answer "which browser is installed" and must work before any WebView exists, so they resolve through an owner-less ApiExtensibility extension. The instance members describe a live WebView, so they resolve through opt-in capability interfaces on INativeWebView, alongside the existing ISupportsVirtualHostMapping / ISupportsWebResourceRequested. The capabilities are split three ways rather than bundled, because that split is the portability documentation: data clearing has a real analogue on every head (WKWebsiteDataStore, WebKitWebsiteDataManager, Android WebStorage), profile metadata maps partially, and multi-process diagnostics is Chromium-only. A second head implements one interface without touching Uno.UI. The facades hold the owning CoreWebView2 rather than the native view, and re-resolve on every access: _nativeWebView is assigned in OnOwnerApplyTemplate and reassigned on every re-template, so a captured reference would go stale. For the same reason the async path re-resolves after its await, since EnsureNativeWebViewAsync stays completed across re-templating. Behavior on every platform is unchanged: with nothing registered, each member throws the same NotImplementedException as the deleted stubs, with the same type/member strings so the telemetry key is preserved. ClearBrowsingDataAsync deliberately throws rather than following the graceful in-memory fallback used by SetVirtualHostNameToFolderMapping - a host mapping that quietly buffers is harmless, a data-clearing call that quietly does nothing is a privacy defect. GetAvailableBrowserVersionString(string, CoreWebView2EnvironmentOptions) stays NotImplemented: CoreWebView2EnvironmentOptions is itself an unbacked stub whose getters throw, so the options could not be honored, and ignoring them would return a confidently wrong answer. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 361a3c9)
… Win32 Backs the new API surface on the WebView2Aot backend: the statics through the WebView2Loader.dll exports, and the instance members through ICoreWebView2Profile2 and ICoreWebView2Environment11. The loader probe moves out of Win32NativeAotWebView's static constructor into Win32WebView2Loader.Ensure(), because the statics must be able to load it with no WebView ever created. It uses an explicit lock rather than a static constructor or Lazy: a type initializer caches its failure, so the first DllNotFoundException would be wrapped in a TypeInitializationException and replayed for the rest of the process instead of reporting the real error on each attempt. Win32CoreWebView2EnvironmentStaticsExtension deliberately holds no reference to Win32NativeAotWebView, so a missing runtime stays a per-call failure rather than becoming a startup crash for every Win32 app. Failed HRESULTs from the two statics go through Marshal.ThrowExceptionForHR rather than DirectN's ThrowOnError. The exception type is part of the contract here, since these members are how an app detects a missing runtime: the CLR mapping turns ERROR_FILE_NOT_FOUND into FileNotFoundException, which is what the WinRT surface Uno mirrors produces. ThrowOnError raises a Win32Exception, which would silently break a `catch (FileNotFoundException)` written against Windows. (The WebView2 .NET wrapper used by WinForms/WPF instead raises its own WebView2RuntimeNotFoundException, but that type is not part of the WinAppSDK surface and has no Uno counterpart.) The interfaces are hard-cast: the core WebView is already obtained as ICoreWebView2_22, which is newer than every interface used here, so any runtime able to create the WebView at all satisfies them and a version-fallback ladder would be dead code. ClearBrowsingDataAsync completes on a TaskCompletionSource created with RunContinuationsAsynchronously, because the native handler runs while the WebView2 message loop is being pumped and continuations after clearing routinely call straight back into the WebView. The registration is guarded to net10.0 and later: WebView2Aot is only referenced from net10.0, and on net9.0 the WebView runs on the Microsoft.Web.WebView2 backend, where these members stay NotImplemented. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 53435cf)
…rofile Given_WebView2 cannot host these: its class-level PlatformCondition excludes SkiaWin32 and is evaluated in a separate IsIgnored call that is OR'd with the method-level ones, so no method attribute can opt back in. Given_CoreWebView2Environment needs no WebView in the tree, which is the point: these members must answer before one exists. Given_CoreWebView2Profile loads a real WebView2 and resets WindowContent in a finally. Several assertions are deliberately weaker than they look: - ClearBrowsingDataAsync has no cheap positive observable, so the honest ceiling is "completes without throwing, within a bounded time". The bound turns a native hang into one failed test rather than a stalled run. Note that the AllProfile case destroys state in the app's own WebView2 user-data folder and, unlike PreferredColorScheme, cannot be restored in a finally. - GetProcessInfos asserts neither a count nor a set of kinds: renderer, GPU and utility processes appear asynchronously, and only the browser process is guaranteed once the controller exists. - ProfileName is asserted non-null rather than non-empty. It is genuinely empty on Windows because the controller is created without ICoreWebView2ControllerOptions, so no profile name is requested even though ProfilePath resolves to "Default". - PreferredColorScheme is persisted on-disk profile state shared across the run and across restarts, so the original is restored in a finally. The missing-folder test pins FileNotFoundException, since that type is how an app detects a missing runtime and is what the WinRT surface Uno mirrors produces. Restricted to SkiaWin32 rather than also NativeWinUI: the Inconclusive guard treats a null or empty version as "runtime not installed", so adding the WinAppSDK head before its null-vs-throw behavior is confirmed would make the parity test pass vacuously on exactly the head it was added for. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit acc6670)
Covers the statics, the environment and profile of a live WebView2, and the three ClearBrowsingDataAsync overloads, in two sections so the static half is usable with no WebView2 present. Deliberately not gated to non-Windows, unlike WebView2_EnvironmentOptions: these APIs do exist natively on WinAppSDK, and running the same page on both heads is the whole parity value. It therefore has to survive targets where every call throws, so nothing is called from the constructor - every call sits behind a Click handler that reports the exception type and message. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 4402bef)
Lists the newly supported surface and what other targets do, including two behaviors that are surprising without explanation: ProfileName is always empty on Windows, and the support is specific to the default WebView2 backend on net10.0 and later. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 86aba74)
The note added in 36869f446e conflated two independent things. The statics are registered in Win32Host under a plain TFM guard, while the backend is chosen per-control in Win32NativeWebViewProvider.CreateNativeWebView - nothing connects them. So on net10.0 the statics work whatever UNO_WEBVIEW2_BACKEND says, and only Environment, Profile and BrowserProcessId depend on the backend, because only Win32NativeAotWebView carries the capability interfaces. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit d287809)
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 6824a04)
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit d65ae9c)
Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit 2ea3c48)
The Win32 WebView2 constructor blocks the UI thread in a nested pump while the environment and controller are created. On a cold CI agent that stall consumes the whole 1s WaitForLoaded default, so the first tests of the class timed out waiting on the Border before reaching any assertion. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> (cherry picked from commit ce98cd2)
Merged
3 of 5 tasks
Contributor
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-24249/docs/index.html |
ajpinedam
approved these changes
Aug 27, 2026
Contributor
|
/azp run |
|
Azure Pipelines successfully started running 2 pipeline(s). |
Contributor
|
🤖 Your WebAssembly Skia Sample App stage site is ready! Visit it here: https://unowasmprstaging.z20.web.core.windows.net/pr-24249/wasm-skia-net9/index.html |
Contributor
|
🤖 Your Docs stage site is ready! Visit it here: https://unodocsprstaging.z13.web.core.windows.net/pr-24249/docs/index.html |
Contributor
|
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
GitHub Issue: tracked internally
PR Type:
✨ Feature
What changed? 🚀
CoreWebView2EnvironmentandCoreWebView2Profilewere whole-type[Uno.NotImplemented]stubs. They are nowimplemented on the Skia Windows head:
GetAvailableBrowserVersionString(),GetAvailableBrowserVersionString(string),CompareBrowserVersionString(string, string)CoreWebView2.Profile;ClearBrowsingDataAsync()/(kinds)/(kinds, start, end),ProfileName,ProfilePath,IsInPrivateModeEnabled,DefaultDownloadFolderPath,PreferredColorSchemeCoreWebView2.Environment;BrowserVersionString,UserDataFolder,FailureReportFolderPath,GetProcessInfos();CoreWebView2.BrowserProcessIdEvery other target keeps throwing exactly the
NotImplementedExceptionit threw before, with the sametype/member strings, so the
aka.platform.uno/notimplemented#m=telemetry keys are unchanged.Design
Two seams, because the members have two different lifetimes:
WebView2exists, so they cannot rideINativeWebView. They resolve through an owner-lessApiExtensibilityextension(
ICoreWebView2EnvironmentStaticsExtension). The existing WebView registration uses the typed-owneroverload, which throws on a mismatched owner, so reusing it was not an option.
on
INativeWebView, next to the existingISupportsVirtualHostMapping/ISupportsWebResourceRequested.The capabilities are split three ways rather than bundled because the split is the portability
documentation: data clearing has a real analogue on every head (
WKWebsiteDataStore.removeData,WebKitWebsiteDataManager, AndroidWebStorage), profile metadata maps partially, and multi-processdiagnostics is Chromium-only. A macOS implementer appends one interface to
MacOSNativeWebViewand writes onemethod — nothing in
Uno.UIchanges.The façades hold the owning
CoreWebView2, never the native view, and re-resolve on every access:_nativeWebViewis assigned inOnOwnerApplyTemplateand reassigned on every re-template. The async pathre-resolves after its await too, because
_nativeWebViewInitializedTcsis never reset, soEnsureNativeWebViewAsync()stays completed even after re-templating into a template with no native view.ClearBrowsingDataAsyncthrows when the native view is absent rather than following the graceful in-memoryfallback used three lines away by
SetVirtualHostNameToFolderMapping. A host mapping that quietly buffers isharmless; a data-clearing call that quietly resolves without clearing is a privacy defect.
Reviewer notes — things not visible in the diff
The sync generator could not be run locally.
dotnet restoreonbuild/filters/Uno.UI-top-projects-for-sync-gen.slnffails withNETSDK1147, because thewasm-toolsworkload is not installed on the dev machine. The
Generated/edits were insteadverified against the generator's own rules — type guard flipped to
#if false || false || false || false || false || false, each removed member replaced in place by// Skipping already declared property {Name}or
// Skipping already declared method {fully-qualified signature}, all// Forced skipping of methodlines untouched — and cross-checked against
CoreWebView2Settings.cs, which the generator authored in thesame shape. The new comments sit alongside pre-existing generator-authored ones in the same files with
identical formatting.
winappsdk-sync-checkis the real gate here.Same cause:
Uno.UI.netcoremobilewas not compile-verified locally. Everything else was, on bothTFM bands with analyzers enabled:
Uno.UI.Skia,Uno.UI.Reference,Uno.UI.Wasm,Uno.UI.Runtime.Skia.Win32,Uno.UI.RuntimeTestsandSamplesAppall build clean at net9.0 and net10.0.The new
Uno.UIfiles are unguarded (matchingCoreWebView2Settings.cs) and reference only generated enumsthat exist on all six platform slots, so the mobile variant should be safe too — but CI is the check.
Note the net9.0 split:
WebView2Aotis only referenced from net10.0, so the Win32 statics registration isbehind
#if NET10_0_OR_GREATERand the whole feature staysNotImplementedon net9.0. That guard becomesvacuously true once net9 is dropped (
feature/breakingchangesalready hasNetPrevious=net10.0), and canbe removed then.
ProfileNameis always empty on Windows. Not a marshalling bug:ProfilePathcorrectly returns…\LocalState\WebView2\EBWebView\DefaultandDefaultDownloadFolderPathreturns the user's Downloadsfolder. It is empty because the controller is created without
ICoreWebView2ControllerOptions, so no profilename is ever requested. The test asserts the true contract and the doc explains it; making it non-empty means
passing controller options, which changes on-disk profile layout and deserves its own decision.
CompareBrowserVersionString(null, …)throwsArgumentNullExceptionwhere the WebView2 stack throwsArgumentException.ArgumentNullExceptionderives fromArgumentException, so acatch (ArgumentException)written against Windows still works — the parity direction that matters holds. The explicit guard also avoids
handing a null pointer to a native export whose null behaviour is unverified.
The type-level
[Uno.NotImplemented]attribute is gone fromCoreWebView2Environment,CoreWebView2ProfileandCoreWebView2ProcessInfo, which changes IDE/analyzer surfacing for them. Membersthat remain unimplemented keep their per-member attributes. This is the correct outcome of the types no
longer being wholly unimplemented, but it is a visible change.
When_ClearBrowsingDataAsync_Completes(1)destroys real state in the app's own WebView2 user-datafolder. It is scoped to
LocalStateso it is acceptable, but unlike thePreferredColorSchemetest there isno
finallythat can restore it.Exception-type parity is derived, not observed end-to-end. Verified:
Marshal.GetExceptionForHR(0x80070002)is
FileNotFoundException; DirectN'sThrowOnErrordoes not use the CLR mapping (it builds aWin32Exception);WebView2RuntimeNotFoundExceptionexists only in the WebView2 .NET wrapper and has noWinAppSDK/WinRT counterpart, so it is not the parity target. What was not done is running a WinAppSDK app
to observe it directly. Relatedly, the
0x80070002observation comes from pointing at a folder with nobrowser; a machine with no runtime installed at all was not available to test.
Behaviour change worth noting: the loader probe moved out of
Win32NativeAotWebView's staticconstructor into
Win32WebView2Loader.Ensure(). The instance path is unchanged, but the new static pathsurfaces a direct
DllNotFoundExceptionrather than one wrapped in aTypeInitializationException.Scope deliberately left out
GetAvailableBrowserVersionString(string, CoreWebView2EnvironmentOptions)—CoreWebView2EnvironmentOptionsis an unbacked stub whose getters throw, so the options cannot be honoured and ignoring them would return a
wrong answer. Unblocks once that type gets real backing fields, which is also the right time to retire the
FeatureConfiguration.WebView2.*injection point.CoreWebView2CookieManager/CoreWebView2Cookie. Verified independent of this work:ICoreWebView2Profile2.ClearBrowsingDatatakes only(kinds, handler)and does the work inside the browserprocess, so
ClearBrowsingDataAsync(Cookies)never touches the cookie manager. What is therefore still notpossible: reading cookies, and targeted delete by name/domain/path. Adding it later is one more capability
interface — no reshaping.
CreateAsync/CreateWithOptionsAsync,Profile.CookieManager/.Delete()/.IsGeneralAutofillEnabled/.IsPasswordAutosaveEnabled/.PreferredTrackingPreventionLevel, and theBrowserProcessExited/ProcessInfosChanged/NewBrowserVersionAvailable/Deletedevents.Pre-existing issues found while working here (not fixed in this PR)
get_Source,get_DocumentTitle,get_Uri,get_WebMessageAsJsonand the.Request.csaccessors inWin32NativeAotWebViewall leak caller-ownedPWSTRs via a bare.ToString().ExecuteScriptAsynclacksRunContinuationsAsynchronously, the same hazard this PR guards against inClearBrowsingDataAsync.Given_WebView2'sSkiaWin32exclusion predates theWebView2Aotbackend. This PR demonstrates a liveWebView2runs fine under the runtime-test harness on Skia Win32, so that exclusion now looks stale.PR Checklist ✅
Screenshots Compare Test Runresults.This is an automatic backport of pull request #24062 done by [Mergify](https://mergify.com).