I'm using the Microsoft.Web.WebView2.Wpf.WebView2 control in a c#/WPF application to display local help html pages. I'd like to turn off or block WebView2's ability to access non-local internet webpages. Is that possible?
All you need to do is subscribe to WebView2
's NavigationStarting
and cancel it if the URI isn't pointing to one of your local files.
private void webView_NavigationStarting(object sender, Microsoft.Web.WebView2.Core.CoreWebView2NavigationStartingEventArgs e)
{
//when navigation to local resources - do nothing
if (IsUriLocal(e.Uri))
{
return;
}
//when navigation to any other URI - cancel navigation
e.Cancel = true;
}
private bool IsUriLocal(string uri)
{
//check if a URI is local or not
return uri.StartsWith("https://localhost");
}