Home > OS >  How to create custom windows in a WPF / WebView2 application when window.open is called?
How to create custom windows in a WPF / WebView2 application when window.open is called?

Time:10-19

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?

CodePudding user response:

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.

  • Related