Home > Software design >  Is it possible to block internet access in WebView2?
Is it possible to block internet access in WebView2?

Time:09-26

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?

CodePudding user response:

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");
}
  • Related