Location>code7788 >text

Winform Developing Modern Applications with WebView2

Popularity:547 ℃/2024-12-23 23:25:47

Developing Modern Applications with WebView2

WebView2 is an embedded browser control from Microsoft, based on the Edge (Chromium) engine. It allows developers to combine modern Web technologies such as HTML, CSS, and JavaScript with desktop applications to build powerful, flexible user interfaces.

This article will introduce the basic use of WebView2 and focus on the following important features:

  • NewWindowRequested
  • WebResourceResponseReceived
  • AddWebResourceRequestedFilter
  • WebResourceRequested

environmental preparation

  1. Install WebView2 Runtime: WebView2 requires runtime support and the user device must have the WebView2 Runtime installed. if it is not installed, it can be downloaded at the following link:WebView2 Runtime

  2. Introduce the necessary NuGet packages: In Visual Studio, add the.WebView2 NuGet package.

  3. Initialize WebView2: Create the WebView2 control and make sure it is properly initialized. The following code checks and installs the WebView2 Runtime:

private static async Task<bool> InitializeWebView2()
{
    try
    {
        string version = ();
        return !(version);
    }
    catch
    {
        // Guiding the user through the installation WebView2 Runtime
        ("WebView2 Runtime uninstalled。Please install and retry。", "incorrect", , );
        return false;
    }
}

Creating a WebView2 Control

The following code shows how to create the WebView2 control and initialize its core functionality:

public static async Task<WebView2> CreateWebView()
{
    if (!await InitializeWebView2())
    {
        return null;
    }

    WebView2 webView2 = new WebView2
    {
        Dock =
    };

    await webView2.EnsureCoreWebView2Async(null);

    // registered event
    webView2. += CoreWebView2_NewWindowRequested;
    webView2. += CoreWebView2_WebResourceResponseReceived;

    // Adding a Request Filter
    webView2.("*:///*", );
    webView2. += WebView2_WebResourceRequested;

    return webView2;
}

Intercept new window requests:NewWindowRequested

By default, WebView2 tries to open the popup link in a new window. This is accomplished byNewWindowRequested event, we can intercept the popup behavior and load the new content into the current window.

Sample code:

private static void CoreWebView2_NewWindowRequested(object sender, CoreWebView2NewWindowRequestedEventArgs e)
{
    if (sender is CoreWebView2 webView)
    {
         = true; // Blocking default pop-up behavior
        (); // at the present time WebView2 Loading a new page in
    }
}

Intercepting and processing network responses:WebResourceResponseReceived

pass (a bill or inspection etc)WebResourceResponseReceivedWe can view and analyze all network responses. For example, it is possible to log response times for certain requests or examine response headers.

Sample code:

private static void CoreWebView2_WebResourceResponseReceived(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e)
{
    var uri = ;
    ($"Response received for: {uri}");

    ().ForEach(header =>
    {
        ($"Header: {} - {}");
    });
}

Add a request filter:AddWebResourceRequestedFilter

For improved performance and precise control, WebView2 provides theAddWebResourceRequestedFilter method to define the type and scope of requests to listen for.

Usage:

webView.(
    "*:///*", // Target URL pattern
     // Resource type: document only
);

Intercepting web requests:WebResourceRequested

pass (a bill or inspection etc)WebResourceRequested events that can intercept network requests and process them, such as modifying request headers or blocking specific requests.

Sample code:

private static async void WebView2_WebResourceRequested(object sender, CoreWebView2WebResourceRequestedEventArgs e)
{
    var request = ;

    // Check for specific Cookie
    if (sender is CoreWebView2 webView)
    {
        var cookies = (await ())
                        .Where(c => == "SpecificCookie").ToList();

        if (())
        {
            // Delete specific Cookie
            (c => (c));
        }
    }

    ($"Request intercepted: {}");
}

summarize

WebView2 is a powerful control that provides developers with a rich set of features to control and customize the loading behavior of web resources. With the events and methods described in this article, you can:

  • Block default popup behavior (NewWindowRequested)
  • Analyze the network response (WebResourceResponseReceived)
  • Precise filtering of requests to be intercepted (AddWebResourceRequestedFilter)
  • Modify or block network requests (WebResourceRequested)

These capabilities provide greater flexibility in integrating Web content into desktop applications to meet a variety of business needs.