Skip to content

[iOS/Mac] BlazorWebView: raise ProcessTerminated and reload when the web content process ends - #40419

Merged
kubaflo merged 2 commits into
dotnet:candidate/11.0.1xx-sr2from
Kebechet:fix-24669-blazorwebview-webcontent-terminated
Nov 19, 2026
Merged

kubaflo merged 2 commits into
dotnet:candidate/11.0.1xx-sr2from
Kebechet:fix-24669-blazorwebview-webcontent-terminated

Conversation

@Kebechet

@Kebechet Kebechet commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Target Branch

This PR is for Initial base
New features, API changes, or .NET 12 work (including .NET 12 fixes) main
.NET 11 servicing fixes net11, for review
Older servicing, release integration, infrastructure, or documentation The branch designated for that work

This adds public API, so it targets main.

Description of Change

On iOS and Mac Catalyst, a Blazor Hybrid app reloads itself and loses all UI state whenever the WKWebView's web content process (com.apple.WebKit.WebContent) ends, for example because it crashed or the system reclaimed it. Reporters see it after leaving the app minimized or on another Space for a while.

WebViewNavigationDelegate in IOSWebViewManager.cs does not implement webViewWebContentProcessDidTerminate:. When no client handles the termination, WebKit reloads the page on its own (WebPageProxy::notifyClientOfProcessTermination), and when the view is not visible it holds that reload back until it is. Blazor then attaches to the new page, WebViewManager.AttachToPageAsync disposes the old page context, and every component starts over. The app is never told.

I reproduced it on demand on macOS 26.2 with MAUI 10.0.20 by killing the web content process, and wrote it up with logs in the issue: #24669 (comment). The repro app is https://github.com/Kebechet/maui-blazorwebview-reload-repro.

Change

  • WebViewNavigationDelegate implements ContentProcessDidTerminate and raises the new BlazorWebView.ProcessTerminated event.
  • Implementing it turns WebKit's own reload off, so the new WebContentProcessReloader does that reload the way WebKit does (notifyClientOfProcessTermination, maybeReloadAfterCrashWhenVisible and tryReloadAfterProcessTermination in WebPageProxy.cpp):
    • It reloads right away when the web view is visible: in a window whose scene is not in the background, as PageClientImpl::isViewVisible decides on iOS. Otherwise it waits until the web view is added to a window or its scene comes back to the foreground.
    • A new navigation drops a pending reload, since it starts a web content process of its own.
    • Crash-loop limit: when the process ends again before a page has been loaded for 30 seconds after a reload, that termination is not reloaded. After skipping one, the next termination reloads again, as in WebKit.
    • When the process ended before the first page was committed, there is nothing to reload, so the page that was being loaded (WKWebView.Url) is loaded again, like WebKit does with its pending request.
  • BlazorWKWebView, a WKWebView subclass, raises MovedToWindow like MauiWKWebView does. Without it, UIView.OnLoaded only notices a window when the view's bounds change, which does not happen when the same web view is shown again at the same size. Side effect: this also changes how MAUI detects that a BlazorWebView is loaded on iOS and Mac Catalyst: through MovedToWindow, as for WebView, instead of the bounds observer.
  • Logged: ReloadingAfterWebContentProcessTermination (warning), DeferringReloadAfterWebContentProcessTermination (warning) and NotReloadingAfterWebContentProcessTermination (error).

API

API Notes
BlazorWebView.ProcessTerminated EventHandler<WebViewProcessTerminatedEventArgs>, the same args as WebView.ProcessTerminated; PlatformArgs.Sender is the WKWebView
IBlazorWebView.ProcessTerminated(WebProcessTerminatedEventArgs) default interface member, so existing implementations keep compiling, like IWebView.ProcessTerminated

The event is raised before the reload, while the existing components and services are still alive, so an app can save the state it wants to restore once Blazor starts again.

Open question for API review: the event does not tell the app whether a reload follows, or whether the crash-loop limit skipped it and the page stays blank. That would need a property on the event args, which WebView.ProcessTerminated shares, so I left it out for now.

Not covered here

  • Android and Windows are not wired up. Android's WebKitWebViewClient does not override OnRenderProcessGone, and Windows does not handle CoreWebView2.ProcessFailed. Both need their own recovery work, so I kept this PR to iOS and Mac Catalyst.
  • The plain WebView has the same gap on iOS and Mac Catalyst: MauiWKWebView exports webViewWebContentProcessDidTerminate: on the WKWebView subclass, but WebKit sends it to the navigation delegate (MauiWebViewNavigationDelegate), so WebView.ProcessTerminated does not seem to fire there. That belongs in Core and is not changed here.
  • Keeping component state across a restart of the web content process would need support in WebViewManager in aspnetcore.

Tests

Device tests in BlazorWebViewTests.ProcessTermination.iOS.cs (it also compiles for Mac Catalyst). They end the web content process with kill(pid, SIGKILL), which is what the system does to it. The pid comes from the private _webProcessIdentifier property, used only in the test.

Test Covers
WebContentProcessTerminationRaisesProcessTerminatedAndReloadsVisiblePage in a window: the event is raised with the web view as Sender, and Blazor renders the root component again right away
WebContentProcessTerminationReloadsHiddenPageOnceItIsInAWindow not in a window: the reload waits, and happens once the web view is added to a window
WebContentProcessTerminationRightAfterReloadDoesNotReloadAgain a second termination less than 30 seconds after the reloaded page loaded raises the event but does not reload
WebContentProcessTerminationLongAfterReloadReloadsAgain a second termination 30 seconds after the reloaded page loaded reloads again
WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain the process ends while WebKit decides on the first navigation, before anything is committed; the page is loaded again and Blazor starts

The two tests about the 30 seconds swap the handler's internal TimeProvider for a manual one, so they do not depend on timing.

Run locally with xharness, Category=BlazorWebView, on main (331056d):

Run Result
Mac Catalyst 53 passed, 0 failed, 1 skipped
iOS simulator 26.5 53 passed, 0 failed, 1 skipped
Mac Catalyst, with three behaviors switched off: the web view always counts as visible, a reload is never forgotten, and Reload() is used even when nothing was loaded exactly the three tests that cover them fail (hidden web view, termination after the 30 seconds, termination before the first page), the other two pass: 50 passed, 3 failed, 1 skipped

Issues Fixed

Addresses #24669: apps are now told when the web content process ends, and BlazorWebView handles the reload itself instead of WebKit doing it silently. It does not stop the system from ending the process, and the UI state is still lost unless the app restores it.

…web content process ends

BlazorWebView's navigation delegate did not implement
webViewWebContentProcessDidTerminate:, so when the WKWebView's web content
process ended (it crashed, or the system reclaimed it), WebKit reloaded the
page on its own, and only once the window was visible again if it was
hidden. Blazor then attached to the new page and started from scratch,
and the app had no way to know why its UI state was gone.

The delegate now raises a new BlazorWebView.ProcessTerminated event, with
the same WebViewProcessTerminatedEventArgs as WebView.ProcessTerminated,
and then reloads the page itself. Like WebKit, it does not reload again
when the process ends within 30 seconds of that reload.

dotnet#24669
@github-actions

Copy link
Copy Markdown
Contributor

🚀 Dogfood this PR with:

⚠️ WARNING: Do not do this without first carefully reviewing the code of this PR to satisfy yourself it is safe.

curl -fsSL https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.sh | bash -s -- 40419

Or

  • Run remotely in PowerShell:
iex "& { $(irm https://raw.githubusercontent.com/dotnet/maui/main/eng/scripts/get-maui-pr.ps1) } 40419"

