You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
WebView2.Close() was the generated not-implemented stub on Skia. On WebAssembly, a closed WebView2 kept its <iframe>, with its document still loaded, until the garbage collector removed it (#24841), or for good while the control was still referenced. This PR implements Close() on WebAssembly, following WinUI's WebView2::Close and CloseInternal (src/controls/dev/WebView2/WebView2.cpp).
On WebAssembly, Close() now:
detaches the WebView2 from its CoreWebView2. CoreWebView2 returns null; NavigationStarting, NavigationCompleted and WebMessageReceived are no longer raised, and history and source changes no longer update CanGoBack, CanGoForward and Source; CanGoBack and CanGoForward are reset to false;
stops the CoreWebView2 itself from raising events, as WinUI's closed CoreWebView2 does, so an app that kept a reference to it gets none either. That includes a navigation that is completing when a handler closes the control: if a DocumentTitleChanged or SourceChanged handler calls Close(), SourceChanged and NavigationCompleted aren't raised after it;
releases the native web view: NativeWebView.Dispose(), which had a // Todo and was never called, now unregisters the instance and removes the load listener. A navigation that was requested but hasn't started yet (NavigationStarting is raised from the dispatcher) is dropped, and so is one that a NavigationStarting handler closes the control from. An ExecuteScriptAsync that was still waiting to run completes with an empty string, which is what WinUI's code returns once the browser is gone: its ExecuteScriptAsync swallows the closed browser's ERROR_INVALID_STATE and returns its default value (WebView2.cpp, lines 1903-1929). Without this, removing the iframe would make the script fail with a JSException. The same happens when the control is retemplated while a script waits;
removes the iframe from the page right away: it is detached from its ContentPresenter, then its BrowserHtmlElement is disposed, which also cancels the removal fix(wasm): Remove WebView2 iframe once it is collected #24841 scheduled for collection time.
The control's state is cleared first and the browser is released last, so if releasing it fails (a browser call throws), the control is still fully closed and the iframe is still removed. WinUI's Close() isn't documented to throw, so the error is logged rather than thrown. Retemplating releases the replaced browser through the same code, so a failure there no longer stops the new template from getting its own web view.
Afterwards, the WebView2 behaves as in WinUI:
After webView.Close()
Before
After
The iframe
stays in the page until the WebView2 is collected
removed right away
CoreWebView2
still the same object
null, as in WinUI
EnsureCoreWebView2Async()
completes
fails with ObjectDisposedException, as in WinUI (RO_E_CLOSED), with WinUI's message and no object name
Setting Source
navigates
throws ObjectDisposedException, as in WinUI (RO_E_CLOSED)
NavigateToString, Reload
work
throw InvalidOperationException, as in WinUI (E_ILLEGAL_METHOD_CALL), with WinUI's messages
ExecuteScriptAsync
works
returns an operation that fails with InvalidOperationException, as in WinUI, where the method is a coroutine; the call itself doesn't throw
A script that was still waiting to run
runs and returns its result
completes with an empty string, which is what WinUI's code returns once the browser is gone
GoBack, GoForward
work
do nothing, as in WinUI
CanGoBack, CanGoForward
unchanged
false, as in WinUI
Events of the CoreWebView2, including the rest of a navigation that a handler closes the control from
keep coming
none, as in WinUI
A second Close()
does nothing
does nothing
Unloading or loading the closed control again
the control keeps working
doesn't touch the removed iframe or create a new one
CoreWebView2 keeps its non-nullable signature, as in #23754, but returns null once the control is closed, as WinUI does. Apps that called Close() while it did nothing (for example in an Unloaded handler) and then reused the control now get CoreWebView2 == null and the exceptions above, as on WinUI.
Closing from CoreWebView2Initialized. A handler of CoreWebView2Initialized may close the control, both when it's raised from the first Loaded and when it's raised from EnsureCoreWebView2Async. The Loaded handler rechecks the CoreWebView2 after raising the event, so it doesn't throw, and no iframe is left. EnsureCoreWebView2Async then completes successfully with CoreWebView2 null, as in WinUI, where TryCompleteInitialization returns early once the control is closed.
Retemplating. When a WebView2 gets a new template, the native web view of the replaced template is released and its iframe removed, instead of staying in the page (and in the static registry, which kept the WebView2 alive). The new native web view is registered for the iframe's load events right away when the control is already loaded, the way Loaded registers it the first time, so a retemplated WebView2 keeps raising NavigationCompleted when a document loads. Before, only Loaded registered it, so after a retemplate those events were lost. The same applies to a WebView2 that is loaded while Collapsed (or inside a collapsed container): a collapsed element isn't measured, so its template is applied only once it's shown, after Loaded, and before this PR its loads never raised NavigationCompleted either. The registration is shared Skia code, so on macOS a retemplated or collapsed-at-load WebView2 now also gets WebMessageReceived (its OnLoaded registers the WebKit message handler); that's untested on macOS. A retemplated WebView2 starts again at about:blank in its new iframe; WinUI's browser isn't part of the template, so it keeps its page.
Deliberate differences from WinUI.
A pending EnsureCoreWebView2Async fails with ObjectDisposedException when the control is closed. WinUI's Close() only stops a creation that hasn't started yet (CreateCoreObjects checks m_isClosed when it starts), and a creation already in flight completes, so a waiting call succeeds there. Uno's EnsureCoreWebView2Async waits for the template to create the native web view, which WinUI doesn't wait for, and a closed control never creates one, so the call fails as one made after Close() does.
A CoreWebView2 reference kept from before Close() does nothing: Navigate, NavigateToString, Reload, GoBack, GoForward and Stop return without effect and ExecuteScriptAsync returns null. WinUI's CoreWebView2 fails those calls with ERROR_INVALID_STATE (a COMException in .NET); WinUI's own WebView2 wraps most of its calls to swallow that error (CoreWebView2RunIgnoreInvalidStateSync). Uno has no established way to raise that error from CoreWebView2: nothing in Uno produces ERROR_INVALID_STATE or a COMException for it, and its members already return without effect whenever it has no native web view, for example before the template is applied. Matching WinUI would mean a new error path for this one case, so this PR leaves it.
Other Skia targets. Win32, macOS, X11, and Skia on Android and iOS have no way to close their native web view yet, and each needs its own native teardown. A native web view opts in through a new internal ISupportsClose interface. When the native web view doesn't implement it, Close() keeps reporting itself as not implemented and changes nothing, as before. The one change there: a Close() called before the control has created its native web view closes the control, so it never creates one, as in WinUI.
The generated [NotImplemented("__SKIA__")] stub for Close() is gone (the generated file now has the usual "Skipping already declared method" line, and the WinAppSDK Sync Generator Check passes). To keep the gap visible at build time, Close() is marked [Uno.NotImplemented("__DESKTOP__", "__ANDROID__", "__APPLE_UIKIT__")]. In Uno.UI, which is a single Skia build, the analyzer matches tokens other than __SKIA__ against the app's own symbols (#24554), so desktop, Android, iOS and tvOS apps get UNO0001 for Close() and WebAssembly apps don't. A plain net10.0 library gets no warning, as for a WinRT API that WebAssembly implements. ApiInformation.IsMethodPresent reads any [NotImplemented] as absent, so it still returns false for Close() on every target, WebAssembly included, as before this PR. Close() also still reports itself as not implemented at run time on those targets once the web view exists.
Docs.WebView.md has a new short section, "Closing a WebView2": Close() releases the web view on WebAssembly, other targets get UNO0001 at build time and report it as not implemented at run time once the web view exists, and a Close() before the web view is created closes the control on every target.
Relation to #23754.#23754 also implements Close(), as part of a larger change. This PR uses the same internal interface, ISupportsClose in Uno.UI.Xaml.Controls with a Close() method, and the same WebView2 behavior after closing, ported from the same WinUI code, so the two can be reconciled whichever goes in first. The difference is on WebAssembly: #23754 navigates the iframe to about:blank and leaves it in the page until the control is collected, while this PR removes it from the page right away. The second to merge gets textual conflicts in WebView2.cs, WebView2.Properties.cs, CoreWebView2.cs, ISupportsClose.cs (both add it; #23754's has no doc comments), NativeWebView.wasm.cs and WebView.md.
Given_WebView2_Close.cs (new) compiles for WinUI too, so CI checks these against WinUI:
When_Closed_Then_CoreWebView2_Is_Null_And_Members_Fail (WinUI, Skia WebAssembly): checks the table above for the members that don't depend on the iframe: CoreWebView2, CanGoBack/CanGoForward, a second Close(), GoBack/GoForward, and the exception types of EnsureCoreWebView2Async, Source, NavigateToString, Reload and ExecuteScriptAsync.
When_Closed_With_Navigation_Pending_Then_NavigationStarting_Is_Not_Raised: CoreWebView2.Navigate, then Close(); neither the CoreWebView2 nor the WebView2 handler is called.
When_Closed_During_Navigation_Completion_Then_CoreWebView2_Raises_No_More_Events, once closing from SourceChanged and once from DocumentTitleChanged while a page loads: the CoreWebView2 raises nothing after Close().
When_Closed_From_NavigationStarting_Then_Navigation_Is_Dropped: the control is closed and the iframe removed. The dropped load itself can't be observed (see the results).
When_Releasing_Browser_Fails_Then_WebView2_Is_Still_Closed: makes the browser call that removes the iframe's listeners throw, and checks that Close() doesn't throw, the control is closed and the iframe is removed.
When_Releasing_Browser_Fails_On_Retemplate_Then_New_Template_Gets_A_Browser: the same failure while the control is retemplated; the old iframe is removed, the new template presents a new one, and it navigates.
When_Retemplated_Then_Navigation_Completes and When_Shown_After_Collapsed_Load_Then_Navigation_Completes: both wait for the NavigationCompleted whose NavigationId is the one NavigationStarting reported for a NavigateToString, which is raised when the iframe loads the document. That skips the early one raised before NavigationStarting (WebView2 on WebAssembly raises NavigationCompleted before NavigationStarting, so each navigation completes twice #25806), so the tests keep working once that event is gone.
UnoNotImplementedTests.When_UnoUI_Stub_Is_Implemented_On_Wasm_Only (analyzer test): a Uno.UI member with Close()'s tokens is reported for the desktop, Android, iOS and tvOS consumer symbol sets, and not for WebAssembly or a plain net10.0 library.
I ran all runtime tests matching WebView locally (SamplesApp net10.0-browserwasm, Chrome) on this branch at e477aea, on master at 98b28f8: the 24 that run on Skia WebAssembly pass (two of them are the two cases of one test), and the other WebView, WebView2 and CoreWebView2 tests are skipped there. The browser console shows the two simulated release failures logged as errors. Each of the three commits builds on its own (Uno.UI.Runtime.WebAssembly.Browser and Uno.UI.RuntimeTests).
Earlier runs, with the new tests on the code before each change:
fails when the dropped-navigation checks in ScheduleNavigationStarting are removed (NavigationStarting raised once)
passes
Those runs were on the code this PR had before each change: its first pushed head (a283220) and later intermediate states, with the late-template registration removed for the collapsed-load test and the dropped-navigation checks removed for the navigation-pending test. By the code, every test in the table except the navigation-pending one fails on a283220. When_Closed_From_NavigationStarting_Then_Navigation_Is_Dropped passes even without the check that skips the load after a handler closed the control: the load then fails on the removed iframe, and the dispatcher only logs that error, so the test can't see it. The other tests passed before and after. The two NavigationCompleted tests passed on the rebased branch with the NavigationId wait.
Given_WebView2_Close.cs couldn't be run on WinUI locally (that needs the WinAppSDK head build). It uses only public WinUI and MSTest API, no Uno-only types, so it compiles for the WinUI head, and CI's WinUI runtime tests will run it there.
Implements deterministic WebView2.Close() on WebAssembly for #25736, extending the earlier garbage-collection cleanup with immediate iframe removal and WinUI-compatible closed-control behavior.
Changes:
Adds opt-in native teardown while preserving unsupported-platform behavior.
Releases the WebAssembly iframe, removes listeners, and cancels queued navigation.
Adds runtime tests for iframe removal, closed-control behavior, and collection.
[P2] If the template is applied before the first load, a CoreWebView2Initialized handler can close the control during EnsureCoreWebView2Async(), yet this await succeeds because native initialization has already completed. The caller therefore sees successful initialization with CoreWebView2 == null. Recheck _coreWebView2 after the await and throw ObjectDisposedException if the callback closed the control.
Re the review summary note on WebView2.cs:91: completing successfully there is what WinUI does. When a CoreWebView2Initialized handler closes the control, WinUI's EnsureCoreWebView2Async still finishes without error (CreateCoreObjects only skips TryCompleteInitialization because m_coreWebView is now null), and CoreWebView2 is null afterwards, so that case stays as is. Fixed in e29d410: when the template isn't applied yet, the same case now completes too instead of throwing ObjectDisposedException. Runtime tests cover both orders; the new test fails without the change on WebAssembly and Skia desktop.
[P2] Retemplating a loaded WebView2 replaces _nativeWebView without unregistering the old instance, and this new callback keeps its iframe wrapper reachable from the static _elementIdToNativeWebView dictionary. A later Close() disposes only the replacement, leaving the old iframe and document alive even after garbage collection. Tear down the superseded native view before replacing it in CoreWebView2.OnOwnerApplyTemplate(), and add a retemplate-then-close regression test.
Re the review summary note on BrowserWebViewProvider.cs:34: confirmed, fixed in a283220. A new template gets a new iframe and native view, and the replaced native view stayed registered in the static dictionary. That part predates this PR, but the removal callback added here made the stale entry keep the replaced iframe alive as well. OnOwnerApplyTemplate() now releases the replaced native view (WebAssembly only, through ISupportsClose) before creating the new one, which unregisters it and removes its iframe. Other platforms keep their current behavior; WinUI doesn't host the browser in the template, so a template change doesn't affect it there. The new runtime test When_Retemplated_Then_Closed_Then_Replaced_Iframe_Is_Removed retemplates a loaded WebView2, closes it and collects garbage; without the fix the replaced iframe stays in the DOM.
The reason will be displayed to describe this comment to others. Learn more.
🟡 Changes recommended
Closing the WebView from a SourceChanged or DocumentTitleChanged handler still allows NavigationCompleted to fire on the retained core after closure, requiring closed-state checks and a regression test.
The reason will be displayed to describe this comment to others. Learn more.
Reviewed by reading the code against this PR's head and WinUI's WebView2.cpp. I haven't built or run it.
The documented "after close" behavior matches WinUI: RO_E_CLOSED for Source and EnsureCoreWebView2Async, the E_ILLEGAL_METHOD_CALL messages, ExecuteScriptAsync failing the operation rather than the call, GoBack/GoForward doing nothing, and ERROR_INVALID_STATE giving an empty script result. The two differences from WinUI (a pending EnsureCoreWebView2Async fails, and a retemplate restarts at about:blank) are disclosed. I also checked the new OnLoaded call in OnApplyTemplate: template application runs before RaiseLoaded, so the normal path doesn't register twice.
One point to decide:
Losing the build-time warning on other targets. Removing the generated [Uno.NotImplemented("__SKIA__")] stub means apps on desktop and mobile no longer get a build-time warning for Close(). Once the web view exists, those targets only report not-implemented at runtime, and the control keeps working. Since the title says "Implement WebView2.Close" and only WebAssembly releases the browser, I'd keep the gap visible, for example with [Uno.NotImplemented] limited to the targets that lack ISupportsClose if the analyzer allows it, or at least call it out in the release notes.
Tick the box to add this pull request to the merge queue (same as @mergifyio queue). If it does not match the queue conditions yet, it enters the queue once it does.
Hi @mikernet, heads-up: we rebased your branch onto current master and force-pushed it.
The only red check was Desktop Linux › Snapshot Tests, which crashed with a segfault (exit code 139) when the app shut down after the last screenshot. That wasn't caused by your changes. The CI build tested your branch merged with an older master that still included the IdleFrameProbe sample, which was making Linux snapshot runs segfault on exit. #26205 fixed that on master shortly afterwards. Re-running the job always rebuilds the same old merge, so the retries kept failing. Rebasing gets CI to build against a master that has the fix.
The rebase applied cleanly and your three commits are unchanged apart from their SHAs:
642549a981 fix(wasm): Remove a retemplated WebView2's iframe
3586f44b90 fix(webview): Register late-templated web views
Because the history was rewritten, please reset your local branch before you push again, or your next push will either be rejected or bring back the old commits:
Removing the generated stub dropped the UNO0001 build warning for
WebView2.Close() on every target, but only the WebAssembly web view can
release its browser. Mark Close() not implemented for desktop, Android
and iOS/tvOS apps: in Uno.UI, tokens other than __SKIA__ are matched
against the app's own symbols, so WebAssembly apps get no warning. Add
an analyzer test for that token set and mention the warning in the docs.
On the build-time warning: I kept the gap visible. Close() is now marked [Uno.NotImplemented("__DESKTOP__", "__ANDROID__", "__APPLE_UIKIT__")] (e477aea). Since #24554, the analyzer matches tokens other than __SKIA__ on a Uno.UI member against the app's own symbols, so desktop, Android, iOS and tvOS apps get UNO0001 for Close() and WebAssembly apps don't. A plain net10.0 library gets no warning, the same as for a WinRT API that WebAssembly implements. A new analyzer test, When_UnoUI_Stub_Is_Implemented_On_Wasm_Only, checks this token set against the consumer symbol sets the other tests use. WebView.md and the description now mention the warning.
One side effect: ApiInformation.IsMethodPresent treats any [NotImplemented] as absent, so it still returns false for Close() on every target, WebAssembly included, as it did before this PR.
The reason will be displayed to describe this comment to others. Learn more.
Thanks @mikernet, the [Uno.NotImplemented("__DESKTOP__", "__ANDROID__", "__APPLE_UIKIT__")] approach in e477aea is exactly what I was after, and the analyzer test pins it down nicely. Re-checked the rest against WebView2::CloseInternal/ResetProperties in WinUI and it still lines up. Non-WASM backends stay untouched (no ISupportsClose), so nothing half-tears-down there.
Heads-up for whoever lands second: besides #23754 (which you already called out), #25593 adds EnsureCoreWebView2Async(CoreWebView2Environment) that calls CoreWebView2.AdoptEnvironment(...) directly, so after this PR it would NRE on a closed control instead of throwing ObjectDisposedException. Likewise the new CoreWebView2 events/PostWebMessage* in #25592 will want the _isClosed guard. No action needed here.
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
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: closes #25736
PR Type:
✨ Feature
What changed? 🚀
WebView2.Close()was the generated not-implemented stub on Skia. On WebAssembly, a closedWebView2kept its<iframe>, with its document still loaded, until the garbage collector removed it (#24841), or for good while the control was still referenced. This PR implementsClose()on WebAssembly, following WinUI'sWebView2::CloseandCloseInternal(src/controls/dev/WebView2/WebView2.cpp).On WebAssembly,
Close()now:WebView2from itsCoreWebView2.CoreWebView2returnsnull;NavigationStarting,NavigationCompletedandWebMessageReceivedare no longer raised, and history and source changes no longer updateCanGoBack,CanGoForwardandSource;CanGoBackandCanGoForwardare reset tofalse;CoreWebView2itself from raising events, as WinUI's closedCoreWebView2does, so an app that kept a reference to it gets none either. That includes a navigation that is completing when a handler closes the control: if aDocumentTitleChangedorSourceChangedhandler callsClose(),SourceChangedandNavigationCompletedaren't raised after it;NativeWebView.Dispose(), which had a// Todoand was never called, now unregisters the instance and removes theloadlistener. A navigation that was requested but hasn't started yet (NavigationStartingis raised from the dispatcher) is dropped, and so is one that aNavigationStartinghandler closes the control from. AnExecuteScriptAsyncthat was still waiting to run completes with an empty string, which is what WinUI's code returns once the browser is gone: itsExecuteScriptAsyncswallows the closed browser'sERROR_INVALID_STATEand returns its default value (WebView2.cpp, lines 1903-1929). Without this, removing the iframe would make the script fail with aJSException. The same happens when the control is retemplated while a script waits;ContentPresenter, then itsBrowserHtmlElementis disposed, which also cancels the removal fix(wasm): Remove WebView2 iframe once it is collected #24841 scheduled for collection time.The control's state is cleared first and the browser is released last, so if releasing it fails (a browser call throws), the control is still fully closed and the iframe is still removed. WinUI's
Close()isn't documented to throw, so the error is logged rather than thrown. Retemplating releases the replaced browser through the same code, so a failure there no longer stops the new template from getting its own web view.Afterwards, the
WebView2behaves as in WinUI:webView.Close()WebView2is collectedCoreWebView2null, as in WinUIEnsureCoreWebView2Async()ObjectDisposedException, as in WinUI (RO_E_CLOSED), with WinUI's message and no object nameSourceObjectDisposedException, as in WinUI (RO_E_CLOSED)NavigateToString,ReloadInvalidOperationException, as in WinUI (E_ILLEGAL_METHOD_CALL), with WinUI's messagesExecuteScriptAsyncInvalidOperationException, as in WinUI, where the method is a coroutine; the call itself doesn't throwGoBack,GoForwardCanGoBack,CanGoForwardfalse, as in WinUICoreWebView2, including the rest of a navigation that a handler closes the control fromClose()CoreWebView2keeps its non-nullable signature, as in #23754, but returnsnullonce the control is closed, as WinUI does. Apps that calledClose()while it did nothing (for example in anUnloadedhandler) and then reused the control now getCoreWebView2 == nulland the exceptions above, as on WinUI.Closing from
CoreWebView2Initialized. A handler ofCoreWebView2Initializedmay close the control, both when it's raised from the firstLoadedand when it's raised fromEnsureCoreWebView2Async. TheLoadedhandler rechecks theCoreWebView2after raising the event, so it doesn't throw, and no iframe is left.EnsureCoreWebView2Asyncthen completes successfully withCoreWebView2null, as in WinUI, whereTryCompleteInitializationreturns early once the control is closed.Retemplating. When a
WebView2gets a new template, the native web view of the replaced template is released and its iframe removed, instead of staying in the page (and in the static registry, which kept theWebView2alive). The new native web view is registered for the iframe'sloadevents right away when the control is already loaded, the wayLoadedregisters it the first time, so a retemplatedWebView2keeps raisingNavigationCompletedwhen a document loads. Before, onlyLoadedregistered it, so after a retemplate those events were lost. The same applies to aWebView2that is loaded whileCollapsed(or inside a collapsed container): a collapsed element isn't measured, so its template is applied only once it's shown, afterLoaded, and before this PR its loads never raisedNavigationCompletedeither. The registration is shared Skia code, so on macOS a retemplated or collapsed-at-loadWebView2now also getsWebMessageReceived(itsOnLoadedregisters the WebKit message handler); that's untested on macOS. A retemplatedWebView2starts again atabout:blankin its new iframe; WinUI's browser isn't part of the template, so it keeps its page.Deliberate differences from WinUI.
EnsureCoreWebView2Asyncfails withObjectDisposedExceptionwhen the control is closed. WinUI'sClose()only stops a creation that hasn't started yet (CreateCoreObjectschecksm_isClosedwhen it starts), and a creation already in flight completes, so a waiting call succeeds there. Uno'sEnsureCoreWebView2Asyncwaits for the template to create the native web view, which WinUI doesn't wait for, and a closed control never creates one, so the call fails as one made afterClose()does.CoreWebView2reference kept from beforeClose()does nothing:Navigate,NavigateToString,Reload,GoBack,GoForwardandStopreturn without effect andExecuteScriptAsyncreturnsnull. WinUI'sCoreWebView2fails those calls withERROR_INVALID_STATE(aCOMExceptionin .NET); WinUI's ownWebView2wraps most of its calls to swallow that error (CoreWebView2RunIgnoreInvalidStateSync). Uno has no established way to raise that error fromCoreWebView2: nothing in Uno producesERROR_INVALID_STATEor aCOMExceptionfor it, and its members already return without effect whenever it has no native web view, for example before the template is applied. Matching WinUI would mean a new error path for this one case, so this PR leaves it.Other Skia targets. Win32, macOS, X11, and Skia on Android and iOS have no way to close their native web view yet, and each needs its own native teardown. A native web view opts in through a new internal
ISupportsCloseinterface. When the native web view doesn't implement it,Close()keeps reporting itself as not implemented and changes nothing, as before. The one change there: aClose()called before the control has created its native web view closes the control, so it never creates one, as in WinUI.The generated
[NotImplemented("__SKIA__")]stub forClose()is gone (the generated file now has the usual "Skipping already declared method" line, and the WinAppSDK Sync Generator Check passes). To keep the gap visible at build time,Close()is marked[Uno.NotImplemented("__DESKTOP__", "__ANDROID__", "__APPLE_UIKIT__")]. InUno.UI, which is a single Skia build, the analyzer matches tokens other than__SKIA__against the app's own symbols (#24554), so desktop, Android, iOS and tvOS apps getUNO0001forClose()and WebAssembly apps don't. A plainnet10.0library gets no warning, as for a WinRT API that WebAssembly implements.ApiInformation.IsMethodPresentreads any[NotImplemented]as absent, so it still returnsfalseforClose()on every target, WebAssembly included, as before this PR.Close()also still reports itself as not implemented at run time on those targets once the web view exists.Docs.
WebView.mdhas a new short section, "Closing a WebView2":Close()releases the web view on WebAssembly, other targets getUNO0001at build time and report it as not implemented at run time once the web view exists, and aClose()before the web view is created closes the control on every target.Relation to #23754. #23754 also implements
Close(), as part of a larger change. This PR uses the same internal interface,ISupportsCloseinUno.UI.Xaml.Controlswith aClose()method, and the sameWebView2behavior after closing, ported from the same WinUI code, so the two can be reconciled whichever goes in first. The difference is on WebAssembly: #23754 navigates the iframe toabout:blankand leaves it in the page until the control is collected, while this PR removes it from the page right away. The second to merge gets textual conflicts inWebView2.cs,WebView2.Properties.cs,CoreWebView2.cs,ISupportsClose.cs(both add it; #23754's has no doc comments),NativeWebView.wasm.csandWebView.md.Tests. All are linked to #25736.
Given_WebView2_Close.cs(new) compiles for WinUI too, so CI checks these against WinUI:When_Closed_Then_CoreWebView2_Is_Null_And_Members_Fail(WinUI, Skia WebAssembly): checks the table above for the members that don't depend on the iframe:CoreWebView2,CanGoBack/CanGoForward, a secondClose(),GoBack/GoForward, and the exception types ofEnsureCoreWebView2Async,Source,NavigateToString,ReloadandExecuteScriptAsync.When_Closed_From_CoreWebView2Initialized_Before_Template_Then_EnsureCoreWebView2Async_Completes(WinUI, Skia WebAssembly, Skia desktop).Given_WebView2.uno.cs, Skia WebAssembly only:When_Closed_Then_Native_Iframe_Is_Removed: the iframe is removed right away, and loading the closed control again doesn't present a new one.When_Closed_Then_Collectable: a closedWebView2is still collected once it leaves the tree.When_Closed_Before_Loaded_Then_Pending_EnsureCoreWebView2Async_Fails(the deliberate difference above), which also checks WinUI's message.When_Closed_With_Script_Pending_Then_ExecuteScriptAsync_Returns_Empty_String.When_Closed_With_Navigation_Pending_Then_NavigationStarting_Is_Not_Raised:CoreWebView2.Navigate, thenClose(); neither theCoreWebView2nor theWebView2handler is called.When_Closed_During_Navigation_Completion_Then_CoreWebView2_Raises_No_More_Events, once closing fromSourceChangedand once fromDocumentTitleChangedwhile a page loads: theCoreWebView2raises nothing afterClose().When_Closed_From_NavigationStarting_Then_Navigation_Is_Dropped: the control is closed and the iframe removed. The dropped load itself can't be observed (see the results).When_Releasing_Browser_Fails_Then_WebView2_Is_Still_Closed: makes the browser call that removes the iframe's listeners throw, and checks thatClose()doesn't throw, the control is closed and the iframe is removed.When_Releasing_Browser_Fails_On_Retemplate_Then_New_Template_Gets_A_Browser: the same failure while the control is retemplated; the old iframe is removed, the new template presents a new one, and it navigates.When_Closed_From_CoreWebView2Initialized_On_Load_Then_No_Iframe_Is_Presented.When_Closed_From_CoreWebView2Initialized_After_Template_Then_EnsureCoreWebView2Async_Completes.When_Retemplated_Then_Replaced_Iframe_Is_Removed.When_Retemplated_Then_Navigation_CompletesandWhen_Shown_After_Collapsed_Load_Then_Navigation_Completes: both wait for theNavigationCompletedwhoseNavigationIdis the oneNavigationStartingreported for aNavigateToString, which is raised when the iframe loads the document. That skips the early one raised beforeNavigationStarting(WebView2 on WebAssembly raises NavigationCompleted before NavigationStarting, so each navigation completes twice #25806), so the tests keep working once that event is gone.UnoNotImplementedTests.When_UnoUI_Stub_Is_Implemented_On_Wasm_Only(analyzer test): aUno.UImember withClose()'s tokens is reported for the desktop, Android, iOS and tvOS consumer symbol sets, and not for WebAssembly or a plainnet10.0library.I ran all runtime tests matching
WebViewlocally (SamplesAppnet10.0-browserwasm, Chrome) on this branch at e477aea, onmasterat 98b28f8: the 24 that run on Skia WebAssembly pass (two of them are the two cases of one test), and the otherWebView,WebView2andCoreWebView2tests are skipped there. The browser console shows the two simulated release failures logged as errors. Each of the three commits builds on its own (Uno.UI.Runtime.WebAssembly.BrowserandUno.UI.RuntimeTests).Earlier runs, with the new tests on the code before each change:
When_Closed_With_Script_Pending_Then_ExecuteScriptAsync_Returns_Empty_StringJSExceptionfrom the removed iframe, then the intermediateObjectDisposedExceptionWhen_Releasing_Browser_Fails_Then_WebView2_Is_Still_ClosedCoreWebView2still set afterClose()threw, thenClose()throwing the simulated errorWhen_Releasing_Browser_Fails_On_Retemplate_Then_New_Template_Gets_A_BrowserWhen_Retemplated_Then_Navigation_CompletesNavigationCompletedfor the load within 10 sWhen_Shown_After_Collapsed_Load_Then_Navigation_CompletesNavigationCompletedfor the load within 10 sWhen_Closed_Then_CoreWebView2_Is_Null_And_Members_FailExecuteScriptAsyncthrows from the callWhen_Closed_Before_Loaded_Then_Pending_EnsureCoreWebView2Async_FailsWhen_Closed_During_Navigation_Completion_Then_CoreWebView2_Raises_No_More_Events(both cases)NavigationCompletedis raised afterClose()When_Closed_With_Navigation_Pending_Then_NavigationStarting_Is_Not_RaisedScheduleNavigationStartingare removed (NavigationStartingraised once)Those runs were on the code this PR had before each change: its first pushed head (a283220) and later intermediate states, with the late-template registration removed for the collapsed-load test and the dropped-navigation checks removed for the navigation-pending test. By the code, every test in the table except the navigation-pending one fails on a283220.
When_Closed_From_NavigationStarting_Then_Navigation_Is_Droppedpasses even without the check that skips the load after a handler closed the control: the load then fails on the removed iframe, and the dispatcher only logs that error, so the test can't see it. The other tests passed before and after. The twoNavigationCompletedtests passed on the rebased branch with theNavigationIdwait.Given_WebView2_Close.cscouldn't be run on WinUI locally (that needs the WinAppSDK head build). It uses only public WinUI and MSTest API, no Uno-only types, so it compiles for the WinUI head, and CI's WinUI runtime tests will run it there.PR Checklist ✅
Screenshots Compare Test Runresults.