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 start with the Visual Studio project template for a blank WinUI 3 project, and then 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. The completed sample is available at GitHub: WebView2Samples repo > WinUI3_GettingStarted.

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 box 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 box, 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.

    The Configure your new project dialog box appears.

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

    The 'Configure your new project' dialog box

  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, 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 sample 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 a WebView2 control to the blank WinUI 3 sample app project, as follows.

  1. In Visual Studio, in Solution Explorer, select 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"
        xmlns:controls="using:Microsoft.UI.Xaml.Controls">
    
        <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 <StackPanel> tags 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 sample application 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 sample app.

Step 5 - Add navigation controls

To allow users to control which webpage is displayed in the WebView2 control, add an address bar to the sample 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, copy the following code into myButton_Click. 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 sample app displays the Bing website. The address bar displays the URL, such as https://www.bing.com:

    The sample 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, because the URL doesn't start with http:// or https://.

  7. Close the sample app. The following dialog boxes might appear:

    Debugger not configured

  8. These debugger dialog boxes are a known bug. Click the OK button, and then click the Cancel button to close the dialog boxes.

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:

    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, modify the constructor 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. Enter an HTTP URL, such as http://bing.com.

    Navigation is blocked to HTTP sites.

  7. Enter an HTTPS URL, such as https://bing.com.

    Navigation is allowed for HTTPS sites.

  8. Close the sample app. The following dialog boxes might appear:

    Debugger not configured

  9. These debugger dialog boxes are a known bug. Click the OK button, and then click the Cancel button to close the dialog boxes.

WinRT CoreWebView2 object availability

The WinRT CoreWebView2 object might not be available with the release of the WebView2 API. For a list of available APIs, see:

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. Modify the EnsureHttps function as follows:

    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. Try to open a non-HTTPS URL, such as http://www.bing.com.

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

    Sample app WebView2 control displays an alert dialog for non-HTTPS websites

Congratulations, you built your first WebView2 app!

WinUI 3 WebView2 special considerations

SmartScreen

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, you can do so via an environment variable:

  • 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.

API limitations

The following interfaces aren't accessible in WinUI 3:

  • ICoreWebView2Environment
  • ICoreWebView2EnvironmentOptions and ICoreWebView2EnvironmentOptions2
  • ICoreWebView2ControllerOptions

API Reference

WinUI 3 API Reference (Windows App SDK):

All platforms/languages:

See also

developer.microsoft.com:

Local pages:

GitHub: