| title | Get started with WebView2 in WPF apps |
|---|---|
| description | Get started guide with WebView2 for Windows Presentation Foundation (WPF) apps. |
| author | MSEdgeTeam |
| ms.author | msedgedevrel |
| ms.topic | conceptual |
| ms.prod | microsoft-edge |
| ms.technology | webview |
| ms.date | 04/27/2022 |
This article covers how to set up your development tools and create an initial WebView2 app for Windows Presentation Foundation (WPF), and learn about WebView2 concepts along the way.
In this tutorial, you use the WPF Application or WPF App (.NET Framework) project template to create a WPF app, and then install the WebView2 SDK for the project to add WebView2.
A completed version of this tutorial project is available in the WebView2Samples repo:
- Sample name: WPF_GettingStarted
- Repo directory: WPF_GettingStarted
- Solution file: WPFSample.sln
This tutorial requires Microsoft Visual Studio, not Microsoft Visual Studio Code.
- Install Visual Studio 2017 or later. You can accept the defaults.
-
Download any Microsoft Edge Insider (preview) Channel (Beta, Dev, or Canary) on a supported operating system (OS):
- Windows 7
- Windows 8.1
- Windows 10
- Windows 11
We recommend using the Canary channel of Microsoft Edge. The minimum required version is 82.0.488.0.
Start with a basic desktop project that contains a single main window.
-
Open Microsoft Visual Studio.
-
In the opening panel click Create new project. Or, in the main Visual Studio window, select File > New > Project.
-
Search for
WPF App.The Create a new project panel shows filtered results for
WPF Appsearch results. -
Click either the WPF Application card (shown first below) to use .NET Core/5/6, or the WPF App (.NET Framework) card (shown second below) to use .NET Framework, and then click Next:
The highlighted card in the following image is WPF Application: .NET Core WPF Application:
Alternatively, the highlighted card in the following image is WPF App (.NET Framework): Windows Presentation Foundation client application:
The Configure your new project WPF application dialog box appears.
-
Enter values for Project name and Location, and then click Next.
The Additional information dialog box appears, with a Target Framework dropdown list:
-
Select .NET Core 3.1, 5.0, 6.0, or later (not 3.0). Then click Next.
The Configure your new project dialog box appears, for WPF App (.NET framework):
-
Enter values for Project name and Location.
-
In the Framework dropdown list, select .NET Framework 4.6.2 or later.
-
Click the Create button.
Visual Studio creates the project.
Use NuGet to add the WebView2 SDK to the project.
-
In Solution Explorer, right-click the project name (not the solution node), and then select Manage NuGet Packages. The NuGet Package Manager window opens.
-
In the upper left, click the Browse tab. In the search bar, type
Microsoft.Web.WebView2, then click the Microsoft.Web.WebView2 card.The NuGet package manager dialog box displays search results, including a Microsoft.Web.WebView2 card. The dialog box has a version number and Install button.
-
Accept the default version, and then click the Install button.
-
In the Preview Changes dialog box, click OK.
-
Select File > Save All to save the project.
-
Press F5 to build and run the project.
The project runs, and displays an empty window. This verifies that WebView2 is installed and working, although WebView2 has no content to display yet:
Add a WebView2 control to your app.
-
In the
MainWindow.xamlfile, to add the WebView2 XAML namespace, insert the following line inside the<Window/>tag:xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
-
Make sure the code in
MainWindow.xamllooks like the following code:<Window x:Class="WPF_Getting_Started.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:local="clr-namespace:{YOUR PROJECT NAME}" xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf" mc:Ignorable="d" Title="MainWindow" Height="450" Width="800" > <Grid> </Grid> </Window>
-
To add the WebView2 control, replace the
<Grid>tags with the following code. TheSourceproperty sets the initial URI displayed in the WebView2 control.<DockPanel> <wv2:WebView2 Name="webView" Source="https://www.microsoft.com" /> </DockPanel>
-
Select File > Save All to save the project.
-
Press F5 to build and run the project.
-
Make sure your WebView2 control displays https://www.microsoft.com:
Enable users to change the URL that the WebView2 control displays, by adding an address bar to the app.
-
In the
MainWindow.xamlfile, add an address bar by copying and pasting the following code inside the<DockPanel>that contains the WebView2 control. Keep the existing code below the new snippet.<DockPanel DockPanel.Dock="Top"> <Button x:Name="ButtonGo" DockPanel.Dock="Right" Click="ButtonGo_Click" Content="Go" /> <TextBox Name="addressBar"/> </DockPanel>
-
Make sure the
<DockPanel>section of theMainWindow.xamlfile matches the following code:<DockPanel> <DockPanel DockPanel.Dock="Top"> <Button x:Name="ButtonGo" DockPanel.Dock="Right" Click="ButtonGo_Click" Content="Go"/> <TextBox Name = "addressBar"/> </DockPanel> <wv2:WebView2 Name = "webView" Source = "https://www.microsoft.com" /> </DockPanel>
-
In
MainWindow.xaml.cs, to add theCoreWebView2namespace, insert the following code at the top of the file:using Microsoft.Web.WebView2.Core;
-
In the
MainWindow.xaml.csfile, copy the following code to create theButtonGo_Clickmethod. This code navigates the WebView2 control to the URL entered in the address bar.private void ButtonGo_Click(object sender, RoutedEventArgs e) { if (webView != null && webView.CoreWebView2 != null) { webView.CoreWebView2.Navigate(addressBar.Text); } }
-
Paste the code directly after the
Public MainWIndowdeclaration, as shown in the following code:namespace WpfApp1 { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } void ButtonGo_Click(object sender, RoutedEventArgs e) { if (webView != null && webView.CoreWebView2 != null) { webView.CoreWebView2.Navigate(addressBar.Text); } } } }
-
Select File > Save All to save the project.
-
Press F5 to build and run the project.
-
Type a new URL in the address bar and choose Go. For example, type
https://www.bing.com. -
Make sure the WebView2 control opens the URL you entered.
Make sure you enter a complete URL in the address bar. The app generates an
ArgumentExceptionif the URL doesn't start withhttp://orhttps://.The sample app displays the Bing website with the URL
https://www.bing.comin the address bar:
During webpage navigation, the WebView2 control raises events. The app that hosts WebView2 controls listens for the following events:
NavigationStartingSourceChangedContentLoadingHistoryChangedNavigationCompleted
The above diagram shows the event sequence. Navigation events start with a new document.
A successful path includes the full sequence of events:
- Navigation starting.
- Source changed, with possible input from the same document.
- Content loading.
- History changes.
- Navigation completed.
For more information, see Navigation events for WebView2 apps.
If theres a failure, the failure path proceeds directly from navigation starting, to navigation completed, skipping the intervening events.
When an error occurs, the following events are raised, and may depend on navigation to an error webpage:
SourceChangedContentLoadingHistoryChanged
If an HTTP redirect occurs, there are multiple NavigationStarting events in a row.
To demonstrate how to use the events, register a handler for NavigationStarting that cancels any non-HTTPS requests, as follows.
-
In the
MainWindow.xaml.csfile, modify the constructor to match the top part of the following code. Below the constructor, add theEnsureHttpsfunction:public MainWindow() { InitializeComponent(); webView.NavigationStarting += EnsureHttps; } void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args) { String uri = args.Uri; if (!uri.StartsWith("https://")) { args.Cancel = true; } }
In the constructor,
EnsureHttpsis registered as the event handler on theNavigationStartingevent on the WebView2 control. -
Select File > Save All to save the project.
-
Press F5 to build and run the project.
-
Attempt to open an HTTP site. Make sure the WebView2 control remains unchanged.
-
Attempt to open an HTTPS site. The WebView2 control allows you to open HTTPS sites.
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:
- Run it after the creation of the global object.
- Run it before any other script included in the HTML document is run.
For example, add scripts that send an alert when a user navigates to non-HTTPS sites, as follows:
-
Modify the
EnsureHttpsfunction to inject a script into the web content that uses ExecuteScriptAsync method.void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args) { String uri = args.Uri; if (!uri.StartsWith("https://")) { webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')"); args.Cancel = true; } }
-
Select File > Save All to save the project.
-
Press F5 to build and run the project.
-
Make sure the app displays an alert when you navigate to a website that doesn't use HTTPS.
The host and web content can communicate in the following ways using postMessage:
-
Web content in a WebView2 control can post a message to the host using
window.chrome.webview.postMessage. The host handles the message using any registeredWebMessageReceivedon the host. -
Hosts post messages to web content in a WebView2 control using
CoreWebView2.PostWebMessageAsStringorCoreWebView2.PostWebMessageAsJSON. The messages are caught by handlers added towindow.chrome.webview.addEventListener.
The communication mechanism passes messages from web content to the host using native capabilities.
In your project, when the WebView2 control navigates to a URL, it displays the URL in the address bar and alerts the user of the URL displayed in the WebView2 control.
-
In
MainWindow.xaml.cs, update your constructor and create anInitializeAsyncfunction to match the following code. TheInitializeAsyncfunction awaits EnsureCoreWebView2Async, because the initialization ofCoreWebView2is asynchronous.public MainWindow() { InitializeComponent(); webView.NavigationStarting += EnsureHttps; InitializeAsync(); } async void InitializeAsync() { await webView.EnsureCoreWebView2Async(null); }
-
After CoreWebView2 is initialized, register an event handler to respond to
WebMessageReceived. InMainWindow.xaml.cs, updateInitializeAsyncand addUpdateAddressBarusing the following code:async void InitializeAsync() { await webView.EnsureCoreWebView2Async(null); webView.CoreWebView2.WebMessageReceived += UpdateAddressBar; } void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args) { String uri = args.TryGetWebMessageAsString(); addressBar.Text = uri; webView.CoreWebView2.PostWebMessageAsString(uri); }
-
For the WebView2 control to send and respond to the web message, after
CoreWebView2is initialized, the host does the following:- Injects a script to the web content that registers a handler to print message from the host.
- Injects a script to the web content that posts the URL to the host.
-
In
MainWindow.xaml.cs, updateInitializeAsyncto match the following code:async void InitializeAsync() { await webView.EnsureCoreWebView2Async(null); webView.CoreWebView2.WebMessageReceived += UpdateAddressBar; await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);"); await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));"); }
-
Select File > Save All to save the project.
-
Press F5 to build and run the project.
-
When you open a new URI, the WebView2 control displays the URI in the address bar.
The sample app displays the URI in the address bar and the Microsoft website, https://www.microsoft.com:
Congratulations, you built your first WebView2 app!
developer.microsoft.com:
- Microsoft Edge WebView2 - initial introduction to WebView2 features at developer.microsoft.com.
Local pages:
- WPF sample app
- Manage user data folders
- Sample Code for WebView2 - a guide to the
WebView2Samplesrepo. - Development best practices for WebView2 apps
- See also in Introduction to Microsoft Edge WebView2.
API Reference:
GitHub:











