Search code examples
c#webviewevent-handlingwinui-3webview2

webView.CoreWebView2.NewWindowRequested is null?


I'm making a browser app in WinUI 3 C#. I have found that when I new tab is requested, a new Edge window opens, because I haven't told the WebView what to do when this happens. I have created the method below, which is supposed to be called when the WebView gets a new tab request:

public static void WebView_NewWindowRequested(CoreWebView2 sender, CoreWebView2NewWindowRequestedEventArgs e) {
    MainWindow.NewTab(new(e.Uri));
}

I then attach this event handler to my WebView like this:

Variables.webViews[index].CoreWebView2.NewWindowRequested += WebView_NewWindowRequested;

However, this throws a System.NullReferenceException:

System.NullReferenceException: 'Object reference not set to an instance of an object.'

What is the problem with my code? I have used these other calls to attach other handlers to my WebView:

Variables.webViews[index].NavigationStarting += WebView_NavigationStarting;
Variables.webViews[index].NavigationCompleted += WebView_NavigationCompleted;

And they are virtually the same.

So why is this exception being thrown?


Solution

  • Problem seems to be that WebView2.CoreWebView2 is null. It doesn't get initialized until you start navigation, or set WebView2.Source. You must call WebView2.EnsureCoreWebView2Async() (link) to get CoreWebView2 initialized.