diff --git a/src/shell/dotnet/Shell/Messaging/MessageRouterStartupAction.cs b/src/shell/dotnet/Shell/Messaging/MessageRouterStartupAction.cs index ee42c1a94..ca7d113d1 100644 --- a/src/shell/dotnet/Shell/Messaging/MessageRouterStartupAction.cs +++ b/src/shell/dotnet/Shell/Messaging/MessageRouterStartupAction.cs @@ -53,6 +53,14 @@ public Task InvokeAsync(StartupContext startupContext, Func next) } }; """)); + + webProperties.ScriptProviders.Add( + _ => new ValueTask( + $$""" + window.close = function() { + window.chrome.webview.postMessage("closeWindow"); + }; + """)); } startupContext.AddProperty(new EnvironmentVariables(new[] { new KeyValuePair(WebSocketEnvironmentVariableNames.Uri, _webSocketServer.WebSocketUrl.AbsoluteUri), diff --git a/src/shell/dotnet/Shell/WebContent.xaml.cs b/src/shell/dotnet/Shell/WebContent.xaml.cs index e62715619..d55da81c8 100644 --- a/src/shell/dotnet/Shell/WebContent.xaml.cs +++ b/src/shell/dotnet/Shell/WebContent.xaml.cs @@ -131,10 +131,21 @@ private Task InitializeCoreWebView2(CoreWebView2 coreWebView) Debug.WriteLine($"WindowCloseRequested EventHandler was added at: {DateTime.Now}"); coreWebView.NavigationStarting += (sender, args) => OnNavigationStarting(args); coreWebView.DocumentTitleChanged += (sender, args) => OnDocumentTitleChanged(args); + coreWebView.WebMessageReceived += (sender, args) => OnWebMessageReceived(args); return Task.CompletedTask; } + private void OnWebMessageReceived(CoreWebView2WebMessageReceivedEventArgs args) + { + + var message = args.TryGetWebMessageAsString(); + if (message == "closeWindow") + { + CloseRequested.Invoke(this, EventArgs.Empty); + } + } + private void OnDocumentTitleChanged(object args) { if (_options.Title == null)