Get started with WebView2 in WinUI 3 (Windows App SDK) apps

This article covers how to set up your development tools and create an initial WebView2 app for WinUI 3 (Windows App SDK), and learn about WebView2 concepts along the way.

In this tutorial, you use the Blank App, Packaged (WinUI in Desktop) Visual Studio project template to create a blank WinUI 3 project. That project template uses the WindowsAppSDK, which includes the WebView2 SDK. You add a WebView2 control. You then add an address bar and logic to display a warning dialog when the user tries to navigate to a URL with an http:// prefix.

App displaying the Bing website

Completed project

A completed version of this tutorial project (as of 2020) is available in the WebView2Samples repo:

  • Sample name: WinUI3_GettingStarted
  • Repo directory: WinUI3_GettingStarted
  • Solution file: WinUI_Sample.sln

The present tutorial is updated and only creates a single project, not a second, "(Package)" project like in 2020.

Step 1 - Install Visual Studio and the Windows App SDK

Even if you have Visual Studio installed, read the following page and possibly update your software and install project templates.

  1. In a new window or tab, open the page Install tools for the Windows App SDK and then follow the steps on that page, to install Microsoft Visual Studio, such as Visual Studio 2022.
  1. If needed, in a new window or tab, see Install Visual Studio in Set up your Dev environment for WebView2.

Return from that page and continue the steps below.

For this sample, you don't need to separately install the WebView2 SDK. Below, you'll select the project template Blank App, Packaged (WinUI in Desktop), which uses the WindowsAppSDK, which includes the WebView2 SDK.

Step 2 - Install a preview channel of Microsoft Edge

  1. Install the WebView2 Runtime or any Microsoft Edge preview channel (Beta, Dev, or Canary) installed on Windows 10 version 1803 (build 17134) or later.

Return from that page and continue the steps below.

Step 3 - Create a blank WinUI 3 project

To create a WebView2 app, start by creating a basic desktop project, to create a desktop app that contains a single main window:

  1. If Visual Studio is not running, start Visual Studio (not Visual Studio Code). In the Visual Studio startup window, click the Create a new project card. The Create a new project window opens.

    Or, if Visual Studio is running, select File > New > Project. The Create a new project dialog opens.

    Turning on Developer Mode: When Visual Studio opens at some point during the present article's steps, you might be prompted to turn on Developer Mode for your computer. For more information, if needed, see Enable your device for development, at Build desktop apps for Windows.

  2. In the Create a new project dialog, in the Search for templates field, enter WinUI 3 in Desktop:

    Searching on "WinUI 3 in Desktop" to create a new project

  3. Click the Blank App, Packaged (WinUI in Desktop) card to select it, and then click the Next button.

    If WinUI templates aren't listed, you need to install project templates as mentioned above, from Install tools for the Windows App SDK. Additional tips to get the template to appear:

    After installing "default" options for Visual Studio 2022 Community edition, in Visual Studio Installer, click the .NET card, then on the right, select the checkbox Windows App SDK C# Templates.

    If the correct project template still doesn't appear: in the Visual Studio Installer, click the UWP card to select it, select the v143 C++ tools checkbox on the right, and then click the Modify button.

    The Configure your new project dialog appears.

  4. In the Project name text box, enter a project name, such as MyWebView2WinUI3:

    The 'Configure your new project' dialog

  5. In the Location text box, enter or navigate to a location, such as C:\Users\username\Documents\WebView2.

  6. Click the Create button.

    The new WinUI 3 project opens in Solution Explorer in Visual Studio:

    The new WinUI 3 project in Solution Explorer

    • The App.xaml.cs file defines an Application class that represents your app instance.

    • The MainWindow.xaml.cs file defines a MainWindow class that represents the main window displayed by your app instance. The classes derive from types in the Microsoft.UI.Xaml namespace of WinUI.

  7. In the Solution Configurations dropdown list (in the middle of the top of the window), select Debug.

  8. In the Solution Platforms dropdown list, select a platform, such as x64.

  9. Select File > Save All (Ctrl+Shift+S) to save the project.

  10. Press F5 to build and run the project. The blank WinUI Desktop app opens, with no WebView2 control added yet:

    The new blank WinUI 3 app

  11. Close the app.

Updating target version numbers

For the build step above: If you're updating a previous project, you might need to update the version numbers for Target version and Minimum version. To do this, in Solution right-click the project and then select Edit Project File. Your .csproj file opens. Make sure the values are updated as follows, and then save any changes and build the project.

    <TargetFramework>net6.0-windows10.0.19041.0</TargetFramework>
    <TargetPlatformMinVersion>10.0.17763.0</TargetPlatformMinVersion>

The above values represent:

  • Target version: Windows 10, version 2004 (build 19041) or later.
  • Minimum version: Windows 10, version 1809 (build 17763).

Step 4 - Add a WebView2 control

