2

I want to know about all the static files which the webview2 component loads in order to perform some validations. Files that I want to be informed about are images, JavaScript and CSS files.

I spent several hours trying to find an event which will inform me about these files but I did not manage to make it work. I suppose there is some kind of low level management which will give me access to these information.

Can someone help me?

pitaridis
  • 2,801
  • 3
  • 22
  • 41

1 Answers1

2

You can use WebResourceRequested event which raises when the WebView is performing a URL request to a matching URL and resource context filter that was added with AddWebResourceRequestedFilter.

Example

In the following example, a message box will be displayed whenever an image is loading from any uri. To do so, drop a WebView2 on the Window and assign it a name webView21 and handle the Loaded event of the window with the following code:

//using Microsoft.Web.WebView2.Core;
//using System.Windows;
private async void Window_Loaded(object sender, RoutedEventArgs e)
{
    await webView21.EnsureCoreWebView2Async();
    webView21.CoreWebView2.AddWebResourceRequestedFilter(
        "*",
        CoreWebView2WebResourceContext.Image);
    webView21.CoreWebView2.WebResourceRequested += (obj, args) =>
    {
        MessageBox.Show(args.Request.Uri);
    };
    webView21.CoreWebView2.Navigate("https://www.google.com");
}

You can find another example here: Edit HTTP Request header with WebView2.

Reza Aghaei
  • 120,393
  • 18
  • 203
  • 398
  • 1
    Be sure to only set AddWebResourceRequestedFilter as minimally as possible to avoid negatively impacting performance. All web requests that match a filter set with AddWebResourceRequestedFilter will be paused in the webview2 while it sends a message to your host app UI thread to raise the WebResourceRequested event. The web request will only continue on after your host app finishes running your event handler and a message is sent back to the webview2 process. – David Risney Jan 04 '23 at 18:46