Search code examples
c#winformswebview2

How to restrict WebView2 from downloading content?


I have a WinForms2 C# application with a basic WebView2 component along with a textBox (to be used as a search bar). I want to restrict the webView2 from being able to download content. For example, if I go to pixabay.com and try to download an image, I want it to stop the download and restrict that image from being downloaded.

I tried using the CloseDefaultDownloadDialog and webView.CoreWebView2.IsDefaultDownloadDialogOpenChanged methods to block the content from downloading: webView.CoreWebView2.IsDefaultDownloadDialogOpenChanged += downloadsPrompted; and this:

private void downloadsPrompted(object sender, object e)
{
    button1.Text = "It runs";
    WebView2 webView = sender as WebView2;
    if (webView.CoreWebView2.IsDefaultDownloadDialogOpen)
    {
        webView.CoreWebView2.CloseDefaultDownloadDialog();
    }
}

However this didn't work and the image still downloaded. I have the button1.Text = "It runs"; to make sure that method is actually running (and it ran).


Solution

  • The CoreWebView2.CloseDefaultDownloadDialog() is meant to close Download dialog, not to stop or prevent a download that has already been initiated.

    As you have experienced, when this method is called, it's already too late: the download has pre-emptively started. If you just close the dialog, the file requested is stored in the default location (the User's Download folder).

    You can instead handle the DownloadStarting event, which is related to the actual download request.
    This event is raised before the download begins.
    You can then set the e.Cancel property of the CoreWebView2DownloadStartingEventArgs to true to cancel the download entirely:

    [WebView2].CoreWebView2.DownloadStarting += CoreWebView2_DownloadStarting;
    
    // [...]
    
    private void CoreWebView2_DownloadStarting(object? sender, 
                 CoreWebView2DownloadStartingEventArgs e) {
        e.Cancel = true;
    }
    

    This also sets a state, CoreWebView2DownloadState, to Interrupted and the InterruptReason - CoreWebView2DownloadInterruptReason - to UserCanceled.

    It may be interesting to also see the functionality of the e.DownloadOperation member, which allows to pause and resume the download (if CanResume is true), redirect the file on the fly (to something different than [WebView2].CoreWebView2.Profile.DefaultDownloadFolderPath), get the count of bytes received against the total bytes to receive, etc.