0

I have a Webview2 app that needs to be able to intercept window.open calls and configure the resulting window in a certain way (e.g. make it non-resizable, frameless, remove the default location bar that appears, etc).

So far, I know that I need to intercept the NewWindowRequested event and assign the NewWindow property of the EventArgs to the new Webview2 control, however I'm having trouble getting this to work, and I haven't found any documentation listing an example that attempts this.

I'm using WPF.

Note also that I'm new to both WPF and WebView2, so maybe something I'm doing is totally non-sensical.

This is roughly my code:

public static async void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e) {
    var obj = e.GetDeferral(); // I think I need to do this to ensure that the resulting window ends up as the return of window.open
    var win = new System.Windows.Window(); // create my WPF window
    var w = new WebView2(); // create my Webview control
    win.Content = w; // site the Webview control?

    await w.EnsureCoreWebView2Async(MainWindow.Webview.CoreWebView2.Environment);

    e.NewWindow = w.CoreWebView2;
    obj.Complete();
}

The problem I'm seeing is that the Task returned by EnsureCoreWebView2Async never completes.

Am I setting this up correctly? Why doesn't EnsureCoreWebView2Async resolve?

pushkin
  • 9,575
  • 15
  • 51
  • 95
  • Try: `public async void CoreWebView2_NewWindowRequested` then you can `await`. – Poul Bak Oct 14 '21 at 23:41
  • But won't an exception inside of an `async void` crash the process? I mean I guess I can wrap everything in try/catch, but kind of annoying; maybe that's what I'll do though. @PoulBak – pushkin Oct 15 '21 at 00:38
  • The `async void` is specifically made for eventhandlers and should only be used for that. When you don't `await` it's 'fire and forget'. – Poul Bak Oct 15 '21 at 15:13
  • @PoulBak Ok, I'll update my code. Though it doesn't fix my issue – pushkin Oct 15 '21 at 15:33
  • Check this answer: https://stackoverflow.com/questions/65139090/how-can-i-initialize-the-webview2-in-wpf/65176665#65176665 – Poul Bak Oct 15 '21 at 15:40
  • @PoulBak I'm not sure which `Controls` property they're talking about. My `System.Windows.Window` object doesn't have `Controls`, only `Content`. Not sure what `Controls` refers to exactly. I vaguely recall using that for a `Form`, but I'm not using WinForms here – pushkin Oct 15 '21 at 15:43
  • 1
    @PoulBak It seems that calling `win.Show()` makes it work and the Task completes – pushkin Oct 15 '21 at 17:17

1 Answers1

0

It seems like I had to call win.Show() to make the EnsureCoreWebView2Async Task complete.

Perhaps I'll really want to only show the window after the webview content has loaded, but this is a good start at least.

pushkin
  • 9,575
  • 15
  • 51
  • 95