This tutorial project is based on the project template Blank App, Packaged (WinUI in Desktop). This project template uses the WindowsAppSDK, which includes the WebView2 SDK.

Edit the MainWindow.xaml and MainWindow.xaml.cs files to add a WebView2 control to the blank WinUI 3 app project, as follows:

  1. In Visual Studio, in Solution Explorer, double-click MainWindow.xaml to open it in the code editor.

  2. Add the WebView2 XAML namespace by inserting the following attribute inside the <Window> start tag:

    xmlns:controls="using:Microsoft.UI.Xaml.Controls"
    

    Make sure your code in MainWindow.xaml is similar to the following:

    <Window
        x:Class="MyWebView2WinUI3.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:MyWebView2WinUI3"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d">
    
        <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
            <Button x:Name="myButton" Click="myButton_Click">Click Me</Button>
        </StackPanel>
    </Window>
    
  3. To add the WebView2 control, replace the entire <StackPanel> element with the following <Grid> code. The Source property, near the bottom, sets the initial URI that's displayed in the WebView2 control (https://www.microsoft.com):

    <Grid>
    
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
    
        <controls:WebView2 x:Name="MyWebView"  Grid.Row="1" Grid.ColumnSpan="2"
            Source="https://www.microsoft.com" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    
    </Grid>
    
  4. In Solution Explorer, expand MainWindow.xaml and then open MainWindow.xaml.cs.

  5. In MainWindow.xaml.cs, comment out the following line, as shown:

        // myButton.Content = "Clicked";
    
  6. Select File > Save All (Ctrl+Shift+S) to save the project.

  7. Press F5, to build and run the project.

  8. The app is a WebView2 host app that includes the WebView2 control. The WebView2 control displays the website https://www.microsoft.com:

    The WebView2 control displaying the microsoft.com webpage

  9. Close the app.

WinAppSDK supports custom WebView2 environments

WinAppSDK supports custom WebView2 environments, starting with WinAppSDK 1.5 (1.5.0-experimental2). For more information, see WinUI3 WebView2 with a custom CoreWebView2Environment.

To instantiate a custom WebView2 environment, initialize WebView2 with one of the overrides of WebView2.EnsureCoreWebView2Async (listed below), and pass in your custom CoreWebView2Environment (and, optionally, custom CoreWebView2ControllerOptions):

public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment)
public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment, CoreWebView2ControllerOptions controllerOptions)

Also see the example code in Disabling SmartScreen navigation, below.

API Reference:

Step 5 - Add navigation controls

To allow users to control which webpage is displayed in the WebView2 control, add an address bar to the app, as follows:

  1. In MainWindow.xaml, paste the following code inside the <Grid> element that contains the <controls:WebView2> element:

       <TextBox Name="addressBar" Grid.Column="0"/>
       <Button x:Name="myButton" Grid.Column="1" Click="myButton_Click">Go</Button>
    

    Make sure the resulting <Grid> element in the MainWindow.xaml file matches the following:

    <Grid>
    
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"/>
            <ColumnDefinition Width="Auto"/>
        </Grid.ColumnDefinitions>
    
        <TextBox Name="addressBar" Grid.Column="0"/>
        <Button x:Name="myButton" Grid.Column="1" Click="myButton_Click">Go</Button>
    
        <controls:WebView2 x:Name="MyWebView"  Grid.Row="1" Grid.ColumnSpan="2"
        Source="https://www.microsoft.com" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"/>
    
    </Grid>
    
  2. In MainWindow.xaml.cs, paste the following code into myButton_Click, overwriting the existing myButton_Click method (which is nearly empty). This code navigates the WebView2 control to the URL entered in the address bar.

    private void myButton_Click(object sender, RoutedEventArgs e)
    {
        try
        {
            Uri targetUri = new Uri(addressBar.Text);
            MyWebView.Source = targetUri;
        }
        catch (FormatException ex)
        {
            // Incorrect address entered.
        }
    }
    
  3. Select File > Save All (Ctrl+Shift+S) to save the project.

  4. Press F5 to build and run the project.

  5. Enter a new complete URL in the address bar, such as https://www.bing.com, and then click the Go button.

    The WebView2 control in the app displays the Bing website. The address bar displays the URL, such as https://www.bing.com:

    The app displays the Bing website

  6. Enter an incomplete URL in the address bar, such as bing.com, and then click the Go button.

    An ArgumentException exception is thrown, and appears after you close the app, because the URL doesn't start with http:// or https://.

  7. Close the app.

Step 6 - Navigation events

