I am developing an email application where I would like to display mail messages in WebView2. I would like to give a choice to the users to download or not remote resources in Html mail messages(for security reasons). How can I cancel requested resource in WebView2?
I tried subscribing for the event webView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
but when the event handler is invoked I don't see a way to cancel the request.
The way to cancel a request to a resource is to set the Response
property of the CoreWebView2WebResourceRequestedEventArgs
parameter to a dummy response.
However, before you do that, you have to call CoreWebView2.AddWebResourceRequestedFilter
to specify which resource types you want to trigger the WebResourceRequested
event.
Here is an example, that will filter out all requests to images:
using Microsoft.Web.WebView2.Core;
private async void Form1_Load(object sender, EventArgs e)
{
await webView21.EnsureCoreWebView2Async();
}
private void WebView21_CoreWebView2InitializationCompleted(object sender, Microsoft.Web.WebView2.Core.CoreWebView2InitializationCompletedEventArgs e)
{
webView21.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
webView21.CoreWebView2.AddWebResourceRequestedFilter(null, Microsoft.Web.WebView2.Core.CoreWebView2WebResourceContext.Image);
webView21.CoreWebView2.Navigate("https://stackoverflow.com");
}
private void CoreWebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
{
e.Response = webView21.CoreWebView2.Environment.CreateWebResourceResponse(null, 404, "Not found", null);
}
You can of course and more filtering logic, if you like.