From 86952a32c198353de48f28baa493ef0bbba6e8ca Mon Sep 17 00:00:00 2001 From: Oleg Date: Mon, 16 Nov 2026 22:33:02 -0500 Subject: [PATCH] feat: open owned child windows from the host window.open and window.openChild stay on the caller's origin, connect as a new FDC3 instance of the parent's app, and close with the window that owns them. Co-authored-by: Cursor --- src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs | 19 ++ src/Bermuda.IpcContract/IpcContract.cs | 5 + src/Bermuda.IpcContract/IpcModels.cs | 17 ++ src/Bermuda.Web/e2e/host-api.spec.ts | 255 +++++++++++++++++ src/Bermuda.Web/src/bridge/index.ts | 11 + .../src/ipc/__generated__/ipc.d.ts | 9 + src/Bermuda/HostBridge.cs | 11 +- src/Bermuda/IWindowController.cs | 9 +- src/Bermuda/MainWindow.xaml.cs | 265 +++++++++++++++++- 9 files changed, 581 insertions(+), 20 deletions(-) diff --git a/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs b/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs index cef6337..36331dc 100644 --- a/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs +++ b/src/Bermuda.Fdc3.Tests/IpcDispatchTests.cs @@ -15,6 +15,7 @@ public class IpcDispatchTests [Theory] [InlineData("ping", typeof(IHostCommands))] + [InlineData("window.openChild", typeof(IWindowCommands))] [InlineData("fdc3.getInfo", typeof(IFdc3Commands))] [InlineData("fdc3.raiseIntent", typeof(IFdc3Commands))] // "Async" suffix dropped [InlineData("fdc3.getIntentResult", typeof(IFdc3Commands))] @@ -33,6 +34,17 @@ public void Every_fdc3_command_is_discovered() Assert.Equal(typeof(IFdc3Commands).GetMethods().Length, discovered); } + [Fact] + public async Task Window_openChild_binds_url_width_and_height() + { + var window = new RecordingWindow(); + + var result = await Invoke(window, "window.openChild", """{ "url": "/child", "width": 640, "height": 480 }"""); + + Assert.Null(result); + Assert.Equal(new OpenChildRequest("/child", 640, 480), window.Last); + } + [Fact] public async Task CamelCase_payloads_bind_to_typed_parameters() { @@ -82,6 +94,13 @@ public async Task Command_errors_propagate_unwrapped() Assert.Equal(Fdc3Errors.NoChannelFound, error.Message); } + private sealed class RecordingWindow : IWindowCommands + { + public OpenChildRequest? Last { get; private set; } + + public void OpenChild(OpenChildRequest request) => Last = request; + } + private static Task Invoke(object target, string name, string? payload) => IpcContract.IpcContract.Find(name)!.InvokeAsync( target, diff --git a/src/Bermuda.IpcContract/IpcContract.cs b/src/Bermuda.IpcContract/IpcContract.cs index eb469fb..321d968 100644 --- a/src/Bermuda.IpcContract/IpcContract.cs +++ b/src/Bermuda.IpcContract/IpcContract.cs @@ -44,6 +44,11 @@ public static string CommandName(string prefix, string methodName) /// Thrown when an invoke() payload doesn't bind to the command's parameter. public sealed class IpcInvalidPayloadException() : Exception("InvalidArguments"); +/// +/// A command refused its input. The message is safe to return to the page as { error }. +/// +public sealed class IpcRejectedException(string message) : Exception(message); + /// One method on an interface. public sealed record IpcCommand(string Name, Type Interface, MethodInfo Method) { diff --git a/src/Bermuda.IpcContract/IpcModels.cs b/src/Bermuda.IpcContract/IpcModels.cs index ec54c20..ae19f3a 100644 --- a/src/Bermuda.IpcContract/IpcModels.cs +++ b/src/Bermuda.IpcContract/IpcModels.cs @@ -44,6 +44,23 @@ public sealed record HostResponse(string Id, object? Result); [IpcType] public sealed record WindowBounds(int Left, int Top, int Width, int Height); +/// +/// Input to window.openChild. Url is absolute or relative to the calling page +/// and must be same-origin; Width and Height are the child window's outer size. +/// +public sealed record OpenChildRequest(string Url, int Width, int Height); + +/// +/// Commands for the page's own host window (window.*). Implemented by +/// MainWindow (see IWindowController). +/// +[IpcCommands("window")] +public interface IWindowCommands +{ + /// Opens a same-origin child window owned by this one. A cross-origin URL is refused. + void OpenChild(OpenChildRequest request); +} + /// /// Shape returned by the frontend's bermudaHost.window.getState(), which /// builds it by combining several WindowScriptHost (windowController) diff --git a/src/Bermuda.Web/e2e/host-api.spec.ts b/src/Bermuda.Web/e2e/host-api.spec.ts index bec14f8..2bc7346 100644 --- a/src/Bermuda.Web/e2e/host-api.spec.ts +++ b/src/Bermuda.Web/e2e/host-api.spec.ts @@ -1,4 +1,5 @@ import { readFileSync } from 'node:fs' +import type { DesktopAgent } from '@finos/fdc3-standard' import type { Page } from '@playwright/test' import { expect, test } from './fixtures' @@ -296,3 +297,257 @@ test.describe('taskbar overlay badge', () => { expect(clearAfterSet.ok).toBe(true) }) }) + +async function closeHostPage(popup: Page) { + if (popup.isClosed()) return + const closed = popup.waitForEvent('close') + await popup.evaluate(() => window.chrome.webview.hostObjects.windowController.Close()).catch(() => {}) + await closed +} + +type CdpTarget = { url?: string; webSocketDebuggerUrl?: string } + +function cdpPort() { + return process.env.CDP_PORT ?? '9222' +} + +async function frameText(data: unknown): Promise { + if (typeof data === 'string') return data + if (data instanceof Blob) return data.text() + if (data instanceof ArrayBuffer) return new TextDecoder().decode(data) + return String(data) +} + +async function listTargets(): Promise { + return (await fetch(`http://127.0.0.1:${cdpPort()}/json`).then((response) => response.json())) as CdpTarget[] +} + +/** + * window.open's WebView2 target never becomes a Playwright page on the opener's CDP connection + * (that connection only sees a blank target that closes). Drive the probe through its own + * target websocket instead. + */ +class ProbeSession { + private nextId = 0 + private readonly pending = new Map void; reject: (error: Error) => void }>() + + private constructor(private readonly ws: WebSocket) { + ws.addEventListener('message', (event) => { + void frameText(event.data).then((text) => { + const message = JSON.parse(text) as { + id?: number + error?: { message?: string } + result?: { + result?: { value?: unknown } + exceptionDetails?: { text?: string; exception?: { description?: string } } + } + } + if (message.id === undefined) return + const waiter = this.pending.get(message.id) + if (!waiter) return + this.pending.delete(message.id) + const details = message.result?.exceptionDetails + if (message.error) waiter.reject(new Error(message.error.message ?? 'cdp error')) + else if (details) waiter.reject(new Error(details.exception?.description ?? details.text ?? 'evaluate failed')) + else waiter.resolve(message.result?.result?.value) + }) + }) + } + + static async open(urlFragment: string): Promise { + const deadline = Date.now() + 15_000 + let socketUrl: string | undefined + while (Date.now() < deadline) { + socketUrl = (await listTargets()).find((target) => target.url?.includes(urlFragment))?.webSocketDebuggerUrl + if (socketUrl) break + await new Promise((resolve) => setTimeout(resolve, 200)) + } + if (!socketUrl) throw new Error('child window did not load') + + const ws = new WebSocket(socketUrl) + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('cdp websocket timed out')), 5_000) + ws.addEventListener( + 'open', + () => { + clearTimeout(timer) + resolve() + }, + { once: true }, + ) + ws.addEventListener( + 'error', + () => { + clearTimeout(timer) + reject(new Error('cdp websocket failed')) + }, + { once: true }, + ) + }) + return new ProbeSession(ws) + } + + evaluate(expression: string): Promise { + const id = ++this.nextId + const result = new Promise((resolve, reject) => { + const timer = setTimeout(() => { + this.pending.delete(id) + reject(new Error('cdp evaluate timed out')) + }, 5_000) + this.pending.set(id, { + resolve: (value) => { + clearTimeout(timer) + resolve(value as T) + }, + reject: (error) => { + clearTimeout(timer) + reject(error) + }, + }) + }) + this.ws.send( + JSON.stringify({ + id, + method: 'Runtime.evaluate', + params: { expression, awaitPromise: true, returnByValue: true }, + }), + ) + return result + } + + /** window.close() is handled by the host. The socket dying as the window goes away is success. */ + async close() { + await this.evaluate('window.close()').catch(() => {}) + this.ws.close() + } + + async gone(urlFragment: string) { + const deadline = Date.now() + 10_000 + while (Date.now() < deadline) { + if (!(await listTargets()).some((target) => target.url?.includes(urlFragment))) return + await new Promise((resolve) => setTimeout(resolve, 200)) + } + throw new Error('child window stayed open') + } +} + +test.describe('child windows', () => { + test('openChild opens a sized same-origin window as a new instance of this app', async ({ page }) => { + const parent = await page.evaluate(async () => { + const metadata = (await (window.fdc3 as DesktopAgent).getInfo()).appMetadata + return { appId: metadata.appId, instanceId: metadata.instanceId } + }) + + let child: Page | undefined + try { + ;[child] = await Promise.all([ + page.context().waitForEvent('page'), + inPage(page, "await bermudaHost.window.openChild({ url: '/fdc3-probe.html', width: 720, height: 500 })"), + ]) + await expect(child.locator('#status')).toHaveText('fdc3 ready') + const info = await child.evaluate(async () => { + const metadata = (await (window.fdc3 as DesktopAgent).getInfo()).appMetadata + const controller = window.chrome.webview.hostObjects.windowController + return { + appId: metadata.appId, + instanceId: metadata.instanceId, + width: await controller.Width, + height: await controller.Height, + // openChild navigates the child itself, so there is no window.opener. window.open covers that. + hasOpener: window.opener !== null, + } + }) + expect(info.appId).toBe(parent.appId) + expect(info.instanceId).toBeTruthy() + expect(info.instanceId).not.toBe(parent.instanceId) + expect(info.width).toBe(720) + expect(info.height).toBe(500) + expect(info.hasOpener).toBe(false) + } finally { + if (child) await closeHostPage(child) + } + }) + + test('openChild rejects a cross-origin url', async ({ page }) => { + const before = page.context().pages().length + const crossOrigin = await attempt( + page, + "bermudaHost.window.openChild({ url: 'https://example.com/', width: 400, height: 300 })", + ) + const scriptUrl = await attempt( + page, + "bermudaHost.window.openChild({ url: 'javascript:alert(1)', width: 400, height: 300 })", + ) + + expect(crossOrigin.ok).toBe(false) + expect(scriptUrl.ok).toBe(false) + if (!crossOrigin.ok) expect(crossOrigin.message).toMatch(/same-origin/i) + expect(page.context().pages().length).toBe(before) + }) + + test('window.open stays same-origin and keeps window.opener', async ({ page }) => { + test.setTimeout(60_000) + const before = page.context().pages().length + await page.evaluate(() => { + window.open('https://example.com/') + }) + expect(page.context().pages().length).toBe(before) + + let child: ProbeSession | undefined + try { + const probe = ProbeSession.open('via=open') + await page.evaluate(() => { + window.open(`${location.origin}/fdc3-probe.html?via=open`, '_blank', 'width=640,height=480') + }) + child = await probe + await expect + .poll(() => child?.evaluate(`document.getElementById('status')?.textContent ?? null`), { + timeout: 10_000, + }) + .toBe('fdc3 ready') + const openerHref = await child.evaluate(`window.opener?.location.href ?? null`) + expect(openerHref).toBe(page.url()) + // width/height on window.open size the WPF window. The viewport is that size minus the + // frame, and it stays under the 800x600 default used when the features omit a size. + const box = await child.evaluate<{ w: number; h: number }>(`({ w: window.innerWidth, h: window.innerHeight })`) + expect(box.w).toBeGreaterThan(500) + expect(box.w).toBeLessThanOrEqual(640) + expect(box.h).toBeGreaterThan(360) + expect(box.h).toBeLessThanOrEqual(480) + } finally { + await child?.close() + } + }) + + test('a child window closes with the window that owns it', async ({ page }) => { + test.setTimeout(60_000) + let child: Page | undefined + let grandchild: ProbeSession | undefined + try { + ;[child] = await Promise.all([ + page.context().waitForEvent('page'), + inPage(page, "await bermudaHost.window.openChild({ url: '/fdc3-probe.html', width: 720, height: 520 })"), + ]) + await expect(child.locator('#status')).toHaveText('fdc3 ready') + const probe = ProbeSession.open('via=grandchild') + await child.evaluate(() => { + window.open(`${location.origin}/fdc3-probe.html?via=grandchild`, '_blank', 'width=500,height=400') + }) + grandchild = await probe + await expect + .poll(() => grandchild?.evaluate(`document.getElementById('status')?.textContent ?? null`), { + timeout: 10_000, + }) + .toBe('fdc3 ready') + + const childClosed = child.waitForEvent('close') + await child.evaluate(() => window.chrome.webview.hostObjects.windowController.Close()).catch(() => {}) + await childClosed + await grandchild.gone('via=grandchild') + grandchild = undefined + } finally { + await grandchild?.close() + if (child) await closeHostPage(child) + } + }) +}) diff --git a/src/Bermuda.Web/src/bridge/index.ts b/src/Bermuda.Web/src/bridge/index.ts index f81e61a..f9f9d34 100644 --- a/src/Bermuda.Web/src/bridge/index.ts +++ b/src/Bermuda.Web/src/bridge/index.ts @@ -6,6 +6,7 @@ import type { ShowNotificationResult, SimulateNotificationActivationRequest, SimulateNotificationActivationResult, + OpenChildRequest, TaskbarProgressState, UpdateApplyResult, UpdateCheckResult, @@ -19,6 +20,7 @@ export type { ShowNotificationResult, SimulateNotificationActivationRequest, SimulateNotificationActivationResult, + OpenChildRequest, TaskbarProgressState, UpdateApplyResult, UpdateCheckResult, @@ -92,6 +94,15 @@ const windowApi = { setOverlay: (iconPng: string, description = '') => windowController().SetOverlayIcon(iconPng, description), /** Sets the taskbar progress bar's state ('none' hides it). */ setProgressState: (state: TaskbarProgressState) => windowController().SetProgressState(state), + /** + * Opens a child window owned by this one (it closes with this window). `url` is absolute or + * relative to this page and must be same-origin; `width` and `height` are the outer window size. + * A cross-origin url rejects. The child joins FDC3 as a new instance of this window's app. + */ + openChild: async (request: OpenChildRequest): Promise => { + const result = await invoke<{ error?: string } | null>('window.openChild', request) + if (result?.error) throw new Error(result.error) + }, } as const export type WindowApi = typeof windowApi diff --git a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts index ca23371..1ae69f3 100644 --- a/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts +++ b/src/Bermuda.Web/src/ipc/__generated__/ipc.d.ts @@ -187,6 +187,12 @@ export interface NotificationButton { label: string; } +export interface OpenChildRequest { + height: number; + url: string; + width: number; +} + export interface PingResult { pong: boolean; } @@ -311,6 +317,9 @@ export interface IpcMethods { sendIntentResult: (payload: Fdc3SendIntentResultRequest, ) => Promise; unsubscribe: (payload: Fdc3ListenerIdRequest, ) => Promise; }; + window: { + openChild: (payload: OpenChildRequest, ) => Promise; + }; } export interface IpcHostObjects { diff --git a/src/Bermuda/HostBridge.cs b/src/Bermuda/HostBridge.cs index 887d7d8..0947d25 100644 --- a/src/Bermuda/HostBridge.cs +++ b/src/Bermuda/HostBridge.cs @@ -17,10 +17,11 @@ namespace Bermuda; /// This window's current FDC3 connection, read per call because a page reload /// reconnects as a new instance (see MainWindow.OnContentLoading). /// +/// This window, for window.* commands such as window.openChild. /// Enables dev/test-only commands (MainWindow: when CDP_PORT is set). [ClassInterface(ClassInterfaceType.AutoDual)] [ComVisible(true)] -public class HostBridge(Func fdc3, bool testHooks = false) : IHostCommands +public class HostBridge(Func fdc3, IWindowCommands window, bool testHooks = false) : IHostCommands { /// Web preset (camelCase, case-insensitive) with enums as camelCase strings, matching the generated TS unions. public static JsonSerializerOptions PayloadJson { get; } = new(JsonSerializerDefaults.Web) @@ -70,11 +71,12 @@ public SimulateNotificationActivationResult SimulateNotificationActivation(Simul // A missing payload is reported in these commands' normal result shape. return result; } - catch (Exception ex) when (ex is Fdc3Exception or IpcInvalidPayloadException) + catch (Exception ex) when (ex is Fdc3Exception or IpcInvalidPayloadException or IpcRejectedException) { // Fdc3Exception messages are the standard FDC3 error strings (and - // IpcInvalidPayloadException's is "InvalidArguments"), which the - // frontend's window.fdc3 rejects with as-is. + // IpcInvalidPayloadException's is "InvalidArguments"; IpcRejectedException + // carries a short refusal such as a cross-origin child URL). The page + // rejects with the message as-is. return new { error = ex.Message }; } catch (Exception) @@ -87,5 +89,6 @@ public SimulateNotificationActivationResult SimulateNotificationActivation(Simul private object TargetFor(Type commands) => commands == typeof(IFdc3Commands) ? fdc3() : commands == typeof(IHostCommands) ? this + : commands == typeof(IWindowCommands) ? window : throw new InvalidOperationException($"No handler for {commands.Name}."); } diff --git a/src/Bermuda/IWindowController.cs b/src/Bermuda/IWindowController.cs index 56acb07..07388c4 100644 --- a/src/Bermuda/IWindowController.cs +++ b/src/Bermuda/IWindowController.cs @@ -1,4 +1,4 @@ -using System.Windows; +using Bermuda.IpcContract; namespace Bermuda; @@ -59,4 +59,11 @@ public interface IWindowController /// Sets the taskbar progress value. Clamped to 0.0–1.0; ignored while the state is "none" or "indeterminate". void SetProgressValue(double value); + + /// + /// Opens a child window owned by this one, sized from . + /// The URL must be same-origin with this window; otherwise throws . + /// The child connects to FDC3 as a new instance of this window's app and closes when this window closes. + /// + void OpenChild(OpenChildRequest request); } diff --git a/src/Bermuda/MainWindow.xaml.cs b/src/Bermuda/MainWindow.xaml.cs index 8adcf38..b47cd82 100644 --- a/src/Bermuda/MainWindow.xaml.cs +++ b/src/Bermuda/MainWindow.xaml.cs @@ -13,7 +13,7 @@ namespace Bermuda; -public partial class MainWindow : Window, IWindowController, IFdc3AppSink +public partial class MainWindow : Window, IWindowController, IWindowCommands, IFdc3AppSink { // The web side speaks camelCase (the generated TS shapes in // src/ipc/__generated__/ipc.d.ts); System.Text.Json's default is to keep @@ -28,6 +28,7 @@ public partial class MainWindow : Window, IWindowController, IFdc3AppSink // to repeat the exact same options anyway, e.g. the CDP port. private static Task? _environment; + private readonly IConfiguration _configuration; private readonly HostBridge _bridge; private readonly DesktopAgent _fdc3; private readonly string _fdc3AppId; @@ -36,6 +37,24 @@ public partial class MainWindow : Window, IWindowController, IFdc3AppSink private readonly int _cdpPort; private readonly bool _clientTitleBar; + // False when this window exists only to satisfy NewWindowRequested: WebView2 navigates + // it (so window.opener is wired) and we must not navigate it ourselves. + private readonly bool _navigateOnLoad; + + // One initialization, shared by OnLoaded and by a parent waiting on the NewWindowRequested deferral. + private Task? _coreWebView; + + // Set before Show when this window exists to satisfy NewWindowRequested. Invoked on the + // init stack, before that task's awaiters resume, so NewWindow is set while the + // CoreWebView2 is still unnavigated (WebView2 rejects one that has already navigated). + private Action? _assignNewWindow; + + private bool _coreEventsWired; + + // window.open without a size, and openChild when a dimension is missing or not positive. + private const int DefaultChildWidth = 800; + private const int DefaultChildHeight = 600; + // Resize border width and caption strip height used in client title bar mode. private const double ClientResizeBorder = 3; private const double ClientCaptionHeight = 40; @@ -59,9 +78,12 @@ public partial class MainWindow : Window, IWindowController, IFdc3AppSink /// The App Directory appId this window's page runs as. /// Set when FDC3 launched this window; the agent is waiting on this id. /// Overrides WEB_URL (FDC3-launched windows load their App Directory URL). - public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3AppId, string? fdc3InstanceId = null, string? url = null) + /// False for a NewWindowRequested child: WebView2 navigates it after the deferral. + public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3AppId, string? fdc3InstanceId = null, string? url = null, bool navigateOnLoad = true) { InitializeComponent(); + _configuration = configuration; + _navigateOnLoad = navigateOnLoad; _fdc3 = fdc3; _fdc3AppId = fdc3AppId; _fdc3LaunchInstanceId = fdc3InstanceId; @@ -70,6 +92,7 @@ public MainWindow(IConfiguration configuration, DesktopAgent fdc3, string fdc3Ap // A remote debugging port already means "dev/test run"; test-only commands ride on that. _bridge = new HostBridge( () => _fdc3Connection ?? throw new InvalidOperationException("FDC3 not connected yet."), + this, testHooks: _cdpPort > 0); // TITLE_BAR=client (default) lets the web app draw the title bar; TITLE_BAR=native @@ -192,24 +215,88 @@ private async void OnLoaded(object sender, RoutedEventArgs e) DwmSetWindowAttribute(hwnd, 33 /* DWMWA_WINDOW_CORNER_PREFERENCE */, ref round, sizeof(int)); } + try + { + await EnsureCoreWebViewAsync(); + } + catch (Exception ex) + { + // A child window's init failure must not take the process down; the opener sees no window. + System.Diagnostics.Debug.WriteLine($"WebView2 failed to start: {ex}"); + } + } + + /// + /// Creates this window's WebView2 once. A parent opening this window from + /// NewWindowRequested awaits the same task starts, + /// then hands the to the deferral so window.opener works. + /// + internal Task EnsureCoreWebViewAsync() => _coreWebView ??= InitializeCoreWebViewAsync(); + + /// + /// Called by the parent before this window is shown, when it is the target of + /// NewWindowRequested. Invoked once the core exists and its document-created + /// script is registered, while the opener's deferral is still open. + /// + internal void WhenCoreReady(Action assign) => _assignNewWindow = assign; + + private async Task InitializeCoreWebViewAsync() + { + // The script has to be registered before this core is handed to NewWindowRequested. + // WebView2 snapshots the document-created scripts when it accepts NewWindow, so a + // registration after that assignment misses the page window.open navigates to. + var preload = await LoadFdc3PreloadAsync(); + await _webView.EnsureCoreWebView2Async(await GetEnvironmentAsync()); - if (_closed) return; + if (_closed) throw new InvalidOperationException("Window closed before its WebView2 was ready."); + var core = _webView.CoreWebView2; #if !DEBUG - _webView.CoreWebView2.Settings.AreDefaultContextMenusEnabled = false; - _webView.CoreWebView2.Settings.AreDevToolsEnabled = false; + core.Settings.AreDefaultContextMenusEnabled = false; + core.Settings.AreDevToolsEnabled = false; #endif - // window.fdc3 for every page, whatever app it is: runs before the page's own scripts. - if (File.Exists(Fdc3PreloadPath)) - await _webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync(await File.ReadAllTextAsync(Fdc3PreloadPath)); - if (_closed) return; + if (preload is not null) + await core.AddScriptToExecuteOnDocumentCreatedAsync(preload); + if (_closed) throw new InvalidOperationException("Window closed before its WebView2 was ready."); + + WireCoreEvents(core); + if (_navigateOnLoad) + { + ExposeHostObject(); + core.Navigate(_webUrl); + } + else + { + // Assign while the opener's deferral is still open so window.opener is + // this core. The host object is registered after the deferral completes, + // once WebView2 has finished initializing the new web content. + _assignNewWindow?.Invoke(core); + } + + return core; + } - _webView.CoreWebView2.AddHostObjectToScript("windowController", new WindowScriptHost(this)); - _webView.CoreWebView2.WebMessageReceived += OnWebMessageReceived; - _webView.CoreWebView2.NavigationStarting += OnNavigationStarting; - _webView.CoreWebView2.ContentLoading += OnContentLoading; - _webView.CoreWebView2.Navigate(_webUrl); + private void WireCoreEvents(CoreWebView2 core) + { + if (_coreEventsWired) return; + _coreEventsWired = true; + core.WebMessageReceived += OnWebMessageReceived; + core.NavigationStarting += OnNavigationStarting; + core.ContentLoading += OnContentLoading; + core.NewWindowRequested += OnNewWindowRequested; + // window.close() from a page opened with window.open. CloseWindow honors the tray rule. + core.WindowCloseRequested += (_, _) => CloseWindow(); + } + + private static string? _fdc3Preload; + + private static async Task LoadFdc3PreloadAsync() + { + if (_fdc3Preload is not null) return _fdc3Preload; + if (!File.Exists(Fdc3PreloadPath)) return null; + var text = await File.ReadAllTextAsync(Fdc3PreloadPath); + return _fdc3Preload ??= text; } private static string Fdc3PreloadPath { get; } = Path.Combine(AppContext.BaseDirectory, "Preload", "fdc3-preload.js"); @@ -220,18 +307,156 @@ private string Origin(string? uri) => private bool IsTrustedOrigin(string? uri) => string.Equals(Origin(uri), Origin(_webUrl), StringComparison.OrdinalIgnoreCase); + // True once a trusted document has started loading. Until then the implicit about:blank + // WebView2 creates must be left alone: cancelling it drops a NewWindowRequested child. + private bool _acceptedNavigation; + // Only this window's own origin may be shown: anything else would be // connected to the agent (and the host bridge) under this window's appId. + // Child windows use the same rule (their _webUrl is already on this origin). private void OnNavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e) { - if (!IsTrustedOrigin(e.Uri)) e.Cancel = true; + if (IsInitialBlank(e.Uri) && !_acceptedNavigation) + return; + + if (!IsTrustedOrigin(e.Uri)) + { + e.Cancel = true; + return; + } + + _acceptedNavigation = true; } + private static bool IsInitialBlank(string? uri) => + string.IsNullOrEmpty(uri) || string.Equals(uri, "about:blank", StringComparison.OrdinalIgnoreCase); + + // window.open / target=_blank. The deferral keeps the caller's script waiting until + // NewWindow is set, which is what makes the return value (and window.opener) the child. + private async void OnNewWindowRequested(object? sender, CoreWebView2NewWindowRequestedEventArgs e) + { + // Handled with no NewWindow blocks the default popup, including a cross-origin one. + e.Handled = true; + var accepted = TryResolveSameOrigin(e.Uri, out var target); + if (_closed || !accepted) return; + + MainWindow? child = null; + using (e.GetDeferral()) + { + try + { + var features = e.WindowFeatures; + var width = features is { HasSize: true, Width: > 0 } ? (int)features.Width : DefaultChildWidth; + var height = features is { HasSize: true, Height: > 0 } ? (int)features.Height : DefaultChildHeight; + double? left = features is { HasPosition: true } ? (double)features.Left : null; + double? top = features is { HasPosition: true } ? (double)features.Top : null; + child = ShowOwnedChild( + target.AbsoluteUri, + width, + height, + navigateOnLoad: false, + left, + top, + onCoreReady: core => e.NewWindow = core); + await child.EnsureCoreWebViewAsync(); + if (e.NewWindow is null) + throw new InvalidOperationException("Child CoreWebView2 was not assigned to NewWindow."); + } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Child window failed to open: {ex}"); + // CloseWindow defers the close: this handler is still inside the parent's WebView2 callback. + try { child?.CloseWindow(); } catch { /* already closing */ } + child = null; + } + } + + // Deferral is complete, so the child's web content is initialized. + try { child?.ExposeHostObject(); } + catch (Exception ex) + { + System.Diagnostics.Debug.WriteLine($"Child window failed to open: {ex}"); + try { child?.CloseWindow(); } catch { /* already closing */ } + } + } + + /// + /// Resolves against this page and accepts it only when the result is an + /// http(s) URL on this window's origin — the same trust check as . + /// + private bool TryResolveSameOrigin(string? url, out Uri resolved) + { + resolved = null!; + if (string.IsNullOrWhiteSpace(url)) return false; + + var baseText = _webView.CoreWebView2?.Source; + if (!IsTrustedOrigin(baseText) || !Uri.TryCreate(baseText, UriKind.Absolute, out var baseUri)) + { + if (!Uri.TryCreate(_webUrl, UriKind.Absolute, out baseUri)) return false; + } + + if (!Uri.TryCreate(baseUri, url.Trim(), out var absolute)) return false; + if (absolute.Scheme != Uri.UriSchemeHttp && absolute.Scheme != Uri.UriSchemeHttps) return false; + if (!IsTrustedOrigin(absolute.AbsoluteUri)) return false; + + resolved = absolute; + return true; + } + + /// + /// A new window owned by this one, registered like every other window, running as a new FDC3 + /// instance of this window's appId. Pass false when WebView2 + /// itself will navigate the child (NewWindowRequested). + /// + private MainWindow ShowOwnedChild( + string url, + int width, + int height, + bool navigateOnLoad, + double? left, + double? top, + Action? onCoreReady = null) + { + var child = new MainWindow(_configuration, _fdc3, _fdc3AppId, url: url, navigateOnLoad: navigateOnLoad) + { + Owner = this, + WindowStartupLocation = WindowStartupLocation.Manual, + Width = width, + Height = height, + Left = left ?? Left + 32, + Top = top ?? Top + 32, + }; + // Before Show: OnLoaded starts init, and the callback must be in place when init finishes. + if (onCoreReady is not null) child.WhenCoreReady(onCoreReady); + child.Show(); + return child; + } + + /// + /// Projects the window controller into the page. For a window.open child this + /// has to happen after the opener's deferral completes; before that the web content + /// is not initialized and the registration never receives calls. + /// + internal void ExposeHostObject() + { + if (_webView.CoreWebView2 is not { } core) return; + _scriptHost ??= new WindowScriptHost(this); + core.AddHostObjectToScript("windowController", _scriptHost); + } + + private WindowScriptHost? _scriptHost; + // Reconnect once a navigation commits (ContentLoading fires before the // page's scripts and not for cancelled/failed navigations or redirect hops), // so the live page keeps its listeners until it is really replaced. private void OnContentLoading(object? sender, CoreWebView2ContentLoadingEventArgs e) { + if (!_navigateOnLoad) + { + try { ExposeHostObject(); } + catch (Exception ex) { System.Diagnostics.Debug.WriteLine($"Child host object failed: {ex}"); } + } + try { var isFirstNavigation = _fdc3Connection is null; @@ -430,6 +655,16 @@ public void SetProgressValue(double value) }); } + public void OpenChild(OpenChildRequest request) + { + if (!TryResolveSameOrigin(request.Url, out var target)) + throw new IpcRejectedException("Child URL must be same-origin."); + + var width = request.Width > 0 ? request.Width : DefaultChildWidth; + var height = request.Height > 0 ? request.Height : DefaultChildHeight; + ApplyWindowAction(() => ShowOwnedChild(target.AbsoluteUri, width, height, navigateOnLoad: true, left: null, top: null)); + } + [DllImport("user32.dll", EntryPoint = "GetForegroundWindow")] private static extern IntPtr NativeGetForegroundWindow();