In this section, you add code to import the WebView2 Core library.

  1. In MainWindow.xaml.cs, add the following line at the top, above the other using statements:

    using Microsoft.Web.WebView2.Core;
    

    Apps that host WebView2 controls listen for the following events that are raised by WebView2 controls during webpage navigation:

    • NavigationStarting
    • SourceChanged
    • ContentLoading
    • HistoryChanged
    • NavigationCompleted

    If an HTTP redirect occurs, there are multiple NavigationStarting events in a row.

    For more information, see Navigation events for WebView2 apps.

    When errors occur, the following events are raised, and an error webpage might be displayed:

    • SourceChanged
    • ContentLoading
    • HistoryChanged

    As an example of how to use the events, register a handler for NavigationStarting that cancels any non-HTTPS requests, as follows:

  2. In MainWindow.xaml.cs, in the constructor, add the following NavigationStarting line, to register the EnsureHttps method:

    public MainWindow()
    {
        this.InitializeComponent();
        MyWebView.NavigationStarting += EnsureHttps;
    }
    
  3. In MainWindow.xaml.cs, below the constructor, add the following EnsureHttps method:

    private void EnsureHttps(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
    {
        String uri = args.Uri;
        if (!uri.StartsWith("https://"))
        {
            args.Cancel = true;
        }
        else
        {
            addressBar.Text = uri;
        }
    }
    
  4. Select File > Save All (Ctrl+Shift+S) to save the project.

  5. Press F5 to build and run the project.

  6. In the app, in the Address bar, enter an HTTP URL, such as http://bing.com, and then click the Go button.

    Nothing happens, because navigation is blocked to HTTP sites, and we haven't yet added a dialog to provide feedback.

  7. Enter an HTTPS URL, such as https://bing.com, and then click the Go button.

    The app navigates to the specified page, because navigation is allowed for HTTPS sites.

  8. Close the app.

Step 7 - Scripting

You can use host apps to inject JavaScript code into WebView2 controls at runtime. You can task WebView2 to run arbitrary JavaScript or add initialization scripts. The injected JavaScript applies to all new top-level documents and any child frames until the JavaScript is removed. The injected JavaScript is run with specific timing, to either:

  • Run the injected JavaScript after the creation of the global object.

  • Run the injected JavaScript before running any other script that's included in the HTML document.

As an example, next, you add scripts that send an alert when a user tries to open non-HTTPS sites. To do this, you inject a script into the web content that uses ExecuteScriptAsync.

  1. In the EnsureHttps method, add the following ExecuteScriptAsync line:

    private void EnsureHttps(WebView2 sender, CoreWebView2NavigationStartingEventArgs args)
    {
        String uri = args.Uri;
        if (!uri.StartsWith("https://"))
        {
            MyWebView.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
            args.Cancel = true;
        }
        else
        {
            addressBar.Text = uri;
        }
    }
    
  2. Select File > Save All (Ctrl+Shift+S) to save the project.

  3. Press F5 to build and run the project.

  4. In the app's Address bar, enter a non-HTTPS URL, such as http://www.bing.com, and then click the Go button.

    The app's WebView2 control displays an alert dialog for non-HTTPS websites, saying that the non-HTTPS uri is not safe:

    The app's WebView2 control displays an alert dialog for non-HTTPS websites

  5. Close the app.

Congratulations, you built your first WebView2 app!

WinUI 3 WebView2 special considerations

Disabling SmartScreen navigation

WebView2 sends URLs that are navigated to in your application to the SmartScreen service, to ensure that your customers stay secure. If you want to disable this navigation, use a custom CoreWebView2Environment, as follows:

CoreWebView2EnvironmentOptions environmentOptions = new CoreWebView2EnvironmentOptions();
environmentOptions.AdditionalBrowserArguments = "--disable-features=msSmartScreenProtection";

string browserFolder = null; // Use null to get default browser folder
string userDataFolder = null; // Use null to get default user data folder
CoreWebView2Environment environment = await CoreWebView2Environment.CreateWithOptionsAsync(
    browserFolder, userDataFolder, environmentOptions);

// ...

this.WebView2.EnsureCoreWebView2Async(environment);
Disabling SmartScreen by using an environment variable

We no longer recommend using an environment variable. Use the above API code-based approach instead.

  • Environment.SetEnvironmentVariable("WEBVIEW2_ADDITIONAL_BROWSER_ARGUMENTS", "--disable-features=msSmartScreenProtection");

This environment variable must be set prior to CoreWebView2 creation, which occurs when the WebView2.Source property is initially set or the WebView2.EnsureCoreWebView2Async method is initially called.

Setting DefaultBackgroundColor

In WebView2 for WinUI 3, the DefaultBackgroundColor setting exists on the WebView2 XAML object. For example:

public MainWindow()
{
    this.InitializeComponent();
    MyWebView.DefaultBackgroundColor = Colors.LightBlue;
}

Transparency

WinUI 3 doesn't support transparent backgrounds. See Transparent background support for WebView2? · Issue #2992.

WinAppSDK support for custom WebView2 environments

See WinAppSDK supports custom WebView2 environments, above.

See also

developer.microsoft.com:

GitHub: