Skip to content

Commit

Permalink
feat(Shell): override window.close() in the embedded browser
Browse files Browse the repository at this point in the history
  • Loading branch information
kruplm committed Sep 25, 2024
1 parent 232b394 commit 4a9a8af
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,14 @@ public Task InvokeAsync(StartupContext startupContext, Func<Task> next)
}
};
"""));

webProperties.ScriptProviders.Add(
_ => new ValueTask<string>(
$$"""
window.close = function() {
window.chrome.webview.postMessage("closeWindow");
};
"""));
}

startupContext.AddProperty(new EnvironmentVariables(new[] { new KeyValuePair<string, string>(WebSocketEnvironmentVariableNames.Uri, _webSocketServer.WebSocketUrl.AbsoluteUri),
Expand Down
11 changes: 11 additions & 0 deletions src/shell/dotnet/Shell/WebContent.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down

0 comments on commit 4a9a8af

Please sign in to comment.