Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions cmake/Frontends.cmake
Original file line number Diff line number Diff line change
Expand Up @@ -440,8 +440,9 @@ function(webfront_add_browser_tests target frontend assets_directory lifecycle_t
endif()
set(lifecycle_modes no-bridge early-close rejected-ready navigation-failure path-encoding content-policy navigation-allow-list view-association stage-report)
list(APPEND lifecycle_modes ui-executor native-window second-open host-close second-window)
# A closed secondary window disconnects at once, window after window (#702); WKWebView's page outlived its window.
if(frontend STREQUAL "WKWebView")
# A closed secondary window disconnects at once, window after window: WKWebView's page outlived its window (#702),
# and WebView2's page its controller (#708).
if(frontend MATCHES "^(WKWebView|WebView2)$")
list(APPEND lifecycle_modes secondary-close)
endif()
# CEF neither supports nor checks a secondary thread: nothing to observe there (docs/HOST_INTEGRATION.md).
Expand Down
1 change: 1 addition & 0 deletions docs/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,7 @@ these entries stays in the GitHub releases and the Git history.
### Fixed
- A closed WKWebView secondary window, or one that another window covered, no longer leaves its page suspended and connected to the application: on macOS 14+ a secondary window is never suspended while inactive (#681, `docs/WKWEBVIEW.md`).
- A closed WKWebView secondary window disconnects as soon as it is released, even while the system still holds its view: its page is closed explicitly instead of when the view's last reference goes, which kept the detached inspector window connected for more than thirty seconds (#702, `docs/WKWEBVIEW.md`).
- A closed WebView2 secondary window disconnects at once: its page navigates to `about:blank` before its controller closes, instead of ending whenever the renderer of the shared environment got to it, which once kept the detached inspector window connected for more than thirty seconds (#708, `docs/WEBVIEW2.md`).
- A WKWebView page whose web content process ends says why: its memory or CPU limit, the application's request, or a crash of the WebKit engine, which `DeveloperBrowserIntegration-jasmine` met on the macOS runner while esbuild ran in its Worker, instead of only that the process terminated (#706, `docs/WKWEBVIEW.md`).
- `webfront.session` names the native deadline that revoked a session (`revocation`: `operation-deadline` or `startup-deadline`, empty otherwise), and `Session::revokedBy()` gives it in C++: `AutomationMcpWatchdog` no longer fails when the window closes after the deadline, since its host recognised only a reason that the deadline never wrote (#709, `docs/AUTOMATION.md`).
- An invalid content policy (an origin of `bridgeAllowedOrigins` or `navigationAllowedOrigins`, a `referrerPolicy`, a `htmlCacheControl`) throws `std::invalid_argument` before the server binds its port, as documented, instead of an "address already in use" error when that port is taken (#674).
Expand Down
1 change: 1 addition & 0 deletions docs/FRONTENDS.md
Original file line number Diff line number Diff line change
Expand Up @@ -213,6 +213,7 @@ Registry order determines the initial cache default: the first enabled embedded
- `content-policy`: block a popup and a foreign-origin top-level navigation while keeping the original page alive.
- `navigation-allow-list`: permit the same top-level destination through the explicit navigation allow-list.
- `second-window` (#616): a second window shares storage, a `cppFunction` and a pushed `jsFunction` with the first and carries the embedded-view proof; the same page again opens nothing; closing the second leaves the first usable and it can reopen; closing the first closes the second; a window opened as soon as the loop runs, before the first page connected, opens; a request that runs in the pass where the first window closed is refused (WebKitGTK, WKWebView). Frontends without the capability must refuse with `std::logic_error`.
- `secondary-close` (#702, #708; WKWebView and WebView2): a secondary window opened and closed five times in a row disconnects each time within 3 s, and the first window stays usable.
- `host-close`: a host thread exchanges with the page while `show()` runs, then `requestClose()` ends the session; a request before and after the window is refused.
- `host-thread` (not CEF): `webfront::UIThread` runs the application on a secondary thread where the frontend allows it; elsewhere a window opened on a secondary thread must be refused with the main-thread diagnostic.
- `view-association`: the page of the view connects with the secret of the launch and `UI::isEmbeddedView()` is true; a second connection of that page, from the same loopback address and without the secret, is not associated.
Expand Down
2 changes: 1 addition & 1 deletion docs/WEBVIEW2.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ This page covers what is specific to WebView2. The rules shared by every fronten

The **Microsoft Edge WebView2 Evergreen Runtime** must be installed separately. If it is absent, opening throws an actionable error before creating a window. App installers can redistribute Microsoft's small online Evergreen bootstrapper or the offline Evergreen standalone installer; see [Microsoft's runtime distribution guide](https://learn.microsoft.com/en-us/microsoft-edge/webview2/concepts/distribution). Fixed-version runtime packaging is outside this adapter's scope.

Follow the [shared main-thread contract](FRONTENDS.md#the-contract). WebView2 additionally needs STA-compatible COM; an existing MTA apartment is rejected. The adapter balances COM initialisation, owns the message loop, resizes the view with its window and applies `WM_DPICHANGED`'s suggested bounds. It handles JavaScript `window.close()` and releases its controller on shutdown. Closing is idempotent; a failed controller `Close()` is reported by `show()` without replacing an earlier error. Late callbacks after the session has ended can only release their own controller references.
Follow the [shared main-thread contract](FRONTENDS.md#the-contract). WebView2 additionally needs STA-compatible COM; an existing MTA apartment is rejected. The adapter balances COM initialisation, owns the message loop, resizes the view with its window and applies `WM_DPICHANGED`'s suggested bounds. It handles JavaScript `window.close()` and releases its controller on shutdown. Closing is idempotent; a failed controller `Close()` is reported by `show()` without replacing an earlier error. Late callbacks after the session has ended can only release their own controller references. A secondary window that closes is hidden and first navigates to `about:blank`, which ends its page and the page's connection; its controller closes when that navigation completes, or after one second (#708). Closing the controller alone ends the page only when its renderer gets to it, and the renderer of the shared environment may outlive the controller.

Profiles default to `%LOCALAPPDATA%/WebFront/<executable-path-hash>/WebView2`, so the executable directory can be read-only. The FNV-64 executable-path hash is case-sensitive: paths differing only by case can select separate profiles. Instances of the same executable share that profile. It is persistent and is not automatically deleted; select another `userDataFolder` through the options below when isolation is needed.

Expand Down
94 changes: 86 additions & 8 deletions include/webfront/frontend/WebView2.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -301,8 +301,11 @@ class Session : public std::enable_shared_from_this<Session> {
UINT_PTR startupTimer = 0;
// A window opened beside the application's own (#616): it shares the environment (profile, browser process) of the first,
// runs no loop of its own and reports its closing to closedHook, once, instead of ending the session.
bool secondary = false;
std::function<void()> closedHook;
bool secondary = false;
std::function<void()> closedHook;
// Called once when a secondary window starts to end its page (#708): the registry takes it out of its table, so that
// its page can be opened again while it closes.
std::function<void()> closingHook;
std::shared_ptr<CaptureQueue> captureQueue = std::make_shared<CaptureQueue>();
CaptureRegistration captureRegistration;

Expand All @@ -317,7 +320,8 @@ class Session : public std::enable_shared_from_this<Session> {
}

void navigationStarting(ICoreWebView2NavigationStartingEventArgs* args) noexcept {
if (closed)
// The navigation of an unloading window is its own to about:blank, which no content policy lists.
if (closed || unloading)
return;
try {
LPWSTR raw = nullptr;
Expand Down Expand Up @@ -358,6 +362,7 @@ class Session : public std::enable_shared_from_this<Session> {
void close() noexcept {
stopStartupTimer();
stopPresentTimer();
stopUnloadTimer();
if (closed)
return;
closed = true;
Expand Down Expand Up @@ -518,7 +523,63 @@ class Session : public std::enable_shared_from_this<Session> {
// (moving or resizing by the title bar), which dispatch window messages without going through dispatchNextMessage().
static constexpr UINT_PTR presentTimerId = 0x5746;
static constexpr UINT_PTR startupTimerId = 0x5747;
void stopPresentTimer() noexcept {
static constexpr UINT_PTR unloadTimerId = 0x5748;
// The wParam of the WM_CLOSE that finishUnload() posts: the page has ended, the window closes now.
static constexpr WPARAM unloadedClose = 0x5748;
// The longest wait for a closing secondary window's page to end, after which it closes all the same.
static constexpr UINT unloadMilliseconds = 1000;
bool unloading = false;
UINT_PTR unloadTimer = 0;

/**
* A secondary window ends its page before its controller (#708). The controller's Close() releases the view, but
* the page, and with it its WebSocket, ends only when its renderer gets to it: the renderer of the shared environment
* may outlive the controller, and a closed inspector window then stayed connected for more than thirty seconds.
* Navigating to about:blank unloads the document, which closes its connections, at once. The window is hidden
* meanwhile; it closes when about:blank completes, or after unloadMilliseconds. False when the window closes at once:
* the first window (its process ends its pages), a window that failed or has no view, or a navigation refused.
*/
bool beginUnload() noexcept {
if (!secondary || closed || failure || !hasLiveController() || !view || !window)
return false;
try {
unloading = true;
ShowWindow(window, SW_HIDE);
unloadTimer = SetTimer(window, unloadTimerId, unloadMilliseconds, nullptr);
if (!unloadTimer)
throw std::runtime_error("WebView2: cannot start the unload delay");
check(view->Navigate(L"about:blank"), "unloading the page of a closing window");
trace("unloading");
if (closingHook) {
auto hook = std::exchange(closingHook, {});
try {
hook();
} catch (...) { }
}
return true;
} catch (...) {
stopUnloadTimer();
return false; // closed at once, as before
}
}
void finishUnload() noexcept {
stopUnloadTimer();
if (window)
PostMessageW(window, WM_CLOSE, unloadedClose, 0);
Comment thread
ambroise-leclerc marked this conversation as resolved.
Resolved
}
void stopUnloadTimer() noexcept {
if (unloadTimer && window)
KillTimer(window, unloadTimer);
unloadTimer = 0;
}
bool showsBlankPage() const noexcept {
LPWSTR raw = nullptr;
if (!view || FAILED(view->get_Source(&raw)) || !raw)
return false;
const std::unique_ptr<wchar_t, decltype(&CoTaskMemFree)> source(raw, CoTaskMemFree);
return std::wstring_view{source.get()} == L"about:blank";
}
void stopPresentTimer() noexcept {
if (presentTimer && window)
KillTimer(window, presentTimer);
presentTimer = 0;
Expand Down Expand Up @@ -646,7 +707,7 @@ class Session : public std::enable_shared_from_this<Session> {
}

void processFailed(ICoreWebView2ProcessFailedEventArgs* args) noexcept {
if (closed)
if (closed || unloading) // the page is being ended on purpose: its process may go with it
return;
try {
COREWEBVIEW2_PROCESS_FAILED_KIND kind{};
Expand All @@ -672,6 +733,12 @@ class Session : public std::enable_shared_from_this<Session> {
}

void navigationCompleted(ICoreWebView2NavigationCompletedEventArgs* args) noexcept {
if (!closed && unloading) {
// An earlier navigation that the unloading one cancelled also completes: only about:blank ends the window.
if (showsBlankPage())
finishUnload();
return;
}
if (closed || !initialNavigationPending)
return;
try {
Expand Down Expand Up @@ -739,7 +806,7 @@ class Session : public std::enable_shared_from_this<Session> {
throw std::runtime_error("WebView2: cannot apply DPI window bounds");
}

bool handleWindowMessage(HWND handle, UINT message, LPARAM lParam) {
bool handleWindowMessage(HWND handle, UINT message, WPARAM wParam, LPARAM lParam) {
switch (message) {
case WM_DPICHANGED:
applyDpiBounds(handle, lParam);
Expand All @@ -763,6 +830,10 @@ class Session : public std::enable_shared_from_this<Session> {
reapSecondaryWindows();
return true;
case WM_CLOSE:
// A secondary window first ends its page (#708); the WM_CLOSE of finishUnload() then closes it. Any
// other WM_CLOSE meanwhile (the user, requestClose(), a failure) waits for that one.
if (unloading ? wParam != unloadedClose : beginUnload())
return true;
close();
DestroyWindow(handle);
return true;
Expand All @@ -787,14 +858,19 @@ class Session : public std::enable_shared_from_this<Session> {
self->secondaryStartupTimedOut();
return 0;
}
if (self && message == WM_TIMER && wParam == unloadTimerId && self->unloadTimer) {
self->trace("unload delay expired");
self->finishUnload();
return 0;
}
if (self && message == WM_TIMER && wParam == presentTimerId && self->presentTimer) {
self->trace("present delay expired");
self->presentWindow();
return 0;
}
if (self) {
try {
if (self->handleWindowMessage(handle, message, lParam))
if (self->handleWindowMessage(handle, message, wParam, lParam))
return 0;
} catch (...) {
self->fail();
Expand Down Expand Up @@ -1039,7 +1115,9 @@ struct WindowHooks {
bool close(Session& session) {
if (!session.window)
return false;
SendMessageW(session.window, WM_CLOSE, 0, 0); // the same thread: closed and retired when this returns
// The same thread: the window is closed and retired when this returns, or, for a secondary window whose page
// ends first (#708), hidden and closed within Session::unloadMilliseconds.
SendMessageW(session.window, WM_CLOSE, 0, 0);
return true;
}
};
Expand Down
Loading
Loading