diff --git a/microsoft-edge/webview2/concepts/navigation-events.md b/microsoft-edge/webview2/concepts/navigation-events.md index 1b414be4c0..6cf840f84b 100644 --- a/microsoft-edge/webview2/concepts/navigation-events.md +++ b/microsoft-edge/webview2/concepts/navigation-events.md @@ -79,7 +79,7 @@ To monitor or cancel navigation events inside frames in a WebView2 instance, use For example code showing how to handle navigation events, see: * [Learn about navigation events](../get-started/winui2.md#learn-about-navigation-events) in _Get started with WebView2 in WinUI 2 (UWP) apps_ - no example code in the article; see other frameworks' articles. -* [Step 5 - Navigation events](../get-started/winui.md#step-5---navigation-events) in _Get started with WebView2 in WinUI 3 (Windows App SDK) apps_. +* [Step 8 - Handle navigation events](../get-started/winui.md#step-8-handle-navigation-events) in _Get started with WebView2 in WinUI 3 (Windows App SDK) apps_. * [Step 7 - Navigation events](../get-started/wpf.md#step-7---navigation-events) in _Get started with WebView2 in WPF apps_. * [Step 8 - Navigation events](../get-started/winforms.md#step-8---navigation-events) in _Get started with WebView2 in WinForms apps_. * [Step 13 - Navigation events](../get-started/win32.md#step-13---navigation-events) in _Get started with WebView2 in Win32 apps_. diff --git a/microsoft-edge/webview2/get-started/get-started.md b/microsoft-edge/webview2/get-started/get-started.md index 719d96a3a9..8cbe052586 100644 --- a/microsoft-edge/webview2/get-started/get-started.md +++ b/microsoft-edge/webview2/get-started/get-started.md @@ -15,7 +15,7 @@ These articles cover how to set up your development tools and create an initial | Article | Completed project | Description | |---|---|---| | [Get started with WebView2 in WinUI 2 (UWP) apps](winui2.md) | [WinUI2_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinUI2_GettingStarted) | Use **C# Blank App (Universal Windows)** project template and install the **Microsoft.UI.Xaml** package (WinUI 2), which installs the **Microsoft.Web.WebView2** SDK package as a dependency. | -| [Get started with WebView2 in WinUI 3 (Windows App SDK) apps](winui.md) | [WinUI3_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinUI3_GettingStarted) | Use the **Blank App, Packaged (WinUI in Desktop)** project template, which uses the WindowsAppSDK, which includes the WebView2 SDK. Add an address bar and URL logic. | +| [Get started with WebView2 in WinUI 3 (Windows App SDK) apps](winui.md) | [WinUI3GetStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinUI3_GettingStarted) | Use the **Blank App, Packaged (WinUI 3 in Desktop)** Visual Studio project template, which uses the WindowsAppSDK, which includes the WebView2 SDK. You add a WebView2 control, an Address bar and **Go** button, and URL logic to only allow navigating to HTTPS URLs. | | [Get started with WebView2 in WPF apps](wpf.md) | [WPF_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WPF_GettingStarted) | 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. | | [Get started with WebView2 in WinForms apps](winforms.md) | [WinForms_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinForms_GettingStarted) | Use the **C# Windows Forms App (.NET Framework)** project template to create a WinForms project, then install the **Microsoft.Web.WebView2** SDK package for the WinForms project. | | [Get started with WebView2 in Win32 apps](win32.md) | [Win32_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) | Starts by opening an existing Win32 app project that has the WebView2 SDK and code already added. | diff --git a/microsoft-edge/webview2/get-started/winui-images/blank-winui3-app.png b/microsoft-edge/webview2/get-started/winui-images/blank-winui3-app.png index 9177ca8b28..6eb1d57360 100644 Binary files a/microsoft-edge/webview2/get-started/winui-images/blank-winui3-app.png and b/microsoft-edge/webview2/get-started/winui-images/blank-winui3-app.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/config-new-proj.png b/microsoft-edge/webview2/get-started/winui-images/config-new-proj.png index bc331088a1..9206c29c2a 100644 Binary files a/microsoft-edge/webview2/get-started/winui-images/config-new-proj.png and b/microsoft-edge/webview2/get-started/winui-images/config-new-proj.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/create-project-winui3-desktop.png b/microsoft-edge/webview2/get-started/winui-images/create-project-winui3-desktop.png index 02c2222eb9..765be5c864 100644 Binary files a/microsoft-edge/webview2/get-started/winui-images/create-project-winui3-desktop.png and b/microsoft-edge/webview2/get-started/winui-images/create-project-winui3-desktop.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/enable-developer-mode.png b/microsoft-edge/webview2/get-started/winui-images/enable-developer-mode.png new file mode 100644 index 0000000000..8f6b5d2c9c Binary files /dev/null and b/microsoft-edge/webview2/get-started/winui-images/enable-developer-mode.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/finished-app.png b/microsoft-edge/webview2/get-started/winui-images/finished-app.png new file mode 100644 index 0000000000..1792c884c7 Binary files /dev/null and b/microsoft-edge/webview2/get-started/winui-images/finished-app.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/getting-started-bing.png b/microsoft-edge/webview2/get-started/winui-images/getting-started-bing.png index 43d17785af..4c942b1113 100644 Binary files a/microsoft-edge/webview2/get-started/winui-images/getting-started-bing.png and b/microsoft-edge/webview2/get-started/winui-images/getting-started-bing.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/getting-started-part-3.png b/microsoft-edge/webview2/get-started/winui-images/getting-started-part-3.png index 47b59a0c62..6a46d2bc27 100644 Binary files a/microsoft-edge/webview2/get-started/winui-images/getting-started-part-3.png and b/microsoft-edge/webview2/get-started/winui-images/getting-started-part-3.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/getting-started-script.png b/microsoft-edge/webview2/get-started/winui-images/getting-started-script.png deleted file mode 100644 index f01b150e8d..0000000000 Binary files a/microsoft-edge/webview2/get-started/winui-images/getting-started-script.png and /dev/null differ diff --git a/microsoft-edge/webview2/get-started/winui-images/installer-winappsdk.png b/microsoft-edge/webview2/get-started/winui-images/installer-winappsdk.png new file mode 100644 index 0000000000..574469577c Binary files /dev/null and b/microsoft-edge/webview2/get-started/winui-images/installer-winappsdk.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/new-winui3-project.png b/microsoft-edge/webview2/get-started/winui-images/new-winui3-project.png index db6489997d..a54583943b 100644 Binary files a/microsoft-edge/webview2/get-started/winui-images/new-winui3-project.png and b/microsoft-edge/webview2/get-started/winui-images/new-winui3-project.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/nuget-install-winappsdk.png b/microsoft-edge/webview2/get-started/winui-images/nuget-install-winappsdk.png new file mode 100644 index 0000000000..4fe821938d Binary files /dev/null and b/microsoft-edge/webview2/get-started/winui-images/nuget-install-winappsdk.png differ diff --git a/microsoft-edge/webview2/get-started/winui-images/nuget-installed-tab.png b/microsoft-edge/webview2/get-started/winui-images/nuget-installed-tab.png new file mode 100644 index 0000000000..888ac06286 Binary files /dev/null and b/microsoft-edge/webview2/get-started/winui-images/nuget-installed-tab.png differ diff --git a/microsoft-edge/webview2/get-started/winui.md b/microsoft-edge/webview2/get-started/winui.md index e32c0bbe5b..86e2d7c427 100644 --- a/microsoft-edge/webview2/get-started/winui.md +++ b/microsoft-edge/webview2/get-started/winui.md @@ -6,131 +6,242 @@ ms.author: msedgedevrel ms.topic: conceptual ms.service: microsoft-edge ms.subservice: webview -ms.date: 04/08/2024 +ms.date: 11/01/2024 --- # 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. +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. You first use the **Blank App, Packaged (WinUI 3 in Desktop)** Visual Studio project template, which uses the WindowsAppSDK, which includes the WebView2 SDK. You then add a WebView2 control, an Address bar and **Go** button, and URL logic to only allow navigating to HTTPS URLs. -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. -![App displaying the Bing website](winui-images/getting-started-bing.png) +In this tutorial, you do the following: + +1. Set up the development environment. + +1. Use the **Blank App, Packaged (WinUI 3 in Desktop)** Visual Studio project template to create a blank WinUI 3 project, which defines an app that contains a button. + +1. Add a WebView2 control instead of the button, and initially navigate to the Microsoft homepage. WebView2 is supported because the project template uses the **Microsoft.WindowsAppSDK** NuGet package, which includes the WebView2 SDK. + +1. Add an Address bar as a text box control, and then use the entered HTTPS string to navigate to a new webpage: + + ![The app, after navigating to the Bing HTTPS address](./winui-images/getting-started-bing.png) + +1. Insert JavaScript into the WebView2 control, to display a warning alert (dialog) when the user tries to navigate to a URL that has only an `http://` prefix instead of `https://`: + + ![The app's WebView2 control displays an alert dialog for non-HTTPS websites](./winui-images/finished-app.png) #### Completed project -A completed version of this tutorial project (as of 2020) is available in the **WebView2Samples** repo: +A completed version of this tutorial project is available in the **WebView2Samples** repo: -* Sample name: **WinUI3_GettingStarted** +* Sample name: **WinUI3GetStarted** * Repo directory: [WinUI3_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinUI3_GettingStarted) -* Solution file: **WinUI_Sample.sln** +* Solution file: **WinUI3GetStarted.sln** + + + +## Step 1: Install the latest Visual Studio 2022 -The present tutorial is updated and only creates a single project, not a second, "(Package)" project like in 2020. +Make sure that Visual Studio 2022 is installed and up-to-date. + +To install the latest Visual Studio 2022: + +1. Go to [Visual Studio: IDE and Code Editor for Software Developers and Teams](https://visualstudio.microsoft.com), and then in the **Visual Studio 2022** section, click the **Download** button, and then select **Community 2022** or another version. + +1. In the **Downloads** popup in the upper right of Microsoft Edge, `VisualStudioSetup.exe` is listed. Click **Open file**. + + Visual Studio Installer opens. + +1. Follow the prompts, and accept the defaults. You'll install or update a workload and a component of a workload in the next step. -## Step 1 - Install Visual Studio and the Windows App SDK +## Step 2: Install the latest Windows App SDK + +Make sure that the latest Windows App SDK is installed in Visual Studio 2022. The Windows App SDK includes Visual Studio project templates, and includes the WebView2 SDK. These project templates include the **Blank App, Packaged (WinUI 3 in Desktop)** project template, which uses the WindowsAppSDK, including the WebView2 SDK. + +The Windows App SDK is installed as the **Windows App SDK C# Templates** component of the **.NET Desktop Development** workload for Visual Studio. Before Visual Studio 2022 version 17.1, the Windows App SDK was instead installed as a Visual Studio extension, as explained in [Install tools for the Windows App SDK](/windows/apps/windows-app-sdk/set-up-your-development-environment). + + +To install the latest Visual Studio 2022 the latest 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 Windows, press the **Start** key, and then type **Visual Studio 2022**. -1. In a new window or tab, open the page [Install tools for the Windows App SDK](/windows/apps/windows-app-sdk/set-up-your-development-environment) and then follow the steps on that page, to install Microsoft Visual Studio, such as Visual Studio 2022. - + The Visual Studio 2022 app is listed. -1. If needed, in a new window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. +1. Click **Open**. -Return from that page and continue the steps below. + The **Visual Studio 2022** dialog opens, with sections including **Open recent** and **Get started**. -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. +1. Click **Continue without code**. + + Visual Studio opens. + +1. In the **Tools** menu, select **Get Tools and Features**. + + The **Visual Studio Installer** window opens. + +1. Make sure the **Workloads** tab is selected. + +1. In the **Desktop & Mobile** section, select the card for the **.NET desktop development** workload, so that a checkmark appears: + + !["Windows App SDK C# Templates" component checkbox of ".NET desktop development" workload in Visual Studio Installer](./winui-images/installer-winappsdk.png) + +1. In the **Installation details** tree on the right, in **.NET desktop development** > **Optional**, select the checkbox for the **Windows App SDK C# Templates** component, near the bottom of the tree. + +1. Click the **Modify** button. + + The **User Account Control** dialog opens. + +1. Click the **Yes** button. + + You're prompted to close Visual Studio. + +1. Click the **Continue** button (assuming you have no unsaved work). + + Visual Studio downloads and installs the latest **Windows App SDK C# Templates** component. In the **Visual Studio Installer** window, a message says **All installations are up to date**, and Visual Studio 2022 opens. -## Step 2 - Create a blank WinUI 3 project +## Step 3: Create a blank WinUI 3 project + +Next, create a project that's a basic WebView2 app for WinUI 3 (Windows App SDK). This desktop app will contain a single main window. The project won't contain any WebView2 code yet. -To create a WebView2 app, start by creating a basic desktop project, to create a desktop app that contains a single main window: +To create a WebView2 app for WinUI 3 (Windows App SDK): -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. +1. If Visual Studio is running, select **File** > **New** > **Project**. The **Create a new project** dialog opens. - Or, if Visual Studio is running, select **File** > **New** > **Project**. The **Create a new project** dialog opens. +1. If Visual Studio 2022 is not running: - **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](/windows/apps/get-started/enable-your-device-for-development), at _Build desktop apps for Windows_. + 1. In Windows, press the **Start** key, and then type **Visual Studio 2022**. -1. In the **Create a new project** dialog, in the **Search for templates** field, enter **WinUI 3 in Desktop**: + The Visual Studio 2022 app is listed. - ![Searching on "WinUI 3 in Desktop" to create a new project](winui-images/create-project-winui3-desktop.png) + 1. Click **Open**. -1. Click the **Blank App, Packaged (WinUI in Desktop)** card to select it, and then click the **Next** button. + The **Visual Studio 2022** startup dialog opens, with sections including **Open recent** and **Get started**. - If **WinUI** templates aren't listed, you need to install project templates as mentioned above, from [Install tools for the Windows App SDK](/windows/apps/windows-app-sdk/set-up-your-development-environment). Additional tips to get the template to appear: + 1. In the **Get started** section, click the **Create a new project** card. The **Create a new project** window opens. - After installing "default" options for Visual Studio 2022 Community edition, in Visual Studio Installer, click the **.NET** card, then on the right, select the checkbox **Windows App SDK C# Templates**. +1. In the **Create a new project** window, in the **Search for templates** field, enter **WinUI 3 in Desktop**: - If the correct project template still doesn't appear: in the Visual Studio Installer, click the **UWP** card to select it, select the **v143 C++ tools** checkbox on the right, and then click the **Modify** button. + ![Searching on "WinUI 3 in Desktop" to create a new project](./winui-images/create-project-winui3-desktop.png) + + The project templates that were installed in the previous major step are listed. + +1. Click the **Blank App, Packaged (WinUI 3 in Desktop)** card to select it, and then click the **Next** button. The **Configure your new project** dialog appears. -1. In the **Project name** text box, enter a project name, such as **MyWebView2WinUI3**: +1. In the **Project name** text box, enter a project name, such as **WinUI3GetStarted**: - ![The 'Configure your new project' dialog](winui-images/config-new-proj.png) + ![The 'Configure your new project' dialog](./winui-images/config-new-proj.png) -1. In the **Location** text box, enter or navigate to a location, such as `C:\Users\username\Documents\WebView2`. +1. In the **Location** text box, enter or navigate to a directory, such as `C:\Users\myUsername\source\`. 1. Click the **Create** button. - The new WinUI 3 project opens in Solution Explorer in Visual Studio: + The project is created: - ![The new WinUI 3 project in Solution Explorer](winui-images/new-winui3-project.png) + ![The new WinUI 3 project in Solution Explorer](./winui-images/new-winui3-project.png) - * The `App.xaml.cs` file defines an `Application` class that represents your app instance. +1. If a dialog appears, saying "Failed to install the Microsoft.WindowsAppSDK package", click the **OK** button. - * 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. -1. In the **Solution Configurations** dropdown list (in the middle of the top of the window), select **Debug**. + +## Step 4: Update or install the Windows App SDK -1. In the **Solution Platforms** dropdown list, select a platform, such as **x64**. +When you create a new project in Visual Studio, check the status of the solution's NuGet packages. Make sure the needed NuGet packages were installed by the project template, and make sure the packages have been updated, so that the project has the latest features and fixes. -1. Select **File** > **Save All** (**Ctrl+Shift+S**) to save the project. +To update or install the latest Windows App SDK NuGet package for your project: -1. Press **F5** to build and run the project. The blank WinUI Desktop app opens, with no WebView2 control added yet: +1. In Visual Studio, in Solution Explorer, right-click the **WinUI3GetStarted** project, and then select **Manage NuGet Packages**. - ![The new blank WinUI 3 app](winui-images/blank-winui3-app.png) + In Visual Studio, the **NuGet: WinUI3GetStarted** tab opens. If the **Microsoft.WindowsAppSDK** package has been installed during project creation using the project template, the **Installed** tab is selected, and that package is listed: -1. Close the app. + ![Expected packages listed in Installed tab of NuGet tab](./winui-images/nuget-installed-tab.png) + If the **Microsoft.WindowsAppSDK** package is not listed in the **Installed** tab: - -#### Updating target version numbers +1. Click the **Browse** tab, and then in the **Search** text box, enter **Microsoft.WindowsAppSDK**. -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. +1. Select the **Microsoft.WindowsAppSDK** card: -```xml - net6.0-windows10.0.19041.0 - 10.0.17763.0 -``` + ![Installing the SDK package](./winui-images/nuget-install-winappsdk.png) + +1. Click the **Install** button, to the right. + + The **Preview Changes** dialog opens. + +1. Click the **Apply** button, and then accept the license terms. -The above values represent: -* **Target version**: **Windows 10, version 2004 (build 19041)** or later. -* **Minimum version**: **Windows 10, version 1809 (build 17763)**. + The **Microsoft.WindowsAppSDK** NuGet package is installed. + +1. In the **NuGet - Solution** tab, click the **Updates** tab, and then optionally update any packages that are listed there. + +1. Close the **NuGet - Solution** tab. -## Step 3 - Add a WebView2 control +## Step 5: Build and run the project + +The new WinUI 3 project remains opens in Solution Explorer in Visual Studio: + +![The new WinUI 3 project in Solution Explorer](./winui-images/new-winui3-project.png) + +* 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 that's displayed by your app instance. The classes derive from types in the `Microsoft.UI.Xaml` namespace of WinUI. + + +To build and run the project: + +1. Select **File** > **Save All** (**Ctrl+Shift+S**). + +1. Select **Debug** > **Start** (**F5**). + + The **Enable Developer Mode for Windows** dialog might open: + + ![Dialog: Enable Developer Mode for Windows](./winui-images/enable-developer-mode.png) + +1. If that dialog appears, click **settings for developers**, turn on the **Developer Mode** toggle, click the **Yes** button, and then click the **Close** button of the Visual Studio dialog. For more information about Developer Mode, see [Enable your device for development](/windows/apps/get-started/enable-your-device-for-development), at _Build desktop apps for Windows_. + + The project builds. The blank WinUI Desktop app opens, with no WebView2 control added yet: -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. + ![The new blank WinUI 3 app](./winui-images/blank-winui3-app.png) -Edit the `MainWindow.xaml` and `MainWindow.xaml.cs` files to add a WebView2 control to the blank WinUI 3 app project, as follows: +1. Click the **Click Me** button. -1. In Visual Studio, in Solution Explorer, double-click `MainWindow.xaml` to open it in the code editor. + The button label changes to **Clicked**. -1. Add the WebView2 XAML namespace by inserting the following attribute inside the `` start tag: +1. Close the app. + + + +## Step 6: Add a WebView2 control + +The project is based on the project template **Blank App, Packaged (WinUI 3 in Desktop)**, which uses the **Microsoft.WindowsAppSDK** NuGet package, which includes the WebView2 SDK. So we can add WebView2 code. You'll edit the `MainWindow.xaml` and `MainWindow.xaml.cs` files to add a WebView2 control to the blank WinUI 3 app project, initially loading the Microsoft home page. In the XAML file, the WebView control will be tagged like: + +`` + + +To add a WebView2 control that initially navigates to the Microsoft home page: + +1. In Visual Studio, in Solution Explorer, double-click `MainWindow.xaml`. + + The file opens in the code editor. + +1. Copy and paste the following attribute inside the `` start tag, at the end of the list of XML namespaces: ```xml xmlns:controls="using:Microsoft.UI.Xaml.Controls" ``` - - Make sure your code in `MainWindow.xaml` is similar to the following: + + That code adds the WebView2 XAML namespace. Make sure your code in `MainWindow.xaml` is similar to the following: ```xml + - + ``` - -1. To add the WebView2 control, replace the entire `` element with the following `` code. The `Source` property, near the bottom, sets the initial URI that's displayed in the WebView2 control (`https://www.microsoft.com`): + +1. Delete the `` element (three lines). + +1. Above the `` end tag, paste the following `` element: ```xml - @@ -159,60 +272,44 @@ Edit the `MainWindow.xaml` and `MainWindow.xaml.cs` files to add a WebView2 cont - + - + Source="https://www.microsoft.com" HorizontalAlignment="Stretch" + VerticalAlignment="Stretch"/> ``` - -1. In Solution Explorer, expand `MainWindow.xaml` and then open `MainWindow.xaml.cs`. - -1. In `MainWindow.xaml.cs`, comment out the following line, as shown: - - ```csharp - // myButton.Content = "Clicked"; - ``` - -1. Select **File** > **Save All** (**Ctrl+Shift+S**) to save the project. -1. Press **F5**, to build and run the project. + This `` element contains a `` element named `MyWebView`, which has a `Source` attribute that sets the initial URI that's displayed in the WebView2 control (`https://www.microsoft.com`). When the app opens, it will initially display the Microsoft.com home page, in the WebView2 control. -1. The app is a WebView2 host app that includes the WebView2 control. The WebView2 control displays the website `https://www.microsoft.com`: +1. In Solution Explorer, expand `MainWindow.xaml` and then double-click `MainWindow.xaml.cs`. - ![The WebView2 control displaying the microsoft.com webpage](winui-images/getting-started-part-3.png) +1. In `MainWindow.xaml.cs`, delete the following line of C# code in the `myButton_Click` method: -1. Close the app. + ```csharp + myButton.Content = "Clicked"; + ``` + The method is empty for now. We'll use it for the Address bar's **Go** button later. - -#### WinAppSDK supports custom WebView2 environments +1. Select **File** > **Save All** (**Ctrl+Shift+S**). -WinAppSDK supports custom WebView2 environments, starting with WinAppSDK 1.5 ([1.5.0-experimental2](/windows/apps/windows-app-sdk/experimental-channel#version-15-experimental-150-experimental2)). For more information, see [WinUI3 WebView2 with a custom CoreWebView2Environment](https://github.com/microsoft/microsoft-ui-xaml/issues/6150). +1. Press **F5**. -To instantiate a custom WebView2 environment, initialize WebView2 with one of the overrides of `WebView2.EnsureCoreWebView2Async` (listed below), and pass in your custom `CoreWebView2Environment` (and, optionally, custom `CoreWebView2ControllerOptions`): + The project builds, and the app opens: -```csharp -public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment) -public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment, CoreWebView2ControllerOptions controllerOptions) -``` + ![The WebView2 control displaying the microsoft.com webpage](./winui-images/getting-started-part-3.png) -Also see the example code in [Disabling SmartScreen navigation](#disabling-smartscreen-navigation), below. - -API Reference: -* [WebView2.EnsureCoreWebView2Async](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.webview2.ensurecorewebview2async) -* [CoreWebView2ControllerOptions](/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2controlleroptions) -* [CoreWebView2Environment](/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environment) -* [CoreWebView2EnvironmentOptions](/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environmentoptions) + The app is a WebView2 host app that includes the WebView2 control. The WebView2 control initially displays the website `https://www.microsoft.com`. There's no Address bar text box or **Go** button yet. +1. Close the app. -## Step 4 - Add navigation controls +## Step 7: Add navigation controls -To allow users to control which webpage is displayed in the WebView2 control, add an address bar to the app, as follows: +To allow users to control which webpage is displayed in the WebView2 control, add an Address bar to the app, as follows: -1. In `MainWindow.xaml`, paste the following code inside the `` element that contains the `` element: +1. In `MainWindow.xaml`, paste the following code inside the `` element, above the `` element: ```xml @@ -223,7 +320,6 @@ To allow users to control which webpage is displayed in the WebView2 control, ad ```xml - @@ -232,17 +328,17 @@ To allow users to control which webpage is displayed in the WebView2 control, ad - + - + - + Source="https://www.microsoft.com" HorizontalAlignment="Stretch" + VerticalAlignment="Stretch"/> ``` -1. In `MainWindow.xaml.cs`, paste the following code into `myButton_Click`, overwriting the existing `myButton_Click` method (which is nearly empty). This code navigates the WebView2 control to the URL entered in the address bar. +1. In `MainWindow.xaml.cs`, paste the following `try/catch` block into the body of the `myButton_Click` method: ```csharp private void myButton_Click(object sender, RoutedEventArgs e) @@ -258,20 +354,24 @@ To allow users to control which webpage is displayed in the WebView2 control, ad } } ``` + + This code navigates the WebView2 control to the URL that the user enters in the Address bar, when the user clicks the **Go** button, by re-setting the value of the `MyWebView.Source` property, which is equivalent to the `Source` attribute of the `` element. -1. Select **File** > **Save All** (**Ctrl+Shift+S**) to save the project. +1. Select **File** > **Save All** (**Ctrl+Shift+S**). -1. Press **F5** to build and run the project. +1. Press **F5**. -1. Enter a new complete URL in the address bar, such as **https://www.bing.com**, and then click the **Go** button. + The project builds, and the app opens, initially showing the Microsoft home page. There's now an Address bar and a **Go** button. - The WebView2 control in the app displays the Bing website. The address bar displays the URL, such as `https://www.bing.com`: +1. Enter a new complete HTTPS URL in the Address bar, such as **https://www.bing.com**, and then click the **Go** button: - ![The app displays the Bing website](winui-images/getting-started-bing.png) + ![The app displays the Bing website](./winui-images/getting-started-bing.png) -1. Enter an incomplete URL in the address bar, such as `bing.com`, and then click the **Go** button. + The WebView2 control in the app displays the Bing website. The Address bar displays the URL, such as `https://www.bing.com`. - An `ArgumentException` exception is thrown, and appears after you close the app, because the URL doesn't start with `http://` or `https://`. +1. Enter an incomplete URL in the Address bar, such as `bing.com`, and then click the **Go** button. + + The WebView2 control doesn't attempt to navigate to that URL. An exception is thrown, because the URL doesn't start with `http://` or `https://`. In the `try` section, the `addressBar.Text` string doesn't start with `http://` or `https://`, yet the non-URI string is passed to the `Uri` constructor, which throws a `System.UriFormatException` exception. In Visual Studio, the **Output** pane displays "Exception thrown: 'System.UriFormatException' in System.Private.Uri.dll". The app continues running. 1. Close the app. @@ -281,38 +381,38 @@ maintenance link (keep) * [Navigation events for WebView2 apps](../concepts/navigation-events.md) - main copy; update it and then propagate/copy to these h2 sections: --> -## Step 5 - Navigation events +## Step 8: Handle navigation events -In this section, you add code to import the WebView2 Core library. +An app that hosts a WebView2 control listens for the following events: -1. In `MainWindow.xaml.cs`, add the following line at the top, above the other `using` statements: +* `NavigationStarting` +* `SourceChanged` +* `ContentLoading` +* `HistoryChanged` +* `NavigationCompleted` - ```csharp - using Microsoft.Web.WebView2.Core; - ``` +These events are raised by a WebView2 control during webpage navigation. If an HTTP redirect occurs, there are multiple `NavigationStarting` events in a row. For more information, see [Navigation events for WebView2 apps](../concepts/navigation-events.md). - Apps that host WebView2 controls listen for the following events that are raised by WebView2 controls during webpage navigation: +When an error occurs, the following events are raised, and an error webpage might be displayed: - * `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](../concepts/navigation-events.md). +* `SourceChanged` +* `ContentLoading` +* `HistoryChanged` - - When errors occur, the following events are raised, and an error webpage might be displayed: +In this section, you add code to import the WebView2 Core library, which handles navigation events to go to various types of URLs. - * `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: +To handle navigation events: -1. In `MainWindow.xaml.cs`, in the constructor, add the following `NavigationStarting` line, to register the `EnsureHttps` method: +1. In `MainWindow.xaml.cs`, add the following line at the top, above the other `using` statements: + + ```csharp + using Microsoft.Web.WebView2.Core; + ``` + + Register a handler for `NavigationStarting` that cancels any non-HTTPS requests: + +1. In `MainWindow.xaml.cs`, in the constructor, add the following `NavigationStarting` line: ```csharp public MainWindow() @@ -322,7 +422,9 @@ In this section, you add code to import the WebView2 Core library. } ``` -1. In `MainWindow.xaml.cs`, below the constructor, add the following `EnsureHttps` method: + That line registers the `EnsureHttps` method (added below) as a listener of the `NavigationStarting` event. + +1. Below the constructor, add the following `EnsureHttps` method: ```csharp private void EnsureHttps(WebView2 sender, CoreWebView2NavigationStartingEventArgs args) @@ -339,34 +441,43 @@ In this section, you add code to import the WebView2 Core library. } ``` -1. Select **File** > **Save All** (**Ctrl+Shift+S**) to save the project. +1. Select **File** > **Save All** (**Ctrl+Shift+S**). + +1. Press **F5**. -1. Press **F5** to build and run the project. + The project builds, and the app opens. 1. In the app, in the Address bar, enter an HTTP URL, such as `http://bing.com`, and then click the **Go** button. - Nothing happens, because navigation is blocked to HTTP sites, and we haven't yet added a dialog to provide feedback. + The app doesn't navigate to that page, because navigation is blocked to HTTP sites. We haven't yet added a dialog to tell the user why the displayed site didn't change. 1. Enter an HTTPS URL, such as `https://bing.com`, and then click the **Go** button. The app navigates to the specified page, because navigation is allowed for HTTPS sites. +1. In the app, in the Address bar, enter a string without a prefix, such as `bing.com`, and then click the **Go** button. + + The app doesn't navigate to that page. A `UriFormatException` exception is thrown, as before, and appears in the **Output** pane in Visual Studio. + 1. Close the app. -## Step 6 - Scripting +## Step 9: Insert JavaScript to alert the user about a non-HTTPS address -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: +You can use the host app to inject JavaScript code into the WebView2 control 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 +Below, you add JavaScript that displays an alert when a user tries to open a non-HTTPS site. To do this, you inject a script into the web content that uses [ExecuteScriptAsync](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.webview2.executescriptasync). -1. In the `EnsureHttps` method, add the following `ExecuteScriptAsync` line: + +To display an alert when the user tries to navigate to a non-HTTPS site: + +1. In `MainWindow.xaml.cs`, in the `EnsureHttps` method, add the following `ExecuteScriptAsync` line: ```csharp private void EnsureHttps(WebView2 sender, CoreWebView2NavigationStartingEventArgs args) @@ -384,19 +495,42 @@ As an example, next, you add scripts that send an alert when a user tries to ope } ``` -1. Select **File** > **Save All** (**Ctrl+Shift+S**) to save the project. +1. Select **File** > **Save All** (**Ctrl+Shift+S**). -1. Press **F5** to build and run the project. +1. Press **F5**. + + The project builds, and the app opens. 1. In the app's Address bar, enter a non-HTTPS URL, such as `http://www.bing.com`, and then click the **Go** button. The app's WebView2 control displays an alert dialog for non-HTTPS websites, saying that the non-HTTPS `uri` is not safe: - ![The app's WebView2 control displays an alert dialog for non-HTTPS websites](winui-images/getting-started-script.png) + ![The app's WebView2 control displays an alert dialog for non-HTTPS websites](./winui-images/finished-app.png) 1. Close the app. -Congratulations, you built your first WebView2 app! +Congratulations, you've built a WebView2 WinUI 3 (Windows App SDK) app! + + + +## WinAppSDK supports custom WebView2 environments + +WinAppSDK supports custom WebView2 environments, starting with WinAppSDK 1.5 ([1.5.0-experimental2](/windows/apps/windows-app-sdk/experimental-channel#version-15-experimental-150-experimental2)). For more information, see [WinUI3 WebView2 with a custom CoreWebView2Environment](https://github.com/microsoft/microsoft-ui-xaml/issues/6150). + +To instantiate a custom WebView2 environment, you could initialize WebView2 with one of the overrides of `WebView2.EnsureCoreWebView2Async` (listed below), and pass in your custom `CoreWebView2Environment` (and, optionally, custom `CoreWebView2ControllerOptions`): + +```csharp +public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment) +public IAsyncAction EnsureCoreWebView2Async (CoreWebView2Environment environment, CoreWebView2ControllerOptions controllerOptions) +``` + +Also see the example code in [Disabling SmartScreen navigation](#disabling-smartscreen-navigation), below. + +API Reference: +* [WebView2.EnsureCoreWebView2Async](/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.controls.webview2.ensurecorewebview2async) +* [CoreWebView2ControllerOptions](/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2controlleroptions) +* [CoreWebView2Environment](/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environment) +* [CoreWebView2EnvironmentOptions](/microsoft-edge/webview2/reference/winrt/microsoft_web_webview2_core/corewebview2environmentoptions)