Getting started with WebView2 in WinUI3 (Preview)

In this article, get started creating your first WebView2 app with WinUI3 and learn about the main features of Introduction to Microsoft Edge WebView2 (Preview). For more information on individual APIs, see API reference.

Prerequisites

Ensure you install the following list of pre-requisites before proceeding with the following article.

Step 1 - Create Project

Start with a basic desktop project containing a single main window.

  1. In Visual Studio, select Create a new project.

  2. In the project drop-down, select C#, Windows, and WinUI respectively.

    Visual studio project creation dialog for  WinUI

  3. Choose Blank App, Packaged (WinUI in Desktop), and then choose Next.

  4. Enter a project name, choose other options as needed, and then select Create.

  5. In New Universal Windows Platform Project, select the following values, and then choose OK:

    • Target version: Windows 10, version 1903 (build 18362) or later.
    • Minimum version: Windows 10, version 1803 (build 17134).

    The New Universal Windows Platform Project dialog with selected values for Target version and Minimum version.

  6. In the Solution Explorer, two projects are generated.

    • Your project name (Desktop). This project contains the code for your app. App.xaml.cs defines an Application class that represents your app instance. MainWindow.xaml.cs defines a MainWindow class that represents the main window displayed by your app instance. These classes derive from types in the Microsoft.UI.Xaml namespace of WinUI.

    • Your project name (Package). This project is a Windows Application Packaging Project that is configured to build the app into an MSIX package for deployment. The project contains the package manifest for your app, and it is the startup project for your solution by default. For more information, see Set up your desktop application for MSIX packaging in Visual Studio and Package manifest schema reference for Windows 10.

  7. In the Solution Explorer, open MainWindow.xaml to display the code. Select F5 to run your project and show a window with a button.

Step 2 - Add a WebView2 control to your project

Next add a WebView2 control to your project.

  1. Open MainWindow.xaml. Add the WebView2 XAML namespace by inserting the following line inside the <Window/> tag.

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

    Confirm that your code in MainWindow.xaml is similar to the following code snippet.

    <Window
          x:Class="WinUI_Sample.MainWindow"
          xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
          xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
          xmlns:local="using:WinUI_Sample"
          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>
    
  2. To add the WebView2 control, replace the <StackPanel> tags with the following code snippet. The Source property sets the initial URI displayed in the WebView2 control.

    <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>
    
  3. Open MainWindow.xaml.cs and comment out the following line.

        // myButton.Content = "Clicked";     
    
  4. Select F5 to build and run your project. Confirm that your WebView2 control displays https://www.microsoft.com.

    A WebView2 control displaying the microsoft.com site

Step 3 - Add navigation controls

Allow users to control the web page that is displayed in your WebView2 control by adding an address bar to your app.

  1. In MainWindow.xaml, copy and paste the following code snippet inside the Grid element that contains the WebView2 element.

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

    Confirm that your Grid element of MainWindow.xaml is similar to the following code snippet.

    <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>
    
        <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 snippet to myButton_Click, which 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.
        }
    }
    

    Select F5 to build and run your project. Enter a new URL in the address bar, and then select Go. For example, enter https://www.bing.com.

    Note

    Ensure you use complete URLs in the address bar. ArgumentException exceptions are thrown if the URL does not start with http:// or https://.

    Bing.com

Step 4 - Navigation events

Applications that host WebView2 controls listen for the following events that are raised by WebView2 controls during web page navigation.

  • NavigationStarting
  • SourceChanged
  • ContentLoading
  • HistoryChanged
  • NavigationCompleted

Note

HTTP redirects raise multiple NavigationStarting events.

For more information, see Navigation Events.

When errors occur, the following events are raised and may navigate to an error page.

  • SourceChanged
  • ContentLoading
  • HistoryChanged

As an example of how to use the events, register a handler for NavigationStarting that cancels any requests that don't use HTTPS. In MainWindow.xaml.cs, modify the constructor to register EnsureHttps, and add the EnsureHttps function so that it matches the following code snippet.

public MainWindow()
{
    InitializeComponent();
    MyWebView.NavigationStarting += EnsureHttps;
}

private void EnsureHttps(WebView2 sender, WebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        args.Cancel = true;
    }
    else
    {
        addressBar.Text = uri;
    }
}

Select F5 to build and run your project. Confirm that navigation is blocked to HTTP sites, and allowed for HTTPS sites.

Step 5 - Scripting

Host applications may inject JavaScript code into WebView2 controls at runtime. The injected JavaScript applies to all new top level documents and any child frames until the JavaScript is removed. The injected JavaScript is run after creation of the global object, and before any other script included in the HTML document is run.

As an example, add scripts send an alert when a user navigates to non-HTTPS sites. Modify the EnsureHttps function to inject a script into the web content using ExecuteScriptAsync.

private void EnsureHttps(WebView2 sender, WebView2NavigationStartingEventArgs 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;
    }
}

Select F5 to build and run your project. Confirm that your application displays an alert when you navigate to a site that does not use HTTPS.

WebView2 control showing an alert dialog

Congratulations, you built your first WebView2 app.

Next Steps

Our team is currently building more WebView2 APIs. For more information on the current state of WebView2 APIs, see the WebView2 spec.

Note

The WinRT CoreWebView2 object may not be available at the time the WebView2 APIs ship. To understand which APIs are available to WebView2 controls, see WebView2 Spec for a list of the APIs that are available.

For more information about WebView2 capabilities, see WebView2 Concepts and How-To guides, and the WebView2 samples repo.

Getting in touch with the Microsoft Edge WebView team

Share your feedback to help build richer WebView2 experiences. To submit feature requests or bugs, or search for known issues, see the Microsoft Edge WebView feedback repo.