diff --git a/CHANGELOG.md b/CHANGELOG.md index 84b07a6f8..329b7ca26 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ## [Unreleased] +- Add `WebView.UserAgentSuffix`, and `userAgentSuffix` in TSX, to append to the platform's own user agent or to `UserAgent` on macOS, iOS, Android, Windows and Linux (#114 by @houko). - Honor every family in a Windows `FontFamily` list when DirectWrite falls back for missing characters (#668 by @houko). - Add the `macos_universal` build target, which joins the arm64 and x64 apps, libraries and widgets into one direct-channel disk image and Sparkle feed (#265 by @houko). - Stop resolving and emitting the whole tree when the platform reports only a new window frame, maximized state, lifecycle or title bar, as on every step of a window drag; what reads them through `Env` still updates (#178 by @houko). diff --git a/core/commit.go b/core/commit.go index 418071d1e..aed271086 100644 --- a/core/commit.go +++ b/core/commit.go @@ -14,7 +14,7 @@ import ( func sameWebConfig(a, b driver.WebConfig) bool { return a.Source == b.Source && a.InjectedJavaScript == b.InjectedJavaScript && a.InjectedJavaScriptBeforeContent == b.InjectedJavaScriptBeforeContent && - a.UserAgent == b.UserAgent && maps.Equal(a.Headers, b.Headers) && a.Incognito == b.Incognito && + a.UserAgent == b.UserAgent && a.UserAgentSuffix == b.UserAgentSuffix && maps.Equal(a.Headers, b.Headers) && a.Incognito == b.Incognito && a.NoScroll == b.NoScroll && a.NoJavaScript == b.NoJavaScript && a.PinchZoom == b.PinchZoom && a.BackForwardGestures == b.BackForwardGestures && a.Mobile == b.Mobile && a.DownloadDir == b.DownloadDir && a.Restricted == b.Restricted && a.Hosts == b.Hosts && a.Schemes == b.Schemes && a.Media == b.Media diff --git a/core/webview.go b/core/webview.go index 8b64d19d3..0852d5424 100644 --- a/core/webview.go +++ b/core/webview.go @@ -27,6 +27,8 @@ type WebView struct { InjectedJavaScriptBeforeContentFunc func() string // UserAgent replaces the platform's. UserAgent string + // UserAgentSuffix is appended after a space to UserAgent, or to the platform's own user agent when UserAgent is empty, such as Version/26.0 Safari/605.1.15 for sites that want Safari's in WKWebView. Apple platforms add it to their own user agent only as the native view is first made, so changing it afterwards takes effect there only with UserAgent set. HarmonyOS, the web and mini programs ignore it, as they do UserAgent. + UserAgentSuffix string // Headers are sent with the initial URL request where the platform // supports custom request headers. HTML sources do not make one. Headers map[string]string @@ -144,7 +146,7 @@ func (t *Tree) mountWebView(cx *Scope, parent *node, w WebView) { n.props = driver.ViewProps{Label: w.Label, TestID: w.TestID} n.web = &webNode{ config: driver.WebConfig{Source: w.Source, InjectedJavaScript: w.InjectedJavaScript, - InjectedJavaScriptBeforeContent: w.InjectedJavaScriptBeforeContent, UserAgent: w.UserAgent, + InjectedJavaScriptBeforeContent: w.InjectedJavaScriptBeforeContent, UserAgent: w.UserAgent, UserAgentSuffix: w.UserAgentSuffix, Headers: cloneWebHeaders(w.Headers), Incognito: w.Incognito, SchemeHandlers: webSchemesOf(cx), NoScroll: w.NoScroll, NoJavaScript: w.NoJavaScript, PinchZoom: w.PinchZoom, BackForwardGestures: w.BackForwardGestures, diff --git a/core/webview_test.go b/core/webview_test.go index 8b7d77a8d..622b46d74 100644 --- a/core/webview_test.go +++ b/core/webview_test.go @@ -90,6 +90,7 @@ func TestWebViewConfiguresLoadsAndReports(t *testing.T) { Incognito: true, PinchZoom: true, Mobile: true, + UserAgentSuffix: "TestBrowser/1.0", Ref: &ref, TestID: "web", Style: Style{Width: Pt(300), Height: Pt(200)}, @@ -113,7 +114,7 @@ func TestWebViewConfiguresLoadsAndReports(t *testing.T) { if n := h.find("web"); n.kind != driver.KindWeb { t.Fatalf("kind %v, want KindWeb", n.kind) } - if cfg == nil || cfg.Source.Src != "https://example.com" || cfg.InjectedJavaScriptBeforeContent != "before" || cfg.InjectedJavaScript != "1" || cfg.Headers["X-Test"] != "one" || !cfg.Incognito || !cfg.PinchZoom || !cfg.Mobile { + if cfg == nil || cfg.Source.Src != "https://example.com" || cfg.InjectedJavaScriptBeforeContent != "before" || cfg.InjectedJavaScript != "1" || cfg.Headers["X-Test"] != "one" || cfg.UserAgentSuffix != "TestBrowser/1.0" || !cfg.Incognito || !cfg.PinchZoom || !cfg.Mobile { t.Fatalf("config %+v", cfg) } if !mask.Has(driver.EventLoad) || !mask.Has(driver.EventMessage) || mask.Has(driver.EventLoadStart) { diff --git a/docs/public/en/components.md b/docs/public/en/components.md index b31434b94..4e6ca0173 100644 --- a/docs/public/en/components.md +++ b/docs/public/en/components.md @@ -18,9 +18,9 @@ core.View{ } ``` -`core.WebView` shows web content; an empty `WebSource` loads `about:blank` and reports the usual load and navigation events. Set `SourceFunc` to an empty source or call `Ref.Load(core.WebSource{})` to clear the previous page. Set `InjectedJavaScriptBeforeContentFunc` when the script before the page's own scripts follows a signal: when it changes, the view loads its source again with the new script, in place of the page it shows, even one the user or `Ref.Load` navigated to. Attach a `core.Ref` to call `Reload`, `GoBack` and `GoForward`. On native targets these commands keep the app's own HTML and data sources exempt from `core.AccessWebSchemes`; pages that create new navigations still follow the access policy. +`core.WebView` shows web content; an empty `WebSource` loads `about:blank` and reports the usual load and navigation events. Set `SourceFunc` to an empty source or call `Ref.Load(core.WebSource{})` to clear the previous page. Set `InjectedJavaScriptBeforeContentFunc` when the script before the page's own scripts follows a signal: when it changes, the view loads its source again with the new script, in place of the page it shows, even one the user or `Ref.Load` navigated to. Set `UserAgentSuffix` (TSX `userAgentSuffix`) to add a token, such as `Version/26.0 Safari/605.1.15`, after the platform's own user agent, or after `UserAgent` when that is set; on macOS and iOS a suffix to the platform's own takes effect only as the view is first made, and HarmonyOS and the web keep their own user agent. Attach a `core.Ref` to call `Reload`, `GoBack` and `GoForward`. On native targets these commands keep the app's own HTML and data sources exempt from `core.AccessWebSchemes`; pages that create new navigations still follow the access policy. -In TSX, a change of `injectedJavaScriptBeforeContentLoaded` loads the source again with the new script in the same web view, as `InjectedJavaScriptBeforeContentFunc` does; a change of `injectedJavaScript` makes a new web view, which loads the source anew, as a change of `userAgent` or `mobile` does. +In TSX, a change of `injectedJavaScriptBeforeContentLoaded` loads the source again with the new script in the same web view, as `InjectedJavaScriptBeforeContentFunc` does; a change of `injectedJavaScript` makes a new web view, which loads the source anew, as a change of `userAgent`, `userAgentSuffix` or `mobile` does. Set `Mobile` (TSX `mobile`) to show a page as a phone sees it on Windows, macOS and Linux, for sites such as YouTube Shorts that switch videos with vertical swipes only on phones: the page gets a phone's user agent unless `UserAgent` is set and a touch screen without hover, and a drag with the mouse, or a wheel or trackpad scroll over what does not scroll, reaches it as a finger's swipe. Windows emulates a phone as Chrome's device mode does. macOS and Linux do it with a script, so their pages' stylesheets still see a mouse, and the touch events are untrusted, which a page may ignore. iOS, Android, HarmonyOS, the web and mini programs show pages as they are. diff --git a/docs/public/zh/components.md b/docs/public/zh/components.md index 458d78d7a..35313a9bb 100644 --- a/docs/public/zh/components.md +++ b/docs/public/zh/components.md @@ -18,9 +18,9 @@ core.View{ } ``` -`core.WebView` 显示网页内容;空的 `WebSource` 会加载 `about:blank`,并报告通常的加载和导航事件。让 `SourceFunc` 返回空来源,或调用 `Ref.Load(core.WebSource{})`,即可清空之前的页面。若页面自身脚本之前的注入脚本跟随 signal,请设置 `InjectedJavaScriptBeforeContentFunc`:脚本变化时,web view 会带着新脚本重新加载它的来源,替换当前显示的页面,即使那是用户或 `Ref.Load` 导航到的页面。给它绑定一个 `core.Ref` 即可调用 `Reload`、`GoBack` 和 `GoForward`。在原生目标上,这些命令让应用自己的 HTML 和 data 来源继续不受 `core.AccessWebSchemes` 限制;页面自己发起的新导航仍遵循访问策略。 +`core.WebView` 显示网页内容;空的 `WebSource` 会加载 `about:blank`,并报告通常的加载和导航事件。让 `SourceFunc` 返回空来源,或调用 `Ref.Load(core.WebSource{})`,即可清空之前的页面。若页面自身脚本之前的注入脚本跟随 signal,请设置 `InjectedJavaScriptBeforeContentFunc`:脚本变化时,web view 会带着新脚本重新加载它的来源,替换当前显示的页面,即使那是用户或 `Ref.Load` 导航到的页面。设置 `UserAgentSuffix`(TSX 中为 `userAgentSuffix`)可在平台自己的 user agent 之后(设置了 `UserAgent` 时则在它之后)追加一段标识,例如 `Version/26.0 Safari/605.1.15`;在 macOS 和 iOS 上,追加到平台自己的 user agent 只在 web view 首次创建时生效,HarmonyOS 和 Web 保持各自的 user agent。给它绑定一个 `core.Ref` 即可调用 `Reload`、`GoBack` 和 `GoForward`。在原生目标上,这些命令让应用自己的 HTML 和 data 来源继续不受 `core.AccessWebSchemes` 限制;页面自己发起的新导航仍遵循访问策略。 -在 TSX 中,`injectedJavaScriptBeforeContentLoaded` 变化时,同一个 web view 会像 `InjectedJavaScriptBeforeContentFunc` 那样带着新脚本重新加载来源;`injectedJavaScript` 变化时,则会像 `userAgent` 或 `mobile` 变化时一样,换成一个新的 web view,重新加载来源。 +在 TSX 中,`injectedJavaScriptBeforeContentLoaded` 变化时,同一个 web view 会像 `InjectedJavaScriptBeforeContentFunc` 那样带着新脚本重新加载来源;`injectedJavaScript` 变化时,则会像 `userAgent`、`userAgentSuffix` 或 `mobile` 变化时一样,换成一个新的 web view,重新加载来源。 设置 `Mobile`(TSX 中为 `mobile`)后,Windows、macOS 和 Linux 上的页面按手机所见的样子显示,适合 YouTube Shorts 这类只在手机上用上下滑动切换视频的网站:页面得到手机的 user agent(设置了 `UserAgent` 时以它为准)和没有悬停的触摸屏,鼠标拖动、以及在不可滚动处的滚轮或触控板滚动,都会作为手指滑动送达页面。Windows 像 Chrome 的设备模式那样模拟手机。macOS 和 Linux 用脚本实现,因此页面的样式表仍看到鼠标,触摸事件也不是可信事件,页面可能忽略它们。iOS、Android、HarmonyOS、Web 和小程序按原样显示页面。 diff --git a/docs/roadmap.md b/docs/roadmap.md index 4fab101e9..2be2ddf13 100644 --- a/docs/roadmap.md +++ b/docs/roadmap.md @@ -116,6 +116,7 @@ What NSGo's own issues ask for beyond NSH's releases, each issue where its desig | Task progress on app icons | [#116](https://github.com/nsgo-dev/nsgo/issues/116) | `core.SetTaskProgress` shows, updates and clears a bar beside the badge on the macOS Dock tile, the Windows taskbar button, indeterminate there, and Linux launchers with LauncherEntry (Ubuntu dock, Plasma, Dash to Dock), and clearing it on macOS brings back the plain icon; so far it ran only in `nsgotest` and pure-logic tests, on no Dock, taskbar or launcher (2026-11-15) | | A clip that keeps its own shadows everywhere | [#210](https://github.com/nsgo-dev/nsgo/issues/210) | A view with `Overflow: Hidden` keeps its own outer shadows and outline on Android, drawing them outside the clipped render node, and on Apple for texts, canvases, inputs, web, video and native views, iOS scroll views, and images and scroll views whose corners differ in radius, checked on a device, so `ui.Dialog`'s `Bare` drops its inner clipping view; so far views, images and macOS scroll views do on macOS and iOS (2026-11-16) | | The web views' cookie store | [#387](https://github.com/nsgo-dev/nsgo/issues/387), [#112](https://github.com/nsgo-dev/nsgo/issues/112), [native views](architecture/native-views.md#web-views) | An HttpOnly, Secure cookie `SetWebCookies` writes for `.example.com` goes with a load of `https://example.com/` on a Mac, an iPhone, Windows, Linux and an Android phone, outlives a restart with an expiry and stays out of Incognito views, `WebCookies` lists a sign-in a page made there with every field, by URL and by domain, and after `ClearWebsiteData` a reload finds no cookies, empty `localStorage` and no IndexedDB, all on HTTPS sites rather than a local server; so far macOS's, Linux's (under Xvfb) and Windows' native tests ran it against a local server over HTTP, on 127.0.0.1, with the cookies written for example.test, and the iOS simulator and an Android 15 emulator set, listed and cleared a store without a page (2026-11-19) | +| Muting web pages | [#114](https://github.com/nsgo-dev/nsgo/issues/114) | `WebView.Muted` and `MutedFunc` silence a page's media elements and Web Audio without the page seeing them muted, across navigations, through WebKitGTK's `webkit_web_view_set_is_muted` and WebView2's `put_IsMuted`, with what macOS, iOS and Android can do stated in the field's comment; `UserAgentSuffix` from the same issue is done | | Restricted web history on devices | [#442](https://github.com/nsgo-dev/nsgo/issues/442), [native views](architecture/native-views.md#web-views) | App-owned HTML and data pages retain their body through `Ref.Reload`, `GoBack` and `GoForward` with no page schemes granted, while a new page-made about:/data: navigation remains refused; macOS, Linux and Windows native tests verify bodies, forward history after reloading a previous page and an iframe-reload attempt, and macOS's and Linux's that a step back within the page passes no exemption to the page's next navigation; iOS/Android devices have not run. A page's own history steps, and on Linux and Windows its reloads, get no exemption, as those platforms' public APIs cannot securely attribute them to an app-created entry before navigation; use the Ref commands (2026-11-17) | | Sign in with Apple on devices | [#354](https://github.com/nsgo-dev/nsgo/issues/354), [services](architecture/services.md#sign-in-with-apple) | On an iPhone, an Apple TV and a Mac App Store build signed with the entitlement, the sheet shows, a sign-in returns an identity token whose `nonce` claim is the SHA-256 of the nonce the app gave, a cancel reports cancelled and a revoked credential reads `revoked`; so far it ran in `nsgotest` alone and was built for macOS, iOS and tvOS, showing no sheet anywhere (2026-11-16) | | Sign in with Apple elsewhere | [#354](https://github.com/nsgo-dev/nsgo/issues/354), Sign in with Apple JS, `ASAuthorizationController` on watchOS | A Developer ID macOS build embeds a Developer ID provisioning profile granting the entitlement and signs in; watchOS's SwiftUI host shows the sheet; and Android, Windows, Linux and the web sign in through Apple's JS flow and a redirect back to the app, a separate decision; all report `Env.CanSignInWithApple` false now | @@ -331,6 +332,7 @@ Go apps run in an ArkTS host under ArkWeb, which draws what the engine mounts wi | Frame rate | `performance.md` | A 30-row window scrolls at 60 fps with a batch per frame, measured on the emulator and a phone; a 200-row list scrolls natively at 61 FPS with 0.03 ms of main-thread work a frame and no batch, and a 30-row list committing on each scroll offset runs at 58 FPS with 6.43 ms of core work a commit (p95 13.70, 6 items, 58 commits a second) and no dropped frame, after caching text measurements and writing only the views a batch names; a phone is not measured. A 1000-row `base.List` already windows: 14 rows in 47 nodes at rest and 8 in 30 after a scroll, 63 FPS during a fast swipe (0 dropped, 1.25 ms core a commit) | | Tests on the target | `testing.md` | `nsgo test -target harmonyos` runs an app's tests on the device through hdc, and a test that mounts an app opens it in the page: a press goes to the view the engine's frames put under the point, typing edits the focused field, and a screenshot is the root `FrameNode` as a PNG; `examples/hello` `TestGreets` types a name and presses twice there, and a test that reads pixels saves the picture the tool collects. The app's own timing and a second app in one process are not checked | | Imperative render tree | `cmd/nsgo/harmony/templates/entry/src/main/ets/pages/Index.ets` | `Renderer` mounts one `FrameNode` per view with `typeNode`, so a batch updates the nodes it names and no version counter is left; rich text, canvases and images from bytes use a `BuilderNode`. A scroll's offsets and a field's keyboard input are still checked by hand on a device | +| Web view settings | `internal/platform/harmonyos/mount.go` (`web`) | ArkWeb's `Web` takes a web view's `UserAgent` and `UserAgentSuffix`, injected scripts, headers and the rest of `WebConfig`, as the other targets do; the host is sent only the source's URL and `NoJavaScript` now | | Clipping and the tab bar | `examples/gallery` | The gallery shows every demo with the system's tab bar: `core.TabBar`'s native component and a view's `Overflow: Hidden` have no renderer yet, so the gallery draws its own tab bar here and leaves out DataTable, whose rows draw over the page unclipped, and Shader, which has no view | | Home-screen cards | `cmd/nsgo/harmony/templates/entry/src/main/ets/widget/pages/WidgetCard.ets` | A card's data comes from the app through `formBindingData` and `formProvider.updateForm`, and its look from a card page that draws with ArkUI, since a card has no `Web` view; `widget.Update` now reaches the host, which writes the data and the form ids to files the provider reads, and `onUpdateForm` answers the system's refresh; the app's path, the form extension's registration and a card added to the home screen are checked on the HarmonyOS emulator, whose launcher offers 卡片 on a long press of the app's icon and sends `onAddForm` the form id; the system's timed `onUpdateForm` is still unmeasured | | Inline views in text | [#811](https://github.com/nsgo-dev/nsgo/issues/811) | A text's inline views (`core.TextAttachment`) show in its lines on the gallery's Text page as on Android: the text engine lays the text out with a placeholder of each attachment's size and reports where each went (`core.AttachmentLayout`), and the host draws the same placeholders; so far the views are hidden and their characters are left out of the text | diff --git a/internal/driver/webview.go b/internal/driver/webview.go index 2e9e0e2f8..05f57f42a 100644 --- a/internal/driver/webview.go +++ b/internal/driver/webview.go @@ -138,6 +138,7 @@ type WebConfig struct { InjectedJavaScript string InjectedJavaScriptBeforeContent string UserAgent string + UserAgentSuffix string // Headers are sent with the initial URL request where the platform // supports custom request headers. HTML sources do not make one. Headers map[string]string @@ -170,6 +171,17 @@ type WebConfig struct { Media WebMedia } +// WebUserAgent appends suffix to base with one separating space. +func WebUserAgent(base, suffix string) string { + if suffix == "" { + return base + } + if base == "" { + return suffix + } + return base + " " + suffix +} + // WebMedia is a set of the devices a web view's pages may capture. type WebMedia uint8 diff --git a/internal/driver/webview_test.go b/internal/driver/webview_test.go index f9c31413a..cd79442b1 100644 --- a/internal/driver/webview_test.go +++ b/internal/driver/webview_test.go @@ -27,6 +27,15 @@ func TestWebOrigin(t *testing.T) { } } +func TestWebUserAgent(t *testing.T) { + if got := WebUserAgent("Mozilla/5.0", "Test/1"); got != "Mozilla/5.0 Test/1" { + t.Fatalf("WebUserAgent = %q", got) + } + if got := WebUserAgent("", "Test/1"); got != "Test/1" { + t.Fatalf("empty WebUserAgent = %q", got) + } +} + func TestWebSourceShows(t *testing.T) { for _, c := range []struct { source WebSource diff --git a/internal/platform/android/android.go b/internal/platform/android/android.go index 0c871a11d..bf3229fc7 100644 --- a/internal/platform/android/android.go +++ b/internal/platform/android/android.go @@ -1491,6 +1491,7 @@ func encode(w *writer, b *driver.MountBatch, first bool, requests []uint32, nati // WebNode runs its bridge first, so the app's script can post. w.str(c.InjectedJavaScriptBeforeContent) w.str(c.UserAgent) + w.str(c.UserAgentSuffix) // Android has no back and forward swipes. w.flags(c.NoScroll, c.NoJavaScript, c.Restricted, c.Incognito, c.Media&driver.WebMicrophone != 0, c.Media&driver.WebCamera != 0, c.PinchZoom) w.str(c.Hosts) diff --git a/internal/platform/android/java/dev/oneo/nsgo/WebNode.java b/internal/platform/android/java/dev/oneo/nsgo/WebNode.java index a416cdd96..f197d8119 100644 --- a/internal/platform/android/java/dev/oneo/nsgo/WebNode.java +++ b/internal/platform/android/java/dev/oneo/nsgo/WebNode.java @@ -625,7 +625,7 @@ private void state(int kind, String url, boolean loading) { void configure(DataInputStream in) throws IOException { String src = Protocol.readString(in), html = Protocol.readString(in), baseURL = Protocol.readString(in); String injected = Protocol.readString(in), injectedBefore = Protocol.readString(in); - String userAgent = Protocol.readString(in); + String userAgent = Protocol.readString(in), userAgentSuffix = Protocol.readString(in); int flags = in.readUnsignedByte(); boolean noScroll = Protocol.flag(flags, 0), noJavaScript = Protocol.flag(flags, 1); restricted = Protocol.flag(flags, 2); @@ -669,6 +669,10 @@ void configure(DataInputStream in) throws IOException { // The built-in zoom is the pinch; its on-screen buttons stay hidden. settings.setBuiltInZoomControls(pinchZoom); settings.setDisplayZoomControls(false); + // The suffix goes after the system's default, not the string set before, which may already carry it. + if (!userAgentSuffix.isEmpty()) { + userAgent = (userAgent.isEmpty() ? WebSettings.getDefaultUserAgent(view.getContext()) : userAgent) + " " + userAgentSuffix; + } if (!userAgent.equals(this.userAgent)) { this.userAgent = userAgent; settings.setUserAgentString(userAgent.isEmpty() ? null : userAgent); // null: the default diff --git a/internal/platform/android/runtime/classes.dex b/internal/platform/android/runtime/classes.dex index 5f32df42a..9cac1cbd5 100644 Binary files a/internal/platform/android/runtime/classes.dex and b/internal/platform/android/runtime/classes.dex differ diff --git a/internal/platform/android/runtime/classes.jar b/internal/platform/android/runtime/classes.jar index 32125dc21..1b1f359ef 100644 Binary files a/internal/platform/android/runtime/classes.jar and b/internal/platform/android/runtime/classes.jar differ diff --git a/internal/platform/apple/web.go b/internal/platform/apple/web.go index 4bf2c1eda..111269193 100644 --- a/internal/platform/apple/web.go +++ b/internal/platform/apple/web.go @@ -381,9 +381,10 @@ func (w *Web) Configure(c *driver.WebConfig) { ua = driver.WebMobileUserAgentIPhone } if ua == "" { + // WebKit's own, which ends in the suffix make gave the configuration. w.web.Send(sel("setCustomUserAgent:"), objc.ID(0)) } else { - w.web.Send(sel("setCustomUserAgent:"), NSString(ua)) + w.web.Send(sel("setCustomUserAgent:"), NSString(driver.WebUserAgent(ua, c.UserAgentSuffix))) } w.web.Send(sel("setAllowsBackForwardNavigationGestures:"), c.BackForwardGestures) if runtime.GOOS != "ios" { @@ -402,6 +403,11 @@ func (w *Web) Configure(c *driver.WebConfig) { func (w *Web) make() { loadWebKit() config := objc.ID(Class("WKWebViewConfiguration")).Send(sel("new")) + // WebKit appends the application name to its default user agent after a space, and a view reads it only as it is made; iOS's default name, such as Mobile/15E148, stays before the suffix. + if suffix := w.config.UserAgentSuffix; suffix != "" { + name := GoString(config.Send(sel("applicationNameForUserAgent"))) + config.Send(sel("setApplicationNameForUserAgent:"), NSString(driver.WebUserAgent(name, suffix))) + } if w.config.Incognito { store := objc.ID(Class("WKWebsiteDataStore")).Send(sel("nonPersistentDataStore")) config.Send(sel("setWebsiteDataStore:"), store) diff --git a/internal/platform/linux/web.go b/internal/platform/linux/web.go index 88106e8f3..2f85c3b73 100644 --- a/internal/platform/linux/web.go +++ b/internal/platform/linux/web.go @@ -78,6 +78,7 @@ var ( webkitBackForwardListItemGetURI func(uintptr) uintptr webkitSettingsSetEnableJSMarkup func(uintptr, int32) webkitSettingsSetUserAgent func(uintptr, *byte) + webkitSettingsGetUserAgent func(uintptr) uintptr webkitSettingsSetBackForwardGestures func(uintptr, int32) webkitSettingsSetEnableMediaStream func(uintptr, int32) webkitUserMediaRequestGetType func() uintptr @@ -190,6 +191,7 @@ func bindWebKit(webkit, jsc, soup uintptr) { reg(&webkitBackForwardListItemGetURI, "webkit_back_forward_list_item_get_uri") reg(&webkitSettingsSetEnableJSMarkup, "webkit_settings_set_enable_javascript_markup") reg(&webkitSettingsSetUserAgent, "webkit_settings_set_user_agent") + reg(&webkitSettingsGetUserAgent, "webkit_settings_get_user_agent") reg(&webkitSettingsSetBackForwardGestures, "webkit_settings_set_enable_back_forward_navigation_gestures") reg(&webkitSettingsSetEnableMediaStream, "webkit_settings_set_enable_media_stream") reg(&webkitUserMediaRequestGetType, "webkit_user_media_permission_request_get_type") @@ -386,8 +388,13 @@ func (w *window) configureWeb(v *view, c *driver.WebConfig) { ua = mobileUserAgent } if ua == "" { + // NULL sets WebKitGTK's default, which the suffix then follows. webkitSettingsSetUserAgent(settings, nil) - } else { + if c.UserAgentSuffix != "" { + ua = goString(webkitSettingsGetUserAgent(settings)) + } + } + if ua = driver.WebUserAgent(ua, c.UserAgentSuffix); ua != "" { webkitSettingsSetUserAgent(settings, cstr(ua)) } webkitSettingsSetBackForwardGestures(settings, boolInt(c.BackForwardGestures)) diff --git a/internal/platform/linux/webuseragent_test.go b/internal/platform/linux/webuseragent_test.go new file mode 100644 index 000000000..92d26ebcb --- /dev/null +++ b/internal/platform/linux/webuseragent_test.go @@ -0,0 +1,112 @@ +//go:build linux && !android + +package linux + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strings" + "sync" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// TestWebUserAgentSuffixFollowsTheUserAgent loads a local server's page in a web view with UserAgentSuffix alone, one with UserAgent too and a Mobile one, and each page reports navigator.userAgent back to the server: the request's User-Agent header and the page's must be WebKitGTK's own followed by the suffix, UserAgent followed by it, and Android Chrome's followed by it. WebKit runs in a process of its own test run, as the other web tests do. +func TestWebUserAgentSuffixFollowsTheUserAgent(t *testing.T) { + if testing.Short() { + t.Skip("opens a window") + } + const suffix = "Version/26.0 Safari/605.1.15" + if os.Getenv("NSGO_TEST_WEBKIT_PROCESS") == t.Name() { + userAgentApp(t, suffix) + return + } + var mu sync.Mutex + header, page := map[string]string{}, map[string]string{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := strings.TrimPrefix(r.URL.Path, "/") + if r.Method == http.MethodPost { + body, _ := io.ReadAll(r.Body) + mu.Lock() + page[id] = string(body) + mu.Unlock() + return + } + mu.Lock() + header[id] = r.Header.Get("User-Agent") + mu.Unlock() + w.Header().Set("Content-Type", "text/html") + w.Write([]byte(``)) + })) + defer server.Close() + cmd := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v") + cmd.Env = append(os.Environ(), "NSGO_TEST_WEBKIT_PROCESS="+t.Name(), "NSGO_TEST_SERVER="+server.URL) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if strings.Contains(string(out), "--- SKIP") { + t.Skipf("%s", out) + } + mu.Lock() + defer mu.Unlock() + t.Logf("headers %q, pages %q", header, page) + for _, c := range []struct { + id string + want func(string) bool + }{ + {"plain", func(ua string) bool { + return strings.HasPrefix(ua, "Mozilla/5.0 (") && strings.Contains(ua, "AppleWebKit/") && strings.HasSuffix(ua, " "+suffix) + }}, + {"agent", func(ua string) bool { return ua == "nsgo-test "+suffix }}, + {"mobile", func(ua string) bool { return ua == mobileUserAgent+" "+suffix }}, + } { + if !c.want(header[c.id]) { + t.Errorf("the %s view's request sent User-Agent %q", c.id, header[c.id]) + } + if page[c.id] != header[c.id] { + t.Errorf("the %s view's page sees %q, its request sent %q", c.id, page[c.id], header[c.id]) + } + } +} + +// userAgentApp is TestWebUserAgentSuffixFollowsTheUserAgent's app, which returns once every page has reported. +func userAgentApp(t *testing.T, suffix string) { + if err := openWebKit(); err != nil { + t.Skip(err) + } + server := os.Getenv("NSGO_TEST_SERVER") + var mu sync.Mutex + reported := 0 + app := func(cx *core.Scope) core.Node { + web := func(id, ua string, mobile bool) core.Node { + return core.WebView{Source: core.WebSrc(server + "/" + id), UserAgent: ua, UserAgentSuffix: suffix, Mobile: mobile, + Style: core.Style{Width: driver.Pt(200), Height: driver.Pt(200)}, + OnMessage: func(string) { + mu.Lock() + reported++ + mu.Unlock() + }} + } + return core.View{Style: core.Style{Width: driver.Pt(600), Height: driver.Pt(200), Direction: core.Row}, + Children: []core.Node{web("plain", "", false), web("agent", "nsgo-test", false), web("mobile", "", true)}} + } + startTestWindow(t, app, Options{Title: "nsgo-native-" + t.Name(), Width: 600, Height: 200}) + for deadline := time.Now().Add(20 * time.Second); ; time.Sleep(20 * time.Millisecond) { + mu.Lock() + done := reported == 3 + mu.Unlock() + if done { + return + } + if time.Now().After(deadline) { + t.Fatalf("%d of the 3 pages reported", reported) + } + } +} diff --git a/internal/platform/macos/webuseragent_test.go b/internal/platform/macos/webuseragent_test.go new file mode 100644 index 000000000..bfd31cf87 --- /dev/null +++ b/internal/platform/macos/webuseragent_test.go @@ -0,0 +1,101 @@ +//go:build darwin && !ios + +package macos + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "strings" + "sync" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// TestWebUserAgentSuffixFollowsTheUserAgent loads a local server's page in a web view with UserAgentSuffix alone, one with UserAgent too and a Mobile one, and each page reports navigator.userAgent back to the server: the request's User-Agent header and the page's must be WebKit's own followed by the suffix, UserAgent followed by it, and iPhone Safari's followed by it. Run ends a process's app for good, so the app runs in a process of its own. +func TestWebUserAgentSuffixFollowsTheUserAgent(t *testing.T) { + if testing.Short() { + t.Skip("opens a window") + } + const suffix = "Version/26.0 Safari/605.1.15" + if os.Getenv("NSGO_TEST_WEB_PROCESS") == t.Name() { + userAgentApp(suffix) + return + } + var mu sync.Mutex + header, page := map[string]string{}, map[string]string{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := strings.TrimPrefix(r.URL.Path, "/") + if r.Method == http.MethodPost { + body, _ := io.ReadAll(r.Body) + mu.Lock() + page[id] = string(body) + mu.Unlock() + return + } + mu.Lock() + header[id] = r.Header.Get("User-Agent") + mu.Unlock() + w.Header().Set("Content-Type", "text/html") + w.Write([]byte(``)) + })) + defer server.Close() + cmd := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v") + cmd.Env = append(os.Environ(), "NSGO_TEST_WEB_PROCESS="+t.Name(), "NSGO_TEST_SERVER="+server.URL, "HOME="+t.TempDir()) + if out, err := cmd.CombinedOutput(); err != nil { + t.Fatalf("%v\n%s", err, out) + } + mu.Lock() + defer mu.Unlock() + t.Logf("headers %q, pages %q", header, page) + for _, c := range []struct { + id string + want func(string) bool + }{ + {"plain", func(ua string) bool { + return strings.HasPrefix(ua, "Mozilla/5.0 (Macintosh;") && strings.Contains(ua, "AppleWebKit/") && strings.HasSuffix(ua, " "+suffix) + }}, + {"agent", func(ua string) bool { return ua == "nsgo-test "+suffix }}, + {"mobile", func(ua string) bool { return ua == driver.WebMobileUserAgentIPhone+" "+suffix }}, + } { + if !c.want(header[c.id]) { + t.Errorf("the %s view's request sent User-Agent %q", c.id, header[c.id]) + } + if page[c.id] != header[c.id] { + t.Errorf("the %s view's page sees %q, its request sent %q", c.id, page[c.id], header[c.id]) + } + } +} + +// userAgentApp is TestWebUserAgentSuffixFollowsTheUserAgent's app, which quits once every page has reported. +func userAgentApp(suffix string) { + server := os.Getenv("NSGO_TEST_SERVER") + var mu sync.Mutex + reported := 0 + app := func(cx *core.Scope) core.Node { + web := func(id, ua string, mobile bool) core.Node { + return core.WebView{Source: core.WebSrc(server + "/" + id), UserAgent: ua, UserAgentSuffix: suffix, Mobile: mobile, + Style: core.Style{Width: core.Pt(200), Height: core.Pt(200)}, + OnMessage: func(string) { + mu.Lock() + reported++ + done := reported == 3 + mu.Unlock() + if done { + cx.Quit() + } + }} + } + return core.View{Style: core.Style{Direction: core.Row}, Children: []core.Node{ + web("plain", "", false), web("agent", "nsgo-test", false), web("mobile", "", true), + }} + } + watchdog := time.AfterFunc(30*time.Second, func() { panic("the pages did not report their user agents") }) + defer watchdog.Stop() + onMain(func() { Run(app, Options{Title: "Web user agent", Width: 600, Height: 200}) }) +} diff --git a/internal/platform/windows/web.go b/internal/platform/windows/web.go index d96b35058..9cc81722f 100644 --- a/internal/platform/windows/web.go +++ b/internal/platform/windows/web.go @@ -709,6 +709,7 @@ func (wv *webView) apply() { if ua == "" { ua = wv.userAgent } + ua = driver.WebUserAgent(ua, c.UserAgentSuffix) if s2 := s.query(&iidSettings2); s2 != nil { s2.call(settingsPutUserAgent, uintptr(unsafe.Pointer(wide(ua)))) s2.release() diff --git a/internal/platform/windows/webmobile.go b/internal/platform/windows/webmobile.go index 5f936c3f3..65fdc8434 100644 --- a/internal/platform/windows/webmobile.go +++ b/internal/platform/windows/webmobile.go @@ -39,6 +39,7 @@ func (wv *webView) emulatePhone(c driver.WebConfig) { if ua == "" { ua = mobileUserAgent(wv.userAgent) } + ua = driver.WebUserAgent(ua, c.UserAgentSuffix) major := majorVersion(wv.userAgent) brands := []cdpBrand{{"Chromium", major}, {"Not_A Brand", "24"}} // An empty user agent ends the override, leaving the settings' own. diff --git a/internal/platform/windows/webuseragent_test.go b/internal/platform/windows/webuseragent_test.go new file mode 100644 index 000000000..be3100aeb --- /dev/null +++ b/internal/platform/windows/webuseragent_test.go @@ -0,0 +1,152 @@ +//go:build windows + +package windows + +import ( + "io" + "net/http" + "net/http/httptest" + "os" + "os/exec" + "runtime" + "strings" + "sync" + "testing" + "time" + + "github.com/nsgo-dev/nsgo/core" + "github.com/nsgo-dev/nsgo/internal/driver" +) + +// TestWebUserAgentSuffixFollowsTheUserAgent loads a local server's page in a web view with UserAgentSuffix alone, one with UserAgent too and a Mobile one, and each page reports navigator.userAgent back to the server: the request's User-Agent header and the page's must be WebView2's own followed by the suffix, UserAgent followed by it, and the phone's made of WebView2's followed by it. It runs in a process of its own, with a profile of its own. +func TestWebUserAgentSuffixFollowsTheUserAgent(t *testing.T) { + if testing.Short() { + t.Skip("opens a window") + } + if _, err := findWebView2(); err != nil { + t.Skip(err) + } + const suffix = "Version/26.0 Safari/605.1.15" + if os.Getenv("NSGO_TEST_WEBVIEW2_PROCESS") == t.Name() { + userAgentApp(t, suffix) + return + } + var mu sync.Mutex + header, page := map[string]string{}, map[string]string{} + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + id := strings.TrimPrefix(r.URL.Path, "/") + if r.Method == http.MethodPost { + body, _ := io.ReadAll(r.Body) + mu.Lock() + page[id] = string(body) + mu.Unlock() + return + } + if id == "favicon.ico" { + http.NotFound(w, r) + return + } + mu.Lock() + header[id] = r.Header.Get("User-Agent") + mu.Unlock() + w.Header().Set("Content-Type", "text/html") + w.Write([]byte(``)) + })) + defer server.Close() + // WebView2's processes may hold the profile a while after the test's process ends. + dir, err := os.MkdirTemp("", "nsgo-useragent-webview2-") + if err != nil { + t.Fatal(err) + } + defer func() { + for deadline := time.Now().Add(5 * time.Second); ; time.Sleep(100 * time.Millisecond) { + if err := os.RemoveAll(dir); err == nil { + return + } else if time.Now().After(deadline) { + t.Logf("WebView2 profile cleanup: %v", err) + return + } + } + }() + cmd := exec.Command(os.Args[0], "-test.run=^"+t.Name()+"$", "-test.v") + cmd.Env = append(os.Environ(), "NSGO_TEST_WEBVIEW2_PROCESS="+t.Name(), "NSGO_TEST_SERVER="+server.URL, "APPDATA="+dir, "LOCALAPPDATA="+dir) + out, err := cmd.CombinedOutput() + if err != nil { + t.Fatalf("%v\n%s", err, out) + } + if strings.Contains(string(out), "--- SKIP") { + t.Skipf("%s", out) + } + mu.Lock() + defer mu.Unlock() + t.Logf("headers %q, pages %q", header, page) + plain := header["plain"] + if !strings.HasPrefix(plain, "Mozilla/5.0 (Windows") || !strings.Contains(plain, " Edg/") || !strings.HasSuffix(plain, " "+suffix) { + t.Fatalf("the plain view's request sent User-Agent %q, want WebView2's own followed by %q", plain, suffix) + } + own := strings.TrimSuffix(plain, " "+suffix) + for id, want := range map[string]string{ + "agent": "nsgo-test " + suffix, + "mobile": mobileUserAgent(own) + " " + suffix, + } { + if header[id] != want { + t.Errorf("the %s view's request sent User-Agent %q, want %q", id, header[id], want) + } + } + for _, id := range []string{"plain", "agent", "mobile"} { + if page[id] != header[id] { + t.Errorf("the %s view's page sees %q, its request sent %q", id, page[id], header[id]) + } + } +} + +// userAgentApp is TestWebUserAgentSuffixFollowsTheUserAgent's app, which returns once every page has reported. +func userAgentApp(t *testing.T, suffix string) { + server := os.Getenv("NSGO_TEST_SERVER") + var mu sync.Mutex + reported := map[string]bool{} + title := "nsgo-web-useragent" + app := func(cx *core.Scope) core.Node { + web := func(id, ua string, mobile bool) core.Node { + return core.WebView{Source: core.WebSrc(server + "/" + id), UserAgent: ua, UserAgentSuffix: suffix, Mobile: mobile, + Style: core.Style{Width: driver.Pt(200), Height: driver.Pt(200)}, + OnMessage: func(string) { + mu.Lock() + reported[id] = true + mu.Unlock() + }} + } + return core.View{Style: core.Style{Width: driver.Pt(600), Height: driver.Pt(200), Direction: core.Row}, + Children: []core.Node{web("plain", "", false), web("agent", "nsgo-test", false), web("mobile", "", true)}} + } + done := make(chan struct{}) + go func() { + runtime.LockOSThread() + defer close(done) + Run(app, Options{Title: title, Width: 600, Height: 200}) + }() + hwnd := waitForWindow(t, title, done) + if hwnd == 0 { + return + } + defer func() { + postMessageW.Call(hwnd, wmClose, 0, 0) + select { + case <-done: + case <-time.After(5 * time.Second): + t.Error("the window did not close") + } + }() + // The first start of the browser process can take a while. + for deadline := time.Now().Add(30 * time.Second); ; time.Sleep(20 * time.Millisecond) { + mu.Lock() + n := len(reported) + mu.Unlock() + if n == 3 { + return + } + if time.Now().After(deadline) { + t.Fatalf("%d of the 3 pages reported", n) + } + } +} diff --git a/internal/testhost/testdata/websource/websource_test.go b/internal/testhost/testdata/websource/websource_test.go index 37fe872f6..c786ccdaa 100644 --- a/internal/testhost/testdata/websource/websource_test.go +++ b/internal/testhost/testdata/websource/websource_test.go @@ -2,6 +2,7 @@ package websource_test import ( "slices" + "strings" "sync" "testing" "time" @@ -142,3 +143,56 @@ func TestEmptyWebSourceClearsAPage(t *testing.T) { page.loaded(t, a, `""`, true) } } + +// A web view with UserAgentSuffix alone sends the platform's own user agent followed by the suffix, which on Apple platforms the configuration carries from the view's start. +func TestUserAgentSuffixFollowsThePlatformsOwn(t *testing.T) { + switch nsgotest.Target() { + case "macos", "ios_simulator", "ios", "linux", "windows", "android": + default: + t.Skip("checks a native web view's user agent") + } + const suffix = "Version/26.0 Safari/605.1.15" + var mu sync.Mutex + var scope *core.Scope + var ref core.Ref + loaded := false + a := nsgotest.Start(t, func(cx *core.Scope) core.Node { + scope = cx + return core.WebView{ + Source: core.WebHTML("
agent
", ""), UserAgentSuffix: suffix, Ref: &ref, TestID: "page", + Style: core.Style{Width: core.Pt(240), Height: core.Pt(140)}, + OnLoad: func(core.WebNavigation) { + mu.Lock() + defer mu.Unlock() + loaded = true + }, + } + }, nsgotest.Size(260, 160)) + a.WaitUntil(15*time.Second, func() bool { + mu.Lock() + defer mu.Unlock() + return loaded + }) + var agent string + var evalErr error + var answered bool + scope.Post(func() { + ref.Evaluate("navigator.userAgent", func(result string, err error) { + mu.Lock() + defer mu.Unlock() + agent, evalErr, answered = result, err, true + }) + }) + a.WaitUntil(10*time.Second, func() bool { + mu.Lock() + defer mu.Unlock() + return answered + }) + mu.Lock() + defer mu.Unlock() + t.Logf("navigator.userAgent = %s", agent) + // Evaluate answers in JSON: a quoted string. + if evalErr != nil || !strings.HasPrefix(agent, `"Mozilla/5.0 (`) || !strings.Contains(agent, "AppleWebKit/") || !strings.HasSuffix(agent, " "+suffix+`"`) { + t.Fatalf("navigator.userAgent = %s, %v; want the platform's own followed by %q", agent, evalErr, suffix) + } +} diff --git a/tsx/elements.go b/tsx/elements.go index 508d35e41..dcb835fc4 100644 --- a/tsx/elements.go +++ b/tsx/elements.go @@ -109,6 +109,7 @@ func webViewFace(p *props) core.Node { return p.str("injectedJavaScriptBeforeContentLoaded") }, UserAgent: p.str("userAgent"), + UserAgentSuffix: p.str("userAgentSuffix"), NoScroll: !p.boolOr("scrollable", true), NoJavaScript: !p.boolOr("javaScriptEnabled", true), BackForwardGestures: p.bool("allowsBackForwardNavigationGestures"), diff --git a/tsx/elements_test.go b/tsx/elements_test.go index 1387a9960..53f2d4a24 100644 --- a/tsx/elements_test.go +++ b/tsx/elements_test.go @@ -233,6 +233,29 @@ mount(App);`) } } +// userAgentSuffix reaches the web view's config, and a change makes a new web view with the new suffix, as Apple reads it only as the view is first made. +func TestWebViewUserAgentSuffixFollowsItsProp(t *testing.T) { + app := run(t, `import { mount, signal, Text, View, WebView } from "nsgo"; +function App() { + const suffix = signal("Version/26.0 Safari/605.1.15"); + return