Open Link Clicked on Webview2 on edge browser new window

Viewed 32

I want to open new edge window on link click on HTML in webview2 popup. Below code opens the url in same window.

private void webView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
 webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
}

private void CoreWebView2_NewWindowRequested(object sender,CoreWebView2NewWindowRequestedEventArgs  e)
{
    e.NewWindow = (CoreWebView2)sender;
   
}
1 Answers

If you want to open the URI in the end user's default web browser instead of a new window in WebView2 you can cancel the CoreWebView2.NewWindowRequested event and send the URI to the browser:

private void webView21_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
 webView21.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
}

private void CoreWebView2_NewWindowRequested(object sender,CoreWebView2NewWindowRequestedEventArgs  e)
{
    e.Handled = true;
    // No need to wait for the launcher to finish sending the URI to the browser
    // before we allow the WebView2 in our app to continue.
    _ = Windows.System.Launcher.LaunchUriAsync(new Uri(args.Uri));
    // LaunchUriAsync is the WinRT API for launching a URI.
    // Another option not involving WinRT might be System.Diagnostics.Process.Start(args.Uri);
}

I have a CoreWebView2.NewWindowRequested handling sample code, that demonstrates different ways of handling NewWindowRequested.

Related