@azure-pipelines

This comment has been minimized.

@dotnet-policy-service dotnet-policy-service Bot added the community ✨ Community Contribution label Nov 19, 2026
@dotnet-policy-service

Copy link
Copy Markdown
Contributor

Hey there @Kebechet! Thank you so much for your PR! Someone from the team will get assigned to your PR shortly and we'll get it reviewed.

@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Nov 19, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Expert Review — 1 finding

Reviewed commit 6bcb7bc.

See inline comments for details.

});

[Fact]
public Task WebContentProcessTerminationRightAfterReloadDoesNotReloadAgain()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[moderate] Regression Prevention and Test Coverage - Neither test exercises a subsequent termination after the 30-second cooldown expires. The first termination covers a null timestamp; this test covers a non-null timestamp still inside the interval. Suppressing every subsequent reload would therefore satisfy both tests but leave the view unrecovered after a later, unrelated process termination. Add the discriminating case with a non-null, expired timestamp and assert another event and successful Blazor reload; use a deterministic timing seam rather than a 30-second sleep.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, the two tests could not tell "reload again later" apart from "never reload again". Added WebContentProcessTerminationLongAfterReloadReloadsAgain in eed36fe:

  • The handler has an internal TimeProvider now, and the test swaps in a manual one.
  • After the first reload, the test waits until the reloaded page has finished loading, moves that clock forward by the 30 seconds, ends the process again, and asserts that the page is reloaded again: Blazor renders the root component a second time, and ReloadingAfterWebContentProcessTermination is logged twice with no NotReloadingAfterWebContentProcessTermination.

WebContentProcessTerminationRightAfterReloadDoesNotReloadAgain uses the same clock and never moves it, so it no longer depends on timing either. The same commit also starts the 30 seconds when a page finishes loading, as WebKit does, and waits with the reload while the web view is not visible. The PR description lists the rest.

@MauiBot

This comment has been minimized.

…e way WebKit does

The first version reloaded right away, also while the web view was not
visible, and counted the 30 seconds from the start of the reload. If the
system reclaimed the new process while the app was in the background, the
second termination skipped the reload, and the page stayed blank when the
app came back. WebKit instead waits until the view is visible.

WebContentProcessReloader now follows WebKit's own reload
(notifyClientOfProcessTermination, maybeReloadAfterCrashWhenVisible and
tryReloadAfterProcessTermination in WebPageProxy.cpp):

- It reloads once the web view is in a window whose scene is not in the
  background, which is how PageClientImpl::isViewVisible decides on iOS.
  BlazorWKWebView raises MovedToWindow like MauiWKWebView, so a web view
  shown again at the same size is noticed too.
- A new navigation drops a pending reload.
- The 30 seconds start when a page finishes loading. After skipping one
  reload, the next termination reloads again.
- When the process ended before the first page was committed, there is
  nothing to reload, so the page that was being loaded is loaded again.

The handler's internal TimeProvider lets the device tests pass the 30
seconds without waiting. New tests cover a visible and a hidden web view, a
termination after the 30 seconds, and one before the first page loaded.

dotnet#24669
@kubaflo

This comment has been minimized.

@github-actions github-actions Bot added the s/agent-review-in-progress AI review is currently running for this PR label Nov 19, 2026
@MauiBot

MauiBot commented Nov 19, 2026

Copy link
Copy Markdown
Collaborator

PR Test Gate

@Kebechet — existing-test verification for commit eed36fe1.

Result FAILED Platform Android Commit eed36fe1


🧪 Gate analysis — click to expand

❌ Failed. The selected tests did not meet the expected outcomes. Inspect the evidence before changing the test or fix.

📱 Device tests
Test group Without fix With fix
BlazorWebViewTests ⚠ Environment blocked ❌ Failed (5228s)
Execution log excerpts

With fix BlazorWebViewTests

8
          },
          "target": {
            "kind": "emulator",
            "name": "sdk_gphone_x86_64",
            "identifier": "emulator-5554",
            "operatingSystem": "Android",
            "operatingSystemVersion": "11",
            "apiLevel": 30,
            "architecture": "x86_64",
            "supportedArchitectures": [
              "x86_64",
              "x86",
              "arm64-v8a",
              "armeabi-v7a",
              "armeabi"
            ],
            "manufacturer": "Google",
            "model": "sdk_gphone_x86_64",
            "productName": "sdk_gphone_x86_64",
            "buildFingerprint": "google/sdk_gphone_x86_64/generic_x86_64_arm64:11/RSR1.201211.001/7027799:user/release-keys",
            "cpuModel": "0",
            "cpuMaxFrequencyHertz": 2000,
            "totalMemoryBytes": 2077544448
          }
        }
      }
      <<XHARNESS_RESULT_END>>
info: Attempting to remove apk 'com.microsoft.maui.mauiblazorwebview.devicetests'..
info: Successfully uninstalled com.microsoft.maui.mauiblazorwebview.devicetests
XHarness exit code: 1 (TESTS_FAILED)
  Passed: 21
  Failed: 42
  Skipped: 4
  Total: 67
  Tests completed with exit code: 1

PR head: eed36fe1.

Without-fix baseline: 5c7a422e.

@MauiBot MauiBot added s/agent-gate-failed AI could not verify tests catch the bug and removed s/agent-review-in-progress AI review is currently running for this PR labels Nov 19, 2026
@kubaflo
kubaflo requested a balanced review from Copilot November 19, 2026 16:05

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Changes recommended

Crash-loop suppression can fail because TryReload() counts time spent hidden after process termination as successful uptime; expiry must be evaluated before visibility, with a manual-clock regression test covering the hidden interval.

1 open issue
What changed in this PR

Makes web-content process termination observable in MAUI’s BlazorWebView on iOS and Mac Catalyst, addressing the silent reloads reported in #24669. Apps can save state before recovery; restoring that state remains their responsibility.

Changes:

  • Adds the ProcessTerminated event and compatible interface notification.
  • Implements visibility-aware recovery, crash-loop suppression, and recovery logging.
  • Adds device tests for visible, hidden, repeated, and pre-load terminations.
File Description
src/​BlazorWebView/​tests/​DeviceTests/​Elements/​BlazorWebViewTests.Startup.cs Allows event setup before startup.
src/​BlazorWebView/​tests/​DeviceTests/​Elements/​BlazorWebViewTests.ProcessTermination.iOS.cs Adds termination and recovery tests.
src/​BlazorWebView/​src/​SharedSource/​Log.cs Adds recovery diagnostics.
src/​BlazorWebView/​src/​Maui/​PublicAPI/​net/​PublicAPI.Unshipped.txt Records the new shared APIs.
src/​BlazorWebView/​src/​Maui/​PublicAPI/​net-windows/​PublicAPI.Unshipped.txt Records the APIs for Windows.
src/​BlazorWebView/​src/​Maui/​PublicAPI/​net-maccatalyst/​PublicAPI.Unshipped.txt Records the APIs for Mac Catalyst.
src/​BlazorWebView/​src/​Maui/​PublicAPI/​net-ios/​PublicAPI.Unshipped.txt Records the APIs for iOS.
src/​BlazorWebView/​src/​Maui/​PublicAPI/​net-android/​PublicAPI.Unshipped.txt Records the APIs for Android.
src/​BlazorWebView/​src/​Maui/​iOS/​WebContentProcessReloader.cs Implements deferred recovery and crash-loop controls.
src/​BlazorWebView/​src/​Maui/​iOS/​IOSWebViewManager.cs Connects termination and navigation callbacks to recovery.
src/​BlazorWebView/​src/​Maui/​iOS/​BlazorWKWebView.cs Provides window-attachment lifecycle notifications.
src/​BlazorWebView/​src/​Maui/​iOS/​BlazorWebViewHandler.iOS.cs Uses the lifecycle-aware view and injectable clock.
src/​BlazorWebView/​src/​Maui/​IBlazorWebView.cs Adds a default termination notification method.
src/​BlazorWebView/​src/​Maui/​BlazorWebViewHandler.cs Forwards termination notifications to the control.
src/​BlazorWebView/​src/​Maui/​BlazorWebView.cs Exposes and documents the public event.

