From 1ef20aa89c2cfbae2d03490b909d18b5174aa4da Mon Sep 17 00:00:00 2001 From: sadsac <444361557@qq.com> Date: Mon, 30 Nov 2026 14:04:12 +0800 Subject: [PATCH] fix(windows): deliver WebView messages through the native channel (cherry picked from commit bdd53da7214c8a905021176fd9b0bf0031fff039) --- .github/workflows/ci.yml | 2 + internal/platform/web_bridge_js_test.go | 38 +++++++++++++ internal/platform/web_cuts.go | 3 + .../windows/web_message_windows_test.go | 56 +++++++++++++++++++ internal/platform/windows/web_windows.go | 3 +- internal/platform/windows/webview2_windows.go | 1 + 6 files changed, 102 insertions(+), 1 deletion(-) create mode 100644 internal/platform/web_bridge_js_test.go create mode 100644 internal/platform/windows/web_message_windows_test.go diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cb02f5be8..b8d1ed3cc 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -384,6 +384,8 @@ jobs: run: go test ./internal/platform/windows ./app -run '^Test(FileDialogInitialDirectory|DriverInterceptsOpenDirectory)$' -count=1 -v - name: Native directory watches run: go test ./internal/filewatch -count=1 -timeout=1m + - name: WebView2 host messages + run: go test ./internal/platform/windows -run '^TestWebViewPostsStringsThroughNativeMessages$' -count=1 -timeout=1m - name: Material contracts and controls (WARP) run: go test ./internal/platform/windows ./ui ./components ./headless ./app -run 'Test(Backdrop|WindowBackdrop|OpeningMaximized|Notification|TaskbarCreated|CompositionClear|CompositionFallback|CompositionCreation|CustomBackdrop|AcrylicAccent|LegacyAcrylic|RoundedOutline|Translucent|MonospaceFamilies|FontWeights|(The)?MonoWeights|(The)?InterfaceWeights|EveryListedFamilyResolves|EngineReportsTheFontsUnderline|AlwaysOnTop|SaveDialogCheckbox|FileIcon|NativeStructureABI|ResizePresents|WindowSwapChain|LiveResize|FlipWindowResize|RedrawWaits|ContinuousRedraw|NoOpFrame|SameSize|ZeroSize|ResizeTimer|RedrawQueue|NativeRedrawMessage|CompositionSupersededFrame|DragPreview|QueuedMenuKeysLeaveTerminalCompositionWithItsOwner|MenuKeysPreserveSystemChordsAndShift|TerminalMenuStopsCapturingWhenWindowLosesFocus|DisabledIMEOffersMenuShortcutDuringComposition)' -count=1 -v - name: Offscreen incremental frame pixels diff --git a/internal/platform/web_bridge_js_test.go b/internal/platform/web_bridge_js_test.go new file mode 100644 index 000000000..429f1f32f --- /dev/null +++ b/internal/platform/web_bridge_js_test.go @@ -0,0 +1,38 @@ +//go:build js && wasm + +package platform + +import ( + "syscall/js" + "testing" +) + +func TestWebView2BridgeDeliversNativeMessages(t *testing.T) { + window := js.Global().Get("Object").New() + channel := js.Global().Get("EventTarget").New() + window.Set("chrome", map[string]any{"webview": channel}) + inject := js.Global().Get("Function").New("window", WebBridgeMainFrameOnlyScript) + window.Set("top", js.Global()) + inject.Invoke(window) + if !window.Get("viva").IsUndefined() { + t.Fatal("subframe received the main-frame bridge") + } + window.Set("top", window) + inject.Invoke(window) + inject.Invoke(window) + + var received []string + handler := js.FuncOf(func(_ js.Value, args []js.Value) any { + received = append(received, args[0].Get("data").String()) + return nil + }) + defer handler.Release() + window.Get("viva").Set("onmessage", handler) + for i, want := range []string{"", "line\n引号\"\x00"} { + event := js.Global().Get("MessageEvent").New("message", map[string]any{"data": want}) + channel.Call("dispatchEvent", event) + if len(received) != i+1 || received[i] != want { + t.Fatalf("message %d: received %q, want one delivery of %q", i, received, want) + } + } +} diff --git a/internal/platform/web_cuts.go b/internal/platform/web_cuts.go index 1ef97d376..0ceddbfa5 100644 --- a/internal/platform/web_cuts.go +++ b/internal/platform/web_cuts.go @@ -101,6 +101,9 @@ const WebBridgeScript = `(function () { }; var viva = { onmessage: null, postMessage: send, deliver: function (text) { if (typeof viva.onmessage === 'function') viva.onmessage({ data: text }); } }; + if (window.chrome && window.chrome.webview) { + window.chrome.webview.addEventListener('message', function (event) { viva.deliver(event.data); }); + } Object.defineProperty(window, 'viva', { value: viva }); })();` diff --git a/internal/platform/windows/web_message_windows_test.go b/internal/platform/windows/web_message_windows_test.go new file mode 100644 index 000000000..576f42b9c --- /dev/null +++ b/internal/platform/windows/web_message_windows_test.go @@ -0,0 +1,56 @@ +package windows + +import ( + "encoding/json" + "runtime" + "slices" + "strings" + "syscall" + "testing" + "unsafe" + + "golang.org/x/sys/windows" +) + +func TestWebViewPostsStringsThroughNativeMessages(t *testing.T) { + type receiver struct { + table *[33]uintptr + messages []string + } + var table [33]uintptr + // ICoreWebView2::PostWebMessageAsJson receives one NUL-terminated JSON value. + table[32] = syscall.NewCallback(func(this, data uintptr) uintptr { + r := (*receiver)(pointer(this)) + r.messages = append(r.messages, windows.UTF16PtrToString((*uint16)(pointer(data)))) + return 0 + }) + // Accept ExecuteScript so a regression reports the missing messages. + table[29] = syscall.NewCallback(func(_, _, _ uintptr) uintptr { return 0 }) + r := receiver{table: &table} + var pin runtime.Pinner + pin.Pin(&r) + defer pin.Unpin() + + page := windowsWeb{} + want := []string{"", "\"\\\n中文\x00", strings.Repeat("ab", 64<<10)} + for _, text := range want { + page.PostMessage(text) + } + page.view = uintptr(unsafe.Pointer(&r)) + for _, action := range page.queued { + action() + } + page.closed = true + page.PostMessage("late") + var got []string + for _, raw := range r.messages { + var text string + if err := json.Unmarshal([]byte(raw), &text); err != nil { + t.Fatal(err) + } + got = append(got, text) + } + if !slices.Equal(got, want) { + t.Fatalf("native messages differ in count, order or contents (got %d, want %d)", len(got), len(want)) + } +} diff --git a/internal/platform/windows/web_windows.go b/internal/platform/windows/web_windows.go index f4ac42150..cedf3956f 100644 --- a/internal/platform/windows/web_windows.go +++ b/internal/platform/windows/web_windows.go @@ -766,7 +766,8 @@ func (page *windowsWeb) PostMessage(text string) { if err != nil { return } - page.Eval("window.viva.deliver(" + string(encoded) + ");") + // A JSON string preserves embedded NULs across WebView2's NUL-terminated input. + page.do(func() { comCall1(page.view, viewPostWebMessageAsJSON, uintptr(unsafe.Pointer(wide(string(encoded))))) }) } func (page *windowsWeb) Focus() { diff --git a/internal/platform/windows/webview2_windows.go b/internal/platform/windows/webview2_windows.go index b2a9a5ad0..f28533ac4 100644 --- a/internal/platform/windows/webview2_windows.go +++ b/internal/platform/windows/webview2_windows.go @@ -406,6 +406,7 @@ const ( viewAddScriptOnCreate = 27 viewExecuteScript = 29 viewReload = 31 + viewPostWebMessageAsJSON = 32 viewAddMessageReceived = 34 viewGoBack = 40 viewGoForward = 41