| title | Get started with WebView2 in WinUI 3 (Windows App SDK) apps |
|---|---|
| description | Get started guide with WebView2 for WinUI 3 (Windows App SDK) apps. |
| author | MSEdgeTeam |
| ms.author | msedgedevrel |
| ms.topic | conceptual |
| ms.prod | microsoft-edge |
| ms.technology | webview |
| ms.date | 07/06/2022 |
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.
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.
Even if you have Visual Studio installed, read the following page and possibly update your software and install project templates.
- 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.
- 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.
- 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.
To create a WebView2 app, start by creating a basic desktop project, to create a desktop app that contains a single main window:
-
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.
-
In the Create a new project dialog box, in the Search for templates field, enter WinUI 3 in Desktop:
-
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.
-
In the Project name text box, enter a project name, such as MyWebView2WinUI3:
-
In the Location text box, enter or navigate to a location, such as
C:\Users\username\Documents\WebView2. -
Click the Create button.
The new WinUI 3 project opens in Solution Explorer in Visual Studio:
-
The
App.xaml.csfile defines anApplicationclass that represents your app instance. -
The
MainWindow.xaml.csfile defines aMainWindowclass that represents the main window displayed by your app instance. The classes derive from types in theMicrosoft.UI.Xamlnamespace of WinUI.
-
-
In the Solution Configurations dropdown list, select Debug.
-
In the Solution Platforms dropdown list, select a platform, such as x64.
-
Select File > Save All (
Ctrl+Shift+S) to save the project. -
Press F5 to build and run the project. The blank WinUI Desktop app opens, with no WebView2 control added yet:
-
Close the sample app.
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).
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.
-
In Visual Studio, in Solution Explorer, select
MainWindow.xamlto open it in the code editor. -
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.xamlis 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>
-
To add the WebView2 control, replace the
<StackPanel>tags with the following<Grid>code. TheSourceproperty, 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>
-
In Solution Explorer, expand
MainWindow.xamland then openMainWindow.xaml.cs. -
In
MainWindow.xaml.cs, comment out the following line, as shown:// myButton.Content = "Clicked"; -
Select File > Save All (
Ctrl+Shift+S) to save the project. -
Press F5, to build and run the project.
-
The sample application is a WebView2 host app that includes the WebView2 control. The WebView2 control displays the website
https://www.microsoft.com: -
Close the sample app.
To allow users to control which webpage is displayed in the WebView2 control, add an address bar to the sample app, as follows:
-
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 theMainWindow.xamlfile 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>
-
In
MainWindow.xaml.cs, copy the following code intomyButton_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. } }
-
Select File > Save All (
Ctrl+Shift+S) to save the project. -
Press F5 to build and run the project.
-
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: -
Enter an incomplete URL in the address bar, such as
bing.com, and then click the Go button.An
ArgumentExceptionexception is thrown, because the URL doesn't start withhttp://orhttps://. -
Close the sample app. The following dialog boxes might appear:
-
These debugger dialog boxes are a known bug. Click the OK button, and then click the Cancel button to close the dialog boxes.
In this section, you add code to import the WebView2 Core library.
-
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:
NavigationStartingSourceChangedContentLoadingHistoryChangedNavigationCompleted
If an HTTP redirect occurs, there are multiple
NavigationStartingevents 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:
SourceChangedContentLoadingHistoryChanged
As an example of how to use the events, register a handler for
NavigationStartingthat cancels any non-HTTPS requests, as follows: -
In
MainWindow.xaml.cs, modify the constructor to register theEnsureHttpsmethod:public MainWindow() { this.InitializeComponent(); MyWebView.NavigationStarting += EnsureHttps; }
-
In
MainWindow.xaml.cs, below the constructor, add the followingEnsureHttpsmethod:private void EnsureHttps(WebView2 sender, CoreWebView2NavigationStartingEventArgs args) { String uri = args.Uri; if (!uri.StartsWith("https://")) { args.Cancel = true; } else { addressBar.Text = uri; } }
-
Select File > Save All (
Ctrl+Shift+S) to save the project. -
Press F5 to build and run the project.
-
Enter an HTTP URL, such as
http://bing.com.Navigation is blocked to HTTP sites.
-
Enter an HTTPS URL, such as
https://bing.com.Navigation is allowed for HTTPS sites.
-
Close the sample app. The following dialog boxes might appear:
-
These debugger dialog boxes are a known bug. Click the OK button, and then click the Cancel button to close the dialog boxes.
The WinRT CoreWebView2 object might not be available with the release of the WebView2 API. For a list of available APIs, see:
- WinUI 3 API Reference (Windows App SDK) - Microsoft.UI.Xaml.Controls.WebView2 Class - in API reference for Windows desktop apps > WinRT APIs.
- The WebView2 Spec
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.
-
Modify the
EnsureHttpsfunction 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; } }
-
Select File > Save All (
Ctrl+Shift+S) to save the project. -
Press F5 to build and run the project.
-
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
uriis not safe:
Congratulations, you built your first WebView2 app!
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.
The following interfaces aren't accessible in WinUI 3:
ICoreWebView2EnvironmentICoreWebView2EnvironmentOptionsandICoreWebView2EnvironmentOptions2ICoreWebView2ControllerOptions
WinUI 3 API Reference (Windows App SDK):
- Microsoft.UI.Xaml.Controls.WebView2 Class - in API reference for Windows desktop apps > WinRT APIs.
All platforms/languages:
- WebView2 API Reference - API Reference for each platform.
developer.microsoft.com:
- Microsoft Edge WebView2 - initial introduction to WebView2 features at developer.microsoft.com.
Local pages:
- Introduction to Microsoft Edge WebView2 - overview of features.
- See also in Introduction to Microsoft Edge WebView2.
- Manage user data folders
- Sample Code for WebView2 - a guide to the
WebView2Samplesrepo. - Development best practices for WebView2 appsDevelopment best practices
GitHub:
- Getting Started with WebView2 in WinUI3
- Spec: The WebView2 Xaml control - the WinUI 3.0 version of the WebView2 control.
- microsoft-ui-xaml repo > Issues - to enter WinUI-specific feature requests or bugs.







