Get started with WebView2 in WPF apps
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.
- Corresponding Get Started sample at GitHub: Getting Started with WebView2 in WPF (WPF_GettingStarted/WPFSample.sln)
Step 1 - Install Visual Studio
This tutorial requires Microsoft Visual Studio, not Microsoft Visual Studio Code.
- Install Visual Studio 2017 or later. You can accept the defaults.
Step 2 - Install a preview channel of Microsoft Edge
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.
Step 3 - Create a single-window WebView2 app
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 App
search 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.
Step 4 - Install the WebView2 SDK
Use NuGet to add the WebView2 SDK to the project.
In Solution Explorer, right-click the project name, and then select Manage NuGet Packages:
(The above image is supposed to show the WPF project instead of the WinForms project.)
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:
Step 5 - Create a single WebView2 control
Add a WebView2 control to your app.
In the
MainWindow.xaml
file, 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.xaml
looks 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. TheSource
property 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:
Step 6 - Navigation
Enable users to change the URL that the WebView2 control displays, by adding an address bar to the app.
In the
MainWindow.xaml
file, 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.xaml
file 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 theCoreWebView2
namespace, insert the following code at the top of the file:using Microsoft.Web.WebView2.Core;
In the
MainWindow.xaml.cs
file, copy the following code to create theButtonGo_Click
method. 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 MainWIndow
declaration, 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
ArgumentException
if the URL doesn't start withhttp://
orhttps://
.The sample app displays the Bing website with the URL
https://www.bing.com
in the address bar:
Step 7 - Navigation events
During webpage navigation, the WebView2 control raises events. The app that hosts WebView2 controls listens for the following events:
NavigationStarting
SourceChanged
ContentLoading
HistoryChanged
NavigationCompleted
The above diagram shows the event sequence. Navigation events start with a new document.
Success path
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.
Failure path
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:
SourceChanged
ContentLoading
HistoryChanged
Redirection
If an HTTP redirect occurs, there are multiple NavigationStarting
events in a row.
Example demonstrating navigation events
To demonstrate how to use the events, register a handler for NavigationStarting
that cancels any non-HTTPS requests, as follows.
In the
MainWindow.xaml.cs
file, modify the constructor to match the top part of the following code. Below the constructor, add theEnsureHttps
function: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,
EnsureHttps
is registered as the event handler on theNavigationStarting
event 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.
Step 8 - 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:
- 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
EnsureHttps
function 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.
Step 9 - Communication between host and web content
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 registeredWebMessageReceived
on the host.Hosts post messages to web content in a WebView2 control using
CoreWebView2.PostWebMessageAsString
orCoreWebView2.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 anInitializeAsync
function to match the following code. TheInitializeAsync
function awaits EnsureCoreWebView2Async, because the initialization ofCoreWebView2
is 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
, updateInitializeAsync
and addUpdateAddressBar
using 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
CoreWebView2
is 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
, updateInitializeAsync
to 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!
See also
developer.microsoft.com:
- Microsoft Edge WebView2 - initial introduction to WebView2 features at developer.microsoft.com.
Local pages:
- WebView2 sample: WPF .NET browser app
- Manage user data folders
- Sample Code for WebView2 - a guide to the
WebView2Samples
repo. - Development best practices for WebView2 apps
- See also in Introduction to Microsoft Edge WebView2.
API Reference:
GitHub:
- WebView2Samples repo - a comprehensive example of WebView2 capabilities.
Feedback
Submit and view feedback for