Repository navigation
feat(web): save downloads and apply request headers - #76
Merged
Merged
Conversation
6 tasks
houko
force-pushed
the
feat/webview-downloads
branch
from
November 14, 2026 07:08
236f418 to
a7aabee
Compare
houko
force-pushed
the
feat/webview-downloads
branch
2 times, most recently
from
November 14, 2026 07:29
59ac980 to
297915e
Compare
houko
force-pushed
the
feat/webview-downloads
branch
from
November 14, 2026 14:22
653f6b5 to
be1ab29
Compare
Collaborator
Author
|
Reviewed and fixed. Head is be1ab29, rebased onto main. Fixed:
Verified on macOS, Windows 11, Ubuntu 24.04 and a Pixel 3 XL with a probe app; details are in the description. |
houko
marked this pull request as ready for review
November 14, 2026 14:23
…slots ICoreWebView2Environment10 has CreateCoreWebView2ControllerOptions at 20 and CreateCoreWebView2CompositionControllerWithOptions at 22, and ICoreWebView2ControllerOptions has put_IsInPrivateModeEnabled at 6, per WebView2.h: the backend called CreateCoreWebView2ControllerWithOptions to make the options, put_ProfileName to set in-private mode and CreateCoreWebView2ControllerOptions to make the composition controller. A web view now also takes its config when it is made, since an environment that already exists calls back before configure and the controller was made without Incognito.
The backend added `Headers` to every request the view made, subresources and other origins included, through a WebResourceRequested filter on all URLs, so an `Authorization` header reached third parties and later navigations; the filter also read the request's headers and set them through the wrong vtable slots (get_Method and GetIterator rather than get_Headers at 9 and SetHeader at 6). Following the contract and the other backends, a URL source now loads through ICoreWebView2_2::NavigateWithWebResourceRequest with a request from ICoreWebView2Environment2::CreateWebResourceRequest carrying the headers, the interception is gone, and a change of headers loads the page again as on Apple and Linux.
WebView2 raises WebResourceRequested for a custom scheme, and navigates to one, only when the environment registered it through ICoreWebView2EnvironmentOptions4::SetCustomSchemeRegistrations as it was made, and the backend made every environment without options, so no `ServeScheme` page loaded on Windows. The environment now gets a Go ICoreWebView2EnvironmentOptions with ICoreWebView2EnvironmentOptions4, following WebView2EnvironmentOptions.h's defaults, whose registrations are secure schemes with an authority and no other allowed origins. It starts once the batch that made its first web view is applied, registering the schemes of all that batch's web views, and every environment of a profile folder registers the first one's, as WebView2 refuses environments of one folder with different options; a scheme served later cannot load on Windows, which is logged once and documented. Each view filters requests by its schemes rather than all URLs, and responses no longer carry `Access-Control-Allow-Origin: *`, so pages of other origins in the view cannot read app-scheme bodies.
WebMIME checked an HTML or XML signature's length against the whole body rather than what follows its leading whitespace, so a response such as "\n<b" or " <HTML>" sliced past the body's end and panicked on the UI thread. It now matches against the rest after the whitespace, as WHATWG's sniffing does, compares only the BOM of the four-byte UTF-16 patterns rather than two following zero bytes, matches "<?xml" case-sensitively, and takes "<!--" without a tag-terminating byte, per the spec's table.
ServeScheme refused only http, https, file, data, blob and about, while WKWebView's setURLSchemeHandler:forURLScheme: raises NSInvalidArgumentException, which ends the app, for every scheme WebKit handles itself (LegacySchemeRegistry::isBuiltinScheme: ws, wss, javascript, ftp, applewebdata, webkit-fake-url and the rest). ServeScheme now refuses that whole set with an error, and Apple's host checks +[WKWebView handlesURLScheme:] before registering a scheme, skipping it with a log, so a later WebKit's own scheme cannot end the app either.
ServeScheme is documented as serving the web views created under its scope, but it wrote one map per runtime, every web view took a copy of all of it, and a restricted owner's sources allowed any scheme served anywhere, so a scheme one subtree or window served reached the web views of every other. The handler now goes in the scope's values, a web view takes the schemes served by its scope and those above, the nearest answering, and a restricted owner loads only the schemes visible from it. Tests check that a sibling subtree and another window see neither the scheme nor its handler.
The Linux and Windows hosts handed the engine a pointer to the download item they keep updating. The engine reads events on its own goroutine, so a started report could arrive reading as finished, and an app saw the end of one download twice and never its start. Each report now carries a copy, as the Apple host's does.
The Linux host kept a set of window handles per network session and released the app's session when the last window using it closed one web view, without forgetting it in webSessions. A web view mounted again then panicked on a nil map inside a GTK callback and used the freed session; with two web views in one window, closing one left the other unable to find itself, so its downloads were cancelled and its app-scheme requests never finished. Scheme requests also carried the session of whichever view registered the scheme first on the shared WebKitWebContext. The app's persistent session now lives as long as the process, as it did before downloads were added; an Incognito view owns its session and releases it as it closes. Live pages are kept by WebKitWebView, which scheme requests and downloads look up, each scheme is registered once per web context with no session attached, and every scheme request is finished, with a WebKit network error when no live view serves its scheme. A Linux test, run in a process of its own as WebKit keeps the first thread that uses it, mounts web views again in both kinds of session and checks schemes, downloads and an unserved scheme.
webkit_network_session_new(NULL, NULL) makes a persistent session in WebKit's default directories, so an Incognito web view on Linux stored cookies and website data on disk, shared with every other such view. It now makes its session with webkit_network_session_new_ephemeral, available since WebKitGTK 2.40, whose website data manager keeps nothing on disk.
A download whose web view closed before WebKit asked for its destination read the closed view's configuration and panicked in a GLib callback. As on Windows, a closing web view now cancels and forgets the downloads it was saving, holding a reference to each download it follows until then, and the download callbacks cancel a download no live view saves rather than leave it to WebKit's default folder. The Linux web view test now unmounts a view in the middle of a download and checks that the server sees it cancelled.
The main-frame file: check refused every file: navigation of a view whose source was not a file: URL, so unrestricted HTML with a file: base URL, such as WebHTML(html, "file:///Users/me/app/"), which loaded before, was refused. HTML with a file: base URL now navigates within the base's directory, as a file: page does within its own; unrestricted views with other sources leave file: links to WebKit as before, and restricted ones still refuse them.
The commit that made Android's incognito web views turn off the HTTP cache, DOM storage and form saving changed WebNode.java without rebuilding classes.dex and classes.jar, so apps ran the old runtime and Incognito did nothing on Android. Both are rebuilt with build.sh. android.webkit keeps one cookie store and one set of website data per app, so WebView.Incognito's comment and the native views document now say what Android does and does not keep apart.
Android's web view host fetched every download again with java.net.URL, so data: and blob: downloads always failed ("unknown protocol"), and it would have copied a file: URL a page offered as a download. It now decodes data: URLs itself, base64 or percent-encoded, and has the page read a blob: URL, which only its document can, handing the bytes back under a random token through a JavaScript interface; a page that leaves first, or has JavaScript off, fails the download with a message. Both save under the name the link's download attribute gives, which a script run as each page starts notes because android.webkit reports downloads without it, else "download" with the type's extension. Only http(s) downloads are fetched again, now with a Referer as browsers send one by default and the view's Headers when the download is on its source's origin. classes.dex and classes.jar are rebuilt.
… URL Android's web view read a blob: download by fetching its URL in the page, but only after android.webkit reports the download, which comes after the click returns, and after evaluateJavascript hops back to the renderer. Pages commonly revoke the object URL right after clicking the link (URL.revokeObjectURL in the same task or a short timeout), so the fetch failed with "TypeError: Failed to fetch" and the download was reported failed. The script run as each page starts now remembers which Blob each object URL the page makes stands for, forgetting it when the page revokes the URL, and keeps the Blob when a download link to that URL is clicked; the blob reader takes the kept Blob, dropping it, before falling back to fetching the URL. Object URLs made before that script runs, or in a frame, still go through the fetch. classes.dex and classes.jar are rebuilt.
Rebasing onto main took this branch's classes.dex and classes.jar, which lacked the biometric Java main had compiled in. Rebuilt with build.sh from the merged sources, so the runtime has both the web view changes and biometric authentication.
houko
force-pushed
the
feat/webview-downloads
branch
from
November 14, 2026 15:12
be1ab29 to
0326f5f
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Problem
Web views that request a download need to save it under the app-owned downloads directory and report the
OnDownloadlifecycle consistently across supported backends. Website data also needs an opt-in in-memory mode for private embedded pages, and desktop apps need to serve authenticated app content without opening a local TCP port.Change
download-started, WebView2DownloadStarting, and AndroidDownloadListener<id>/<filename>destinationOnDownloaddestination is configured..edge casesWebView.Headerson Apple, Windows, Linux and Android, sent with the initial URL request onlyWebView.Incognito: non-persistent WebKit data on Apple, an ephemeral WebKitGTK network session per view on Linux, in-private WebView2 controller profiles on Windows, and on Android, whoseandroid.webkithas one cookie store and one set of website data per app, no HTTP cache, no DOM storage and no saved form data (cookies, IndexedDB and HTTP authentication stay shared; documented)Scope.ServeScheme, serving app-owned URL schemes on Apple, Windows and Linux with inferred content types, scoped to the web views under the serving scopegallery://scheme, while retaining inline fallback on unsupported targetsfile:pages, and HTML with afile:base URL, to navigate only within their directoryEnv.CanSendInput; macOS reports trusted input support and unsupported backends safely report falseEnv.HasWebView, reporting whether the target provides a web view host (false on tvOS)data:downloads by decoding them, andblob:downloads by having the page read the blob, under the name the link'sdownloadattribute gives; Android's http(s) re-fetch sends the page's cookies, user agent, a Referer and, on the source's origin, the view'sHeadersclasses.dexandclasses.jarwithinternal/platform/android/runtime/build.shnet/httpTrusted input delivery on Windows, Linux and iOS remains unavailable because their native web hosts have no supported trusted-event injection bridge; apps can gate the action with
Env.CanSendInput. Remaining gallery coverage is separate follow-up work for issue #33.Review fixes
ICoreWebView2Environment10's real vtable slots (CreateCoreWebView2ControllerOptions,CreateCoreWebView2CompositionControllerWithOptions,put_IsInPrivateModeEnabled), and pass the config when the controller is made so an existing environment does not loseIncognitoHeadersonly with the initial navigation throughNavigateWithWebResourceRequest, rather than intercepting every request of every origin with wrong vtable slotsICoreWebView2EnvironmentOptions4::SetCustomSchemeRegistrations) soServeSchemepages load, and stop answering them withAccess-Control-Allow-Origin: *ServeScheme(and skip such schemes on Apple), which would end the app on AppleWebKitWebViewrather than by session and window, keep the app's persistent network session for the process's life, release an incognito session with its view, register each scheme once per web context, and finish every app-scheme request, with an error when no view serves it; mounting a web view again no longer panics and closing one no longer breaks another in the same windowwebkit_network_session_new_ephemeral, aswebkit_network_session_new(NULL, NULL)is persistent in WebKit's default directoriesfile:base URL again, navigating within the base's directoryBlobbehind a clickeda[download]link to ablob:URL until the download reads it, so a page that revokes the object URL right after the click (the usual hand-written pattern) still saves the file instead of failing withTypeError: Failed to fetchValidation
go tool nsgo check -target allgo tool nsgo test: 1830 passed, 2 failed, 12 skipped; the failures areTestSmallJSON/v2, as the local Go 1.26 toolchain excludesencoding/json/v2, andTestASwipeTurnsTheRing, known failures unrelated to this changeGOOS=windows go vetandGOOS=linux go vetof the touched packagesgo tool nsgo test -target macosininternal/platform/apple, including the newfile:base URL testinternal/platform/linuxbuilt withCGO_ENABLED=0 GOOS=linux GOARCH=arm64 go test -cand run under Xvfb in Debian trixie with GTK 4.18 and WebKitGTK 6.0 2.54:TestWebViewTalksToThePageand the newTestWebViewsOutliveEachOtherpass; the new test fails on the previous Linux backend (an unserved scheme never finished, a download kept going after its view unmounted)GOOS=windows GOARCH=amd64 go test -c ./internal/platform/windows(the Windows tests were not run on Windows)classes.dexchecked to contain the incognito settings and the blob bridge after the rebuildWebNode.javaand run in headless Chromium: without the script, ablob:link revoked in the same task or a 0 ms timeout fails withTypeError: Failed to fetch; with it, both save the bytes under the link'sdownloadname and the keptBlobis dropped once readReal-device checks with a probe app (an Incognito web view loading a local page that fetches subresources and triggers
data:,blob:and http downloads, a second web view on an app scheme,ServeScheme("ws")andServeScheme("javascript"), and the web view unmounted and mounted again):Headers; the app-scheme page loads and runs; all three downloads save, including ablob:URL revoked right after the click;wsandjavascriptare refused; everything works again after the remount.Headers; theprobe://page loads and runs, so the scheme registration takes;data:,blob:and http downloads save. Several downloads a page starts without a user gesture are held by WebView2's multiple-downloads permission, as in Edge. The new Windows tests (TestWebEnvironmentOptionsRegisterSchemes,TestWebRequestHeadersAreLines,TestWebViewPostsMessagesBothWays,TestWebDownloadFilenameStaysInDownloadDirectory) pass there. The rest of the package fails the same tests on that VM as on main, which has a locked console and no GPU.kernel.apparmor_restrict_unprivileged_userns=1stops WebKit's bubblewrap sandbox, so any nsgo web view aborts there on main too unless the app is confined by an AppArmor profile; that is outside this PR.data:,blob:(revoked right after the click) and https downloads save; an Incognito view has nolocalStorage, so the rebuilt runtime is in use.Known, not changed here: when a navigation turns into a download, Apple (as on main) and now Windows also report an
OnErrorfor the interrupted navigation (Frame load interrupted,The connection was aborted.); Linux does not.