Review effort: Balanced

return;
}

if (IsVisible())

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This follows WebKit on purpose. In WebPageProxy.cpp, resetRecentCrashCountTimer (30 s) starts when the main frame finishes loading (resetRecentCrashCountSoon) and is stopped only in tryReloadAfterProcessTermination. A termination does not stop it, so it keeps running while maybeReloadAfterCrashWhenVisible waits for the view to be visible.

It also matters for #24669: when the web view is hidden, the process usually ends because the system reclaimed it in the background, not because of a crash loop. With the suggested change, an app that went to the background shortly after a reload would come back to a blank page. A reload loop needs a visible view, because nothing is reloaded while it is hidden. At most one reload happens each time the view becomes visible again, and a termination within 30 s of that reload is still not reloaded.

@kubaflo kubaflo left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you check the ai's suggestions and why the device test is failing?

@Kebechet

Copy link
Copy Markdown
Contributor Author

The device test failure isn't from this PR's tests. The PR has no platform/* label, so the gate fell back to Android and ran BlazorWebViewTests on an Android 11 emulator. The new tests are in BlazorWebViewTests.ProcessTermination.iOS.cs and only build for iOS and Mac Catalyst. On Android, the shared changes only add an event that is never raised there. The run without the fix on that emulator was "Environment blocked", and the same Android group failed the same way on #39795. Could you run /review gate ios and /review gate catalyst? Locally, the BlazorWebView device tests pass on both (53 passed, 1 skipped).

RunOniOS_Previous_BlazorDebug builds a net10.0-ios template app. It installed, but mlaunch couldn't launch it (APP_LAUNCH_FAILURE), while the Release and current Blazor iOS runs passed. Could you re-run it?

I replied to the Copilot comment inline: the current behaviour does the same as WebKit on purpose.

@kubaflo
kubaflo changed the base branch from main to candidate/11.0.1xx-sr2 November 19, 2026 19:25
@kubaflo
kubaflo merged commit 8e70055 into dotnet:candidate/11.0.1xx-sr2 Nov 19, 2026
30 of 41 checks passed
kubaflo added a commit that referenced this pull request Nov 20, 2026
…nt process ends before it starts loading (#40455)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This targets `candidate/11.0.1xx-sr2`, the same base as #40419.
`WebContentProcessReloader` exists only on the SR2 candidate; it is not
in `net11` or `main`.

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change


`BlazorWebViewTests.WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain`
was added in #40419. It fails on iOS for both the Mono and CoreCLR legs
of the candidate's device-test build
[1690816](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1690816)
(head 8e70055):

```
System.TimeoutException : controlDiv never became 'Static' after the reload. Last value: '<null>'.
```

**Root cause.** The test ends the web content process from `UrlLoading`,
which runs inside `DecidePolicy` for the first navigation, before that
navigation starts. By the time `ContentProcessDidTerminate` is called,
WebKit has already reset its page load state (`PageLoadState::reset`),
so `WKWebView.Url` and `BackForwardList.CurrentItem` are both `null`.
`WebContentProcessReloader.TryReload` assumed that "the page that was
being loaded is still the web view's URL". It therefore fell back to
`Reload()`, which has nothing to load, and the page never loaded.

Temporary diagnostics confirmed this on an iOS 26.0 simulator. For this
test the callback saw `url=<null> current=<null> visible=True`, so the
reload ran immediately (no window wait) and still had no URL.

WebKit avoids this with its own pending API request.
`WebPageProxy::tryReloadAfterProcessTermination` loads
`pendingAPIRequestURL` again when it is set, and calls `reload()` only
otherwise. `pendingAPIRequest` is set by `loadRequest` and cleared when
that navigation starts (`didStartProvisionalLoadForFrame`). It isn't
exposed through `WKWebView`.

**Fix.**
- `WebContentProcessReloader` mirrors WebKit's pending API request.
`PageRequested` remembers the page MAUI last asked for with
`LoadRequest`, and `NavigationStarted` (`DidStartProvisionalNavigation`)
forgets it.
- `TryReload` loads that page again when it is still pending. Otherwise
it keeps the existing behavior: load `Url` when there's no committed
page, else `Reload()`.
- `IOSWebViewManager` calls `PageRequested` for both of its
`LoadRequest` calls: the start page in `NavigateCore`, and the
app-scheme redirect re-issue.
- The URL is stored as a string because `NavigateCore` disposes its
`NSUrl`.
- No test, public API or existing reload/throttle/window-wait behavior
changes.

Intentional difference from WebKit: WebKit also drops the pending
request when the policy decision ignores that navigation. Here the page
stays pending until a navigation starts. If the app cancels its start
page in `UrlLoading` and the process later ends before any navigation
starts, the reload asks for that page again. It still goes through
`DecidePolicy`/`UrlLoading`, so the app's decision still applies.

**Causal evidence.** iOS 26.0 iPhone 11 Pro simulator, Xcode 27.2. Each
run used the full `BlazorWebView` device-test suite:

```
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project BlazorWebView -Platform ios -DeviceUdid <udid> -OutputDirectory artifacts/<run> -SkipXcodeVersionCheck
```

| Run | Tree | Result |
| --- | --- | --- |
| Baseline | 8e70055 (candidate head) | **Red**: 61 passed, 1 failed
(this test, same `'<null>'` error as CI), 1 skipped |
| Fix | this PR | **Green**: 62 passed, 0 failed, 1 skipped |
| Fix reverted | production change stashed | **Red**: 61 passed, 1
failed (same test, same error), 1 skipped |
| Restored | this PR | **Green**: 62 passed, 0 failed, 1 skipped |

All six `WebContentProcessTermination*` tests pass with the fix:
- `RaisesProcessTerminatedAndReloadsVisiblePage`
- `ReloadsHiddenPageOnceItIsInAWindow`
- `RightAfterReloadDoesNotReloadAgain`
- `LongAfterReloadReloadsAgain`
- `BeforeFirstPageLoadsLoadsThatPageAgain`
- `AfterThePageNavigatedByItselfReloadsTheNewPage` (added in 4bb40d5
after review; fails if `NavigationStarted` doesn't clear the pending
request, otherwise 63 passed, 0 failed, 1 skipped)

`dotnet format whitespace --verify-no-changes` passes on both files.
MacCatalyst shares this code (`iOS/` folder) and was not run locally. In
build 1690816 its BlazorWebView work items passed 62/63 at 8e70055
without this change, on macOS 15 (Helix c7a22071) and macOS 26 (Helix
cf4220c0), so only iOS shows the failure. This PR's CI covers
MacCatalyst with the change.

**CI on merge 151ca05:** maui-pr
[1691141](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691141)
succeeded. Device tests
[1691443](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691443)
succeeded with 0 failed tests in all 9 runs (Android, iOS, MacCatalyst,
Windows). All six tests above pass in the iOS Mono and CoreCLR runs on
macOS 15 and 26 and in both MacCatalyst runs. Without this change, a
rerun of 1690816's failed jobs at 8e70055 failed the same test again:
across both attempts it failed 4 of 4 iOS runs on macOS 26 and 1 of 4 on
macOS 15.

### Issues Fixed

No separate issue is logged. This is a follow-up to #40419, found while
auditing the SR2 candidate (#40116).

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 22, 2026
…web content process ends (#40419)

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This adds public API, so it targets `main`.

### Description of Change

On iOS and Mac Catalyst, a Blazor Hybrid app reloads itself and loses
all UI state whenever the WKWebView's web content process
(`com.apple.WebKit.WebContent`) ends, for example because it crashed or
the system reclaimed it. Reporters see it after leaving the app
minimized or on another Space for a while.

`WebViewNavigationDelegate` in `IOSWebViewManager.cs` does not implement
`webViewWebContentProcessDidTerminate:`. When no client handles the
termination, WebKit reloads the page on its own
([`WebPageProxy::notifyClientOfProcessTermination`](https://github.com/WebKit/WebKit/blob/main/Source/WebKit/UIProcess/WebPageProxy.cpp)),
and when the view is not visible it holds that reload back until it is.
Blazor then attaches to the new page, `WebViewManager.AttachToPageAsync`
disposes the old page context, and every component starts over. The app
is never told.

I reproduced it on demand on macOS 26.2 with MAUI 10.0.20 by killing the
web content process, and wrote it up with logs in the issue:
#24669 (comment). The
repro app is
https://github.com/Kebechet/maui-blazorwebview-reload-repro.

**Change**

- `WebViewNavigationDelegate` implements `ContentProcessDidTerminate`
and raises the new `BlazorWebView.ProcessTerminated` event.
- Implementing it turns WebKit's own reload off, so the new
`WebContentProcessReloader` does that reload the way WebKit does
(`notifyClientOfProcessTermination`, `maybeReloadAfterCrashWhenVisible`
and `tryReloadAfterProcessTermination` in `WebPageProxy.cpp`):
- It reloads right away when the web view is visible: in a window whose
scene is not in the background, as `PageClientImpl::isViewVisible`
decides on iOS. Otherwise it waits until the web view is added to a
window or its scene comes back to the foreground.
- A new navigation drops a pending reload, since it starts a web content
process of its own.
- Crash-loop limit: when the process ends again before a page has been
loaded for 30 seconds after a reload, that termination is not reloaded.
After skipping one, the next termination reloads again, as in WebKit.
- When the process ended before the first page was committed, there is
nothing to reload, so the page that was being loaded (`WKWebView.Url`)
is loaded again, like WebKit does with its pending request.
- `BlazorWKWebView`, a `WKWebView` subclass, raises `MovedToWindow` like
`MauiWKWebView` does. Without it, `UIView.OnLoaded` only notices a
window when the view's bounds change, which does not happen when the
same web view is shown again at the same size. **Side effect:** this
also changes how MAUI detects that a `BlazorWebView` is loaded on iOS
and Mac Catalyst: through `MovedToWindow`, as for `WebView`, instead of
the bounds observer.
- Logged: `ReloadingAfterWebContentProcessTermination` (warning),
`DeferringReloadAfterWebContentProcessTermination` (warning) and
`NotReloadingAfterWebContentProcessTermination` (error).

**API**

| API | Notes |
| --- | --- |
| `BlazorWebView.ProcessTerminated` |
`EventHandler<WebViewProcessTerminatedEventArgs>`, the same args as
`WebView.ProcessTerminated`; `PlatformArgs.Sender` is the `WKWebView` |
| `IBlazorWebView.ProcessTerminated(WebProcessTerminatedEventArgs)` |
default interface member, so existing implementations keep compiling,
like `IWebView.ProcessTerminated` |

The event is raised before the reload, while the existing components and
services are still alive, so an app can save the state it wants to
restore once Blazor starts again.

Open question for API review: the event does not tell the app whether a
reload follows, or whether the crash-loop limit skipped it and the page
stays blank. That would need a property on the event args, which
`WebView.ProcessTerminated` shares, so I left it out for now.

**Not covered here**

- Android and Windows are not wired up. Android's `WebKitWebViewClient`
does not override `OnRenderProcessGone`, and Windows does not handle
`CoreWebView2.ProcessFailed`. Both need their own recovery work, so I
kept this PR to iOS and Mac Catalyst.
- The plain `WebView` has the same gap on iOS and Mac Catalyst:
`MauiWKWebView` exports `webViewWebContentProcessDidTerminate:` on the
`WKWebView` subclass, but WebKit sends it to the navigation delegate
(`MauiWebViewNavigationDelegate`), so `WebView.ProcessTerminated` does
not seem to fire there. That belongs in Core and is not changed here.
- Keeping component state across a restart of the web content process
would need support in `WebViewManager` in aspnetcore.

### Tests

Device tests in `BlazorWebViewTests.ProcessTermination.iOS.cs` (it also
compiles for Mac Catalyst). They end the web content process with
`kill(pid, SIGKILL)`, which is what the system does to it. The pid comes
from the private `_webProcessIdentifier` property, used only in the
test.

| Test | Covers |
| --- | --- |
|
`WebContentProcessTerminationRaisesProcessTerminatedAndReloadsVisiblePage`
| in a window: the event is raised with the web view as `Sender`, and
Blazor renders the root component again right away |
| `WebContentProcessTerminationReloadsHiddenPageOnceItIsInAWindow` | not
in a window: the reload waits, and happens once the web view is added to
a window |
| `WebContentProcessTerminationRightAfterReloadDoesNotReloadAgain` | a
second termination less than 30 seconds after the reloaded page loaded
raises the event but does not reload |
| `WebContentProcessTerminationLongAfterReloadReloadsAgain` | a second
termination 30 seconds after the reloaded page loaded reloads again |
| `WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain` |
the process ends while WebKit decides on the first navigation, before
anything is committed; the page is loaded again and Blazor starts |

The two tests about the 30 seconds swap the handler's internal
`TimeProvider` for a manual one, so they do not depend on timing.

Run locally with xharness, `Category=BlazorWebView`, on `main`
(331056d):

| Run | Result |
| --- | --- |
| Mac Catalyst | 53 passed, 0 failed, 1 skipped |
| iOS simulator 26.5 | 53 passed, 0 failed, 1 skipped |
| Mac Catalyst, with three behaviors switched off: the web view always
counts as visible, a reload is never forgotten, and `Reload()` is used
even when nothing was loaded | exactly the three tests that cover them
fail (hidden web view, termination after the 30 seconds, termination
before the first page), the other two pass: 50 passed, 3 failed, 1
skipped |

### Issues Fixed

Addresses #24669: apps are now told
when the web content process ends, and BlazorWebView handles the reload
itself instead of WebKit doing it silently. It does not stop the system
from ending the process, and the UI state is still lost unless the app
restores it.

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 22, 2026
…nt process ends before it starts loading (#40455)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This targets `candidate/11.0.1xx-sr2`, the same base as #40419.
`WebContentProcessReloader` exists only on the SR2 candidate; it is not
in `net11` or `main`.

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change


`BlazorWebViewTests.WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain`
was added in #40419. It fails on iOS for both the Mono and CoreCLR legs
of the candidate's device-test build
[1690816](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1690816)
(head 8e70055):

```
System.TimeoutException : controlDiv never became 'Static' after the reload. Last value: '<null>'.
```

**Root cause.** The test ends the web content process from `UrlLoading`,
which runs inside `DecidePolicy` for the first navigation, before that
navigation starts. By the time `ContentProcessDidTerminate` is called,
WebKit has already reset its page load state (`PageLoadState::reset`),
so `WKWebView.Url` and `BackForwardList.CurrentItem` are both `null`.
`WebContentProcessReloader.TryReload` assumed that "the page that was
being loaded is still the web view's URL". It therefore fell back to
`Reload()`, which has nothing to load, and the page never loaded.

Temporary diagnostics confirmed this on an iOS 26.0 simulator. For this
test the callback saw `url=<null> current=<null> visible=True`, so the
reload ran immediately (no window wait) and still had no URL.

WebKit avoids this with its own pending API request.
`WebPageProxy::tryReloadAfterProcessTermination` loads
`pendingAPIRequestURL` again when it is set, and calls `reload()` only
otherwise. `pendingAPIRequest` is set by `loadRequest` and cleared when
that navigation starts (`didStartProvisionalLoadForFrame`). It isn't
exposed through `WKWebView`.

**Fix.**
- `WebContentProcessReloader` mirrors WebKit's pending API request.
`PageRequested` remembers the page MAUI last asked for with
`LoadRequest`, and `NavigationStarted` (`DidStartProvisionalNavigation`)
forgets it.
- `TryReload` loads that page again when it is still pending. Otherwise
it keeps the existing behavior: load `Url` when there's no committed
page, else `Reload()`.
- `IOSWebViewManager` calls `PageRequested` for both of its
`LoadRequest` calls: the start page in `NavigateCore`, and the
app-scheme redirect re-issue.
- The URL is stored as a string because `NavigateCore` disposes its
`NSUrl`.
- No test, public API or existing reload/throttle/window-wait behavior
changes.

Intentional difference from WebKit: WebKit also drops the pending
request when the policy decision ignores that navigation. Here the page
stays pending until a navigation starts. If the app cancels its start
page in `UrlLoading` and the process later ends before any navigation
starts, the reload asks for that page again. It still goes through
`DecidePolicy`/`UrlLoading`, so the app's decision still applies.

**Causal evidence.** iOS 26.0 iPhone 11 Pro simulator, Xcode 27.2. Each
run used the full `BlazorWebView` device-test suite:

```
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project BlazorWebView -Platform ios -DeviceUdid <udid> -OutputDirectory artifacts/<run> -SkipXcodeVersionCheck
```

| Run | Tree | Result |
| --- | --- | --- |
| Baseline | 8e70055 (candidate head) | **Red**: 61 passed, 1 failed
(this test, same `'<null>'` error as CI), 1 skipped |
| Fix | this PR | **Green**: 62 passed, 0 failed, 1 skipped |
| Fix reverted | production change stashed | **Red**: 61 passed, 1
failed (same test, same error), 1 skipped |
| Restored | this PR | **Green**: 62 passed, 0 failed, 1 skipped |

All six `WebContentProcessTermination*` tests pass with the fix:
- `RaisesProcessTerminatedAndReloadsVisiblePage`
- `ReloadsHiddenPageOnceItIsInAWindow`
- `RightAfterReloadDoesNotReloadAgain`
- `LongAfterReloadReloadsAgain`
- `BeforeFirstPageLoadsLoadsThatPageAgain`
- `AfterThePageNavigatedByItselfReloadsTheNewPage` (added in 4bb40d5
after review; fails if `NavigationStarted` doesn't clear the pending
request, otherwise 63 passed, 0 failed, 1 skipped)

`dotnet format whitespace --verify-no-changes` passes on both files.
MacCatalyst shares this code (`iOS/` folder) and was not run locally. In
build 1690816 its BlazorWebView work items passed 62/63 at 8e70055
without this change, on macOS 15 (Helix c7a22071) and macOS 26 (Helix
cf4220c0), so only iOS shows the failure. This PR's CI covers
MacCatalyst with the change.

**CI on merge 151ca05:** maui-pr
[1691141](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691141)
succeeded. Device tests
[1691443](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691443)
succeeded with 0 failed tests in all 9 runs (Android, iOS, MacCatalyst,
Windows). All six tests above pass in the iOS Mono and CoreCLR runs on
macOS 15 and 26 and in both MacCatalyst runs. Without this change, a
rerun of 1690816's failed jobs at 8e70055 failed the same test again:
across both attempts it failed 4 of 4 iOS runs on macOS 26 and 1 of 4 on
macOS 15.

### Issues Fixed

No separate issue is logged. This is a follow-up to #40419, found while
auditing the SR2 candidate (#40116).

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
…web content process ends (#40419)

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This adds public API, so it targets `main`.

### Description of Change

On iOS and Mac Catalyst, a Blazor Hybrid app reloads itself and loses
all UI state whenever the WKWebView's web content process
(`com.apple.WebKit.WebContent`) ends, for example because it crashed or
the system reclaimed it. Reporters see it after leaving the app
minimized or on another Space for a while.

`WebViewNavigationDelegate` in `IOSWebViewManager.cs` does not implement
`webViewWebContentProcessDidTerminate:`. When no client handles the
termination, WebKit reloads the page on its own
([`WebPageProxy::notifyClientOfProcessTermination`](https://github.com/WebKit/WebKit/blob/main/Source/WebKit/UIProcess/WebPageProxy.cpp)),
and when the view is not visible it holds that reload back until it is.
Blazor then attaches to the new page, `WebViewManager.AttachToPageAsync`
disposes the old page context, and every component starts over. The app
is never told.

I reproduced it on demand on macOS 26.2 with MAUI 10.0.20 by killing the
web content process, and wrote it up with logs in the issue:
#24669 (comment). The
repro app is
https://github.com/Kebechet/maui-blazorwebview-reload-repro.

**Change**

- `WebViewNavigationDelegate` implements `ContentProcessDidTerminate`
and raises the new `BlazorWebView.ProcessTerminated` event.
- Implementing it turns WebKit's own reload off, so the new
`WebContentProcessReloader` does that reload the way WebKit does
(`notifyClientOfProcessTermination`, `maybeReloadAfterCrashWhenVisible`
and `tryReloadAfterProcessTermination` in `WebPageProxy.cpp`):
- It reloads right away when the web view is visible: in a window whose
scene is not in the background, as `PageClientImpl::isViewVisible`
decides on iOS. Otherwise it waits until the web view is added to a
window or its scene comes back to the foreground.
- A new navigation drops a pending reload, since it starts a web content
process of its own.
- Crash-loop limit: when the process ends again before a page has been
loaded for 30 seconds after a reload, that termination is not reloaded.
After skipping one, the next termination reloads again, as in WebKit.
- When the process ended before the first page was committed, there is
nothing to reload, so the page that was being loaded (`WKWebView.Url`)
is loaded again, like WebKit does with its pending request.
- `BlazorWKWebView`, a `WKWebView` subclass, raises `MovedToWindow` like
`MauiWKWebView` does. Without it, `UIView.OnLoaded` only notices a
window when the view's bounds change, which does not happen when the
same web view is shown again at the same size. **Side effect:** this
also changes how MAUI detects that a `BlazorWebView` is loaded on iOS
and Mac Catalyst: through `MovedToWindow`, as for `WebView`, instead of
the bounds observer.
- Logged: `ReloadingAfterWebContentProcessTermination` (warning),
`DeferringReloadAfterWebContentProcessTermination` (warning) and
`NotReloadingAfterWebContentProcessTermination` (error).

**API**

| API | Notes |
| --- | --- |
| `BlazorWebView.ProcessTerminated` |
`EventHandler<WebViewProcessTerminatedEventArgs>`, the same args as
`WebView.ProcessTerminated`; `PlatformArgs.Sender` is the `WKWebView` |
| `IBlazorWebView.ProcessTerminated(WebProcessTerminatedEventArgs)` |
default interface member, so existing implementations keep compiling,
like `IWebView.ProcessTerminated` |

The event is raised before the reload, while the existing components and
services are still alive, so an app can save the state it wants to
restore once Blazor starts again.

Open question for API review: the event does not tell the app whether a
reload follows, or whether the crash-loop limit skipped it and the page
stays blank. That would need a property on the event args, which
`WebView.ProcessTerminated` shares, so I left it out for now.

**Not covered here**

- Android and Windows are not wired up. Android's `WebKitWebViewClient`
does not override `OnRenderProcessGone`, and Windows does not handle
`CoreWebView2.ProcessFailed`. Both need their own recovery work, so I
kept this PR to iOS and Mac Catalyst.
- The plain `WebView` has the same gap on iOS and Mac Catalyst:
`MauiWKWebView` exports `webViewWebContentProcessDidTerminate:` on the
`WKWebView` subclass, but WebKit sends it to the navigation delegate
(`MauiWebViewNavigationDelegate`), so `WebView.ProcessTerminated` does
not seem to fire there. That belongs in Core and is not changed here.
- Keeping component state across a restart of the web content process
would need support in `WebViewManager` in aspnetcore.

### Tests

Device tests in `BlazorWebViewTests.ProcessTermination.iOS.cs` (it also
compiles for Mac Catalyst). They end the web content process with
`kill(pid, SIGKILL)`, which is what the system does to it. The pid comes
from the private `_webProcessIdentifier` property, used only in the
test.

| Test | Covers |
| --- | --- |
|
`WebContentProcessTerminationRaisesProcessTerminatedAndReloadsVisiblePage`
| in a window: the event is raised with the web view as `Sender`, and
Blazor renders the root component again right away |
| `WebContentProcessTerminationReloadsHiddenPageOnceItIsInAWindow` | not
in a window: the reload waits, and happens once the web view is added to
a window |
| `WebContentProcessTerminationRightAfterReloadDoesNotReloadAgain` | a
second termination less than 30 seconds after the reloaded page loaded
raises the event but does not reload |
| `WebContentProcessTerminationLongAfterReloadReloadsAgain` | a second
termination 30 seconds after the reloaded page loaded reloads again |
| `WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain` |
the process ends while WebKit decides on the first navigation, before
anything is committed; the page is loaded again and Blazor starts |

The two tests about the 30 seconds swap the handler's internal
`TimeProvider` for a manual one, so they do not depend on timing.

Run locally with xharness, `Category=BlazorWebView`, on `main`
(331056d):

| Run | Result |
| --- | --- |
| Mac Catalyst | 53 passed, 0 failed, 1 skipped |
| iOS simulator 26.5 | 53 passed, 0 failed, 1 skipped |
| Mac Catalyst, with three behaviors switched off: the web view always
counts as visible, a reload is never forgotten, and `Reload()` is used
even when nothing was loaded | exactly the three tests that cover them
fail (hidden web view, termination after the 30 seconds, termination
before the first page), the other two pass: 50 passed, 3 failed, 1
skipped |

### Issues Fixed

Addresses #24669: apps are now told
when the web content process ends, and BlazorWebView handles the reload
itself instead of WebKit doing it silently. It does not stop the system
from ending the process, and the UI state is still lost unless the app
restores it.

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
kubaflo added a commit that referenced this pull request Nov 23, 2026
…nt process ends before it starts loading (#40455)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This targets `candidate/11.0.1xx-sr2`, the same base as #40419.
`WebContentProcessReloader` exists only on the SR2 candidate; it is not
in `net11` or `main`.

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change


`BlazorWebViewTests.WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain`
was added in #40419. It fails on iOS for both the Mono and CoreCLR legs
of the candidate's device-test build
[1690816](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1690816)
(head 8e70055):

```
System.TimeoutException : controlDiv never became 'Static' after the reload. Last value: '<null>'.
```

**Root cause.** The test ends the web content process from `UrlLoading`,
which runs inside `DecidePolicy` for the first navigation, before that
navigation starts. By the time `ContentProcessDidTerminate` is called,
WebKit has already reset its page load state (`PageLoadState::reset`),
so `WKWebView.Url` and `BackForwardList.CurrentItem` are both `null`.
`WebContentProcessReloader.TryReload` assumed that "the page that was
being loaded is still the web view's URL". It therefore fell back to
`Reload()`, which has nothing to load, and the page never loaded.

Temporary diagnostics confirmed this on an iOS 26.0 simulator. For this
test the callback saw `url=<null> current=<null> visible=True`, so the
reload ran immediately (no window wait) and still had no URL.

WebKit avoids this with its own pending API request.
`WebPageProxy::tryReloadAfterProcessTermination` loads
`pendingAPIRequestURL` again when it is set, and calls `reload()` only
otherwise. `pendingAPIRequest` is set by `loadRequest` and cleared when
that navigation starts (`didStartProvisionalLoadForFrame`). It isn't
exposed through `WKWebView`.

**Fix.**
- `WebContentProcessReloader` mirrors WebKit's pending API request.
`PageRequested` remembers the page MAUI last asked for with
`LoadRequest`, and `NavigationStarted` (`DidStartProvisionalNavigation`)
forgets it.
- `TryReload` loads that page again when it is still pending. Otherwise
it keeps the existing behavior: load `Url` when there's no committed
page, else `Reload()`.
- `IOSWebViewManager` calls `PageRequested` for both of its
`LoadRequest` calls: the start page in `NavigateCore`, and the
app-scheme redirect re-issue.
- The URL is stored as a string because `NavigateCore` disposes its
`NSUrl`.
- No test, public API or existing reload/throttle/window-wait behavior
changes.

Intentional difference from WebKit: WebKit also drops the pending
request when the policy decision ignores that navigation. Here the page
stays pending until a navigation starts. If the app cancels its start
page in `UrlLoading` and the process later ends before any navigation
starts, the reload asks for that page again. It still goes through
`DecidePolicy`/`UrlLoading`, so the app's decision still applies.

**Causal evidence.** iOS 26.0 iPhone 11 Pro simulator, Xcode 27.2. Each
run used the full `BlazorWebView` device-test suite:

```
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project BlazorWebView -Platform ios -DeviceUdid <udid> -OutputDirectory artifacts/<run> -SkipXcodeVersionCheck
```

| Run | Tree | Result |
| --- | --- | --- |
| Baseline | 8e70055 (candidate head) | **Red**: 61 passed, 1 failed
(this test, same `'<null>'` error as CI), 1 skipped |
| Fix | this PR | **Green**: 62 passed, 0 failed, 1 skipped |
| Fix reverted | production change stashed | **Red**: 61 passed, 1
failed (same test, same error), 1 skipped |
| Restored | this PR | **Green**: 62 passed, 0 failed, 1 skipped |

All six `WebContentProcessTermination*` tests pass with the fix:
- `RaisesProcessTerminatedAndReloadsVisiblePage`
- `ReloadsHiddenPageOnceItIsInAWindow`
- `RightAfterReloadDoesNotReloadAgain`
- `LongAfterReloadReloadsAgain`
- `BeforeFirstPageLoadsLoadsThatPageAgain`
- `AfterThePageNavigatedByItselfReloadsTheNewPage` (added in 4bb40d5
after review; fails if `NavigationStarted` doesn't clear the pending
request, otherwise 63 passed, 0 failed, 1 skipped)

`dotnet format whitespace --verify-no-changes` passes on both files.
MacCatalyst shares this code (`iOS/` folder) and was not run locally. In
build 1690816 its BlazorWebView work items passed 62/63 at 8e70055
without this change, on macOS 15 (Helix c7a22071) and macOS 26 (Helix
cf4220c0), so only iOS shows the failure. This PR's CI covers
MacCatalyst with the change.

**CI on merge 151ca05:** maui-pr
[1691141](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691141)
succeeded. Device tests
[1691443](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691443)
succeeded with 0 failed tests in all 9 runs (Android, iOS, MacCatalyst,
Windows). All six tests above pass in the iOS Mono and CoreCLR runs on
macOS 15 and 26 and in both MacCatalyst runs. Without this change, a
rerun of 1690816's failed jobs at 8e70055 failed the same test again:
across both attempts it failed 4 of 4 iOS runs on macOS 26 and 1 of 4 on
macOS 15.

### Issues Fixed

No separate issue is logged. This is a follow-up to #40419, found while
auditing the SR2 candidate (#40116).

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
@kubaflo kubaflo added this to the .NET 11 SR2 milestone Nov 24, 2026
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
…web content process ends (dotnet#40419)

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This adds public API, so it targets `main`.

### Description of Change

On iOS and Mac Catalyst, a Blazor Hybrid app reloads itself and loses
all UI state whenever the WKWebView's web content process
(`com.apple.WebKit.WebContent`) ends, for example because it crashed or
the system reclaimed it. Reporters see it after leaving the app
minimized or on another Space for a while.

`WebViewNavigationDelegate` in `IOSWebViewManager.cs` does not implement
`webViewWebContentProcessDidTerminate:`. When no client handles the
termination, WebKit reloads the page on its own
([`WebPageProxy::notifyClientOfProcessTermination`](https://github.com/WebKit/WebKit/blob/main/Source/WebKit/UIProcess/WebPageProxy.cpp)),
and when the view is not visible it holds that reload back until it is.
Blazor then attaches to the new page, `WebViewManager.AttachToPageAsync`
disposes the old page context, and every component starts over. The app
is never told.

I reproduced it on demand on macOS 26.2 with MAUI 10.0.20 by killing the
web content process, and wrote it up with logs in the issue:
dotnet#24669 (comment). The
repro app is
https://github.com/Kebechet/maui-blazorwebview-reload-repro.

**Change**

- `WebViewNavigationDelegate` implements `ContentProcessDidTerminate`
and raises the new `BlazorWebView.ProcessTerminated` event.
- Implementing it turns WebKit's own reload off, so the new
`WebContentProcessReloader` does that reload the way WebKit does
(`notifyClientOfProcessTermination`, `maybeReloadAfterCrashWhenVisible`
and `tryReloadAfterProcessTermination` in `WebPageProxy.cpp`):
- It reloads right away when the web view is visible: in a window whose
scene is not in the background, as `PageClientImpl::isViewVisible`
decides on iOS. Otherwise it waits until the web view is added to a
window or its scene comes back to the foreground.
- A new navigation drops a pending reload, since it starts a web content
process of its own.
- Crash-loop limit: when the process ends again before a page has been
loaded for 30 seconds after a reload, that termination is not reloaded.
After skipping one, the next termination reloads again, as in WebKit.
- When the process ended before the first page was committed, there is
nothing to reload, so the page that was being loaded (`WKWebView.Url`)
is loaded again, like WebKit does with its pending request.
- `BlazorWKWebView`, a `WKWebView` subclass, raises `MovedToWindow` like
`MauiWKWebView` does. Without it, `UIView.OnLoaded` only notices a
window when the view's bounds change, which does not happen when the
same web view is shown again at the same size. **Side effect:** this
also changes how MAUI detects that a `BlazorWebView` is loaded on iOS
and Mac Catalyst: through `MovedToWindow`, as for `WebView`, instead of
the bounds observer.
- Logged: `ReloadingAfterWebContentProcessTermination` (warning),
`DeferringReloadAfterWebContentProcessTermination` (warning) and
`NotReloadingAfterWebContentProcessTermination` (error).

**API**

| API | Notes |
| --- | --- |
| `BlazorWebView.ProcessTerminated` |
`EventHandler<WebViewProcessTerminatedEventArgs>`, the same args as
`WebView.ProcessTerminated`; `PlatformArgs.Sender` is the `WKWebView` |
| `IBlazorWebView.ProcessTerminated(WebProcessTerminatedEventArgs)` |
default interface member, so existing implementations keep compiling,
like `IWebView.ProcessTerminated` |

The event is raised before the reload, while the existing components and
services are still alive, so an app can save the state it wants to
restore once Blazor starts again.

Open question for API review: the event does not tell the app whether a
reload follows, or whether the crash-loop limit skipped it and the page
stays blank. That would need a property on the event args, which
`WebView.ProcessTerminated` shares, so I left it out for now.

**Not covered here**

- Android and Windows are not wired up. Android's `WebKitWebViewClient`
does not override `OnRenderProcessGone`, and Windows does not handle
`CoreWebView2.ProcessFailed`. Both need their own recovery work, so I
kept this PR to iOS and Mac Catalyst.
- The plain `WebView` has the same gap on iOS and Mac Catalyst:
`MauiWKWebView` exports `webViewWebContentProcessDidTerminate:` on the
`WKWebView` subclass, but WebKit sends it to the navigation delegate
(`MauiWebViewNavigationDelegate`), so `WebView.ProcessTerminated` does
not seem to fire there. That belongs in Core and is not changed here.
- Keeping component state across a restart of the web content process
would need support in `WebViewManager` in aspnetcore.

### Tests

Device tests in `BlazorWebViewTests.ProcessTermination.iOS.cs` (it also
compiles for Mac Catalyst). They end the web content process with
`kill(pid, SIGKILL)`, which is what the system does to it. The pid comes
from the private `_webProcessIdentifier` property, used only in the
test.

| Test | Covers |
| --- | --- |
|
`WebContentProcessTerminationRaisesProcessTerminatedAndReloadsVisiblePage`
| in a window: the event is raised with the web view as `Sender`, and
Blazor renders the root component again right away |
| `WebContentProcessTerminationReloadsHiddenPageOnceItIsInAWindow` | not
in a window: the reload waits, and happens once the web view is added to
a window |
| `WebContentProcessTerminationRightAfterReloadDoesNotReloadAgain` | a
second termination less than 30 seconds after the reloaded page loaded
raises the event but does not reload |
| `WebContentProcessTerminationLongAfterReloadReloadsAgain` | a second
termination 30 seconds after the reloaded page loaded reloads again |
| `WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain` |
the process ends while WebKit decides on the first navigation, before
anything is committed; the page is loaded again and Blazor starts |

The two tests about the 30 seconds swap the handler's internal
`TimeProvider` for a manual one, so they do not depend on timing.

Run locally with xharness, `Category=BlazorWebView`, on `main`
(331056d):

| Run | Result |
| --- | --- |
| Mac Catalyst | 53 passed, 0 failed, 1 skipped |
| iOS simulator 26.5 | 53 passed, 0 failed, 1 skipped |
| Mac Catalyst, with three behaviors switched off: the web view always
counts as visible, a reload is never forgotten, and `Reload()` is used
even when nothing was loaded | exactly the three tests that cover them
fail (hidden web view, termination after the 30 seconds, termination
before the first page), the other two pass: 50 passed, 3 failed, 1
skipped |

### Issues Fixed

Addresses dotnet#24669: apps are now told
when the web content process ends, and BlazorWebView handles the reload
itself instead of WebKit doing it silently. It does not stop the system
from ending the process, and the UI state is still lost unless the app
restores it.

Co-authored-by: Jakub Florkowski <kubaflo123@gmail.com>
KarthikRajaKalaimani pushed a commit to KarthikRajaKalaimani/maui that referenced this pull request Nov 26, 2026
…nt process ends before it starts loading (dotnet#40455)

<!-- Please let the below note in for people that find this PR -->
> [!NOTE]
> Are you waiting for the changes in this PR to be merged?
> It would be very helpful if you could [test the resulting
artifacts](https://github.com/dotnet/maui/wiki/Testing-PR-Builds) from
this PR and let us know in a comment if this change resolves your issue.
Thank you!

<!--
Open .NET 11 fix PRs against net11 for review; target main for
next-major features.
After approval, a maintainer manually retargets the fix PR to the active
inflight
branch and merges it directly there. Do not merge individual fixes into
net11.
Bots must not retarget or merge. Candidate integration into net11 and
release/*
changes are separate, explicitly coordinated release work.
-->

### Target Branch

| This PR is for | Initial base |
| --- | --- |
| New features, API changes, or .NET 12 work (including .NET 12 fixes) |
`main` |
| .NET 11 servicing fixes | `net11`, for review |
| Older servicing, release integration, infrastructure, or documentation
| The branch designated for that work |

- [x] I selected the applicable base branch using the [contribution
guide](https://github.com/dotnet/maui/blob/main/.github/CONTRIBUTING.md#choose-your-pr-base-before-starting).

This targets `candidate/11.0.1xx-sr2`, the same base as dotnet#40419.
`WebContentProcessReloader` exists only on the SR2 candidate; it is not
in `net11` or `main`.

For .NET 11 fixes, only a maintainer retargets the approved PR to the
active
inflight lane and merges it after CI validates that final base. Do not
merge
individual fixes directly into `net11`; agents must not retarget or
merge.

### Description of Change


`BlazorWebViewTests.WebContentProcessTerminationBeforeFirstPageLoadsLoadsThatPageAgain`
was added in dotnet#40419. It fails on iOS for both the Mono and CoreCLR legs
of the candidate's device-test build
[1690816](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1690816)
(head 8e70055):

```
System.TimeoutException : controlDiv never became 'Static' after the reload. Last value: '<null>'.
```

**Root cause.** The test ends the web content process from `UrlLoading`,
which runs inside `DecidePolicy` for the first navigation, before that
navigation starts. By the time `ContentProcessDidTerminate` is called,
WebKit has already reset its page load state (`PageLoadState::reset`),
so `WKWebView.Url` and `BackForwardList.CurrentItem` are both `null`.
`WebContentProcessReloader.TryReload` assumed that "the page that was
being loaded is still the web view's URL". It therefore fell back to
`Reload()`, which has nothing to load, and the page never loaded.

Temporary diagnostics confirmed this on an iOS 26.0 simulator. For this
test the callback saw `url=<null> current=<null> visible=True`, so the
reload ran immediately (no window wait) and still had no URL.

WebKit avoids this with its own pending API request.
`WebPageProxy::tryReloadAfterProcessTermination` loads
`pendingAPIRequestURL` again when it is set, and calls `reload()` only
otherwise. `pendingAPIRequest` is set by `loadRequest` and cleared when
that navigation starts (`didStartProvisionalLoadForFrame`). It isn't
exposed through `WKWebView`.

**Fix.**
- `WebContentProcessReloader` mirrors WebKit's pending API request.
`PageRequested` remembers the page MAUI last asked for with
`LoadRequest`, and `NavigationStarted` (`DidStartProvisionalNavigation`)
forgets it.
- `TryReload` loads that page again when it is still pending. Otherwise
it keeps the existing behavior: load `Url` when there's no committed
page, else `Reload()`.
- `IOSWebViewManager` calls `PageRequested` for both of its
`LoadRequest` calls: the start page in `NavigateCore`, and the
app-scheme redirect re-issue.
- The URL is stored as a string because `NavigateCore` disposes its
`NSUrl`.
- No test, public API or existing reload/throttle/window-wait behavior
changes.

Intentional difference from WebKit: WebKit also drops the pending
request when the policy decision ignores that navigation. Here the page
stays pending until a navigation starts. If the app cancels its start
page in `UrlLoading` and the process later ends before any navigation
starts, the reload asks for that page again. It still goes through
`DecidePolicy`/`UrlLoading`, so the app's decision still applies.

**Causal evidence.** iOS 26.0 iPhone 11 Pro simulator, Xcode 27.2. Each
run used the full `BlazorWebView` device-test suite:

```
pwsh .github/skills/run-device-tests/scripts/Run-DeviceTests.ps1 -Project BlazorWebView -Platform ios -DeviceUdid <udid> -OutputDirectory artifacts/<run> -SkipXcodeVersionCheck
```

| Run | Tree | Result |
| --- | --- | --- |
| Baseline | 8e70055 (candidate head) | **Red**: 61 passed, 1 failed
(this test, same `'<null>'` error as CI), 1 skipped |
| Fix | this PR | **Green**: 62 passed, 0 failed, 1 skipped |
| Fix reverted | production change stashed | **Red**: 61 passed, 1
failed (same test, same error), 1 skipped |
| Restored | this PR | **Green**: 62 passed, 0 failed, 1 skipped |

All six `WebContentProcessTermination*` tests pass with the fix:
- `RaisesProcessTerminatedAndReloadsVisiblePage`
- `ReloadsHiddenPageOnceItIsInAWindow`
- `RightAfterReloadDoesNotReloadAgain`
- `LongAfterReloadReloadsAgain`
- `BeforeFirstPageLoadsLoadsThatPageAgain`
- `AfterThePageNavigatedByItselfReloadsTheNewPage` (added in 4bb40d5
after review; fails if `NavigationStarted` doesn't clear the pending
request, otherwise 63 passed, 0 failed, 1 skipped)

`dotnet format whitespace --verify-no-changes` passes on both files.
MacCatalyst shares this code (`iOS/` folder) and was not run locally. In
build 1690816 its BlazorWebView work items passed 62/63 at 8e70055
without this change, on macOS 15 (Helix c7a22071) and macOS 26 (Helix
cf4220c0), so only iOS shows the failure. This PR's CI covers
MacCatalyst with the change.

**CI on merge 151ca05:** maui-pr
[1691141](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691141)
succeeded. Device tests
[1691443](https://dev.azure.com/dnceng-public/public/_build/results?buildId=1691443)
succeeded with 0 failed tests in all 9 runs (Android, iOS, MacCatalyst,
Windows). All six tests above pass in the iOS Mono and CoreCLR runs on
macOS 15 and 26 and in both MacCatalyst runs. Without this change, a
rerun of 1690816's failed jobs at 8e70055 failed the same test again:
across both attempts it failed 4 of 4 iOS runs on macOS 26 and 1 of 4 on
macOS 15.

### Issues Fixed

No separate issue is logged. This is a follow-up to dotnet#40419, found while
auditing the SR2 candidate (dotnet#40116).

<!--
Verify the target branch follows the release workflow in
docs/ReleaseBranchWorkflow.md.
Infrastructure and documentation changes should target the branch where
they apply.
-->

---------

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community ✨ Community Contribution s/agent-gate-failed AI could not verify tests catch the bug

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants