Home > database >  webview2 events to inform the application for all static files loading
webview2 events to inform the application for all static files loading

Time:01-04

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?

CodePudding user response:

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.

  • Related