diff --git a/microsoft-edge/media/windows-keyboard-logo.png b/microsoft-edge/media/windows-keyboard-logo.png new file mode 100644 index 0000000000..5439c2eef7 Binary files /dev/null and b/microsoft-edge/media/windows-keyboard-logo.png differ diff --git a/microsoft-edge/toc.yml b/microsoft-edge/toc.yml index 961b443856..ea73d0e406 100644 --- a/microsoft-edge/toc.yml +++ b/microsoft-edge/toc.yml @@ -1025,10 +1025,27 @@ href: webview2/code-samples-links.md displayName: + - name: Win32 sample app + href: webview2/samples/webview2apissample.md + displayName: WebView2APISample, SampleApps, Win32 sample app # repo dir names, top-of-page title + + - name: Win32 sample app with Visual Composition + href: webview2/samples/webview2samplewincomp.md + displayName: WebView2SampleWinComp, Win32 sample app with Visual Composition # repo dir name, top-of-page title + + - name: Win32 sample WebView2Browser + href: webview2/samples/webview2browser.md + displayName: WebView2Browser # repo dir name + - name: WinUI 2 (UWP) sample app href: webview2/samples/webview2_sample_uwp.md displayName: webview2_sample_uwp, WinUI 2 (UWP) sample app # repo dir name, top-of-page title +# pending, July 26 2022 +# - name: WinUI 3 sample app +# href: webview2/samples/webview2-winui3-sample.md +# displayName: WebView2_WinUI3_Sample # repo dir name + - name: WPF sample app href: webview2/samples/webview2wpfbrowser.md displayName: WebView2WpfBrowser, WPF sample app # repo dir name, top-of-page title @@ -1041,14 +1058,6 @@ href: webview2/samples/webview2windowsformsbrowser.md displayName: WebView2WindowsFormsBrowser, WinForms sample app # repo dir name, top-of-page title - - name: Win32 sample app - href: webview2/samples/webview2apissample.md - displayName: WebView2APISample, SampleApps, Win32 sample app # repo dir names, top-of-page title - - - name: Win32 sample app with Visual Composition - href: webview2/samples/webview2samplewincomp.md - displayName: WebView2SampleWinComp, Win32 sample app with Visual Composition # repo dir name, top-of-page title - # ----------------------------------------------------------------------------- # Deployment samples - name: Deployment samples diff --git a/microsoft-edge/webview2/code-samples-links.md b/microsoft-edge/webview2/code-samples-links.md index c6f847d3e1..d044325bd9 100644 --- a/microsoft-edge/webview2/code-samples-links.md +++ b/microsoft-edge/webview2/code-samples-links.md @@ -6,21 +6,25 @@ ms.author: msedgedevrel ms.topic: conceptual ms.prod: microsoft-edge ms.technology: webview -ms.date: 07/18/2022 +ms.date: 08/29/2022 --- # Sample apps Sample apps that use WebView2 are available in the [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps), for various frameworks or platforms. -| Framework or platform | Article | Sample in repo | Comments | -|---|---|---|---| -| WinUI 2 (UWP) | [WinUI 2 (UWP) sample app](samples/webview2_sample_uwp.md) | [webview2_sample_uwp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp) |   | -| WinUI 3 (Windows App SDK) | n/a | n/a | [Tutorial](get-started/winui.md).
[Completed tutorial project](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinUI3_GettingStarted). | -| WPF | [WPF sample app](samples/webview2wpfbrowser.md) | [WebView2WpfBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser) |   | -| WPF with CDP | [WPF app with CDP extension](samples/wv2cdpextensionwpfsample.md) | [WV2CDPExtensionWPFSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample) |   | -| WinForms | [WinForms sample app](samples/webview2windowsformsbrowser.md) | [WebView2WindowsFormsBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser) |   | -| Win32 | [Win32 sample app](samples/webview2apissample.md) | [WebView2APISample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample) | Main sample; extensive. Detailed Readme. | -| Win32 with Visual Composition | [Win32 sample app with Visual Composition](samples/webview2samplewincomp.md) | [WebView2SampleWinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp) |   | +| Article | Sample | Notes | +|---|---|---| +| [Win32 sample app](samples/webview2apissample.md) | [WebView2APISample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample) | Main sample; extensive. | +| [Win32 sample app with Visual Composition](samples/webview2samplewincomp.md) | [WebView2SampleWinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp) | Windows Runtime Composition APIs leverage the Windows UI in Win32 app. | +| [WebView2Browser (Win32 C++/JS)](samples/webview2browser.md) | [WebView2Browser repo](https://github.com/MicrosoftEdge/WebView2Browser) | Uses multiple WebView2 instances. A major sample; has its own repo. | +| [WinUI 2 (UWP) sample app](samples/webview2_sample_uwp.md) | [webview2_sample_uwp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp) |   | +| [WPF sample app](samples/webview2wpfbrowser.md) | [WebView2WpfBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser) |   | +| [WPF app with CDP extension](samples/wv2cdpextensionwpfsample.md) | [WV2CDPExtensionWPFSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample) | Use Chrome DevTools Protocol APIs in a WPF app. | +| [WinForms sample app](samples/webview2windowsformsbrowser.md) | [WebView2WindowsFormsBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser) |   | + + These articles provide the specific steps to set up your machine and build, run, and update each sample. @@ -32,14 +36,6 @@ The sample apps are the source of the sample code snippets that are shown in the For some frameworks or platforms, the samples repo contains both a completed Getting Started tutorial and a sample app. These sample apps showcase more of the WebView2 APIs than the Getting Started tutorials. -#### Installed SDK package versions - -Typically, for these samples, you do the following sequence: -1. Build and run the sample as-is from the repo. -1. Update the sample's project's packages, such as the WebView2 prerelease SDK. The prerelease SDK allows you to try the latest APIs. -1. Build and run the sample using the updated SDK packages. - - ## See also diff --git a/microsoft-edge/webview2/concepts/basic-authentication.md b/microsoft-edge/webview2/concepts/basic-authentication.md index dce9938858..1f1baa6d6b 100644 --- a/microsoft-edge/webview2/concepts/basic-authentication.md +++ b/microsoft-edge/webview2/concepts/basic-authentication.md @@ -54,7 +54,7 @@ For more information, see [Navigation events for WebView2 apps](navigation-event The following diagram shows the flow of navigation events for basic authentication for WebView2 apps: -![Flow of navigation events for basic authentication for WebView2 apps.](basic-authentication-images/basic-auth-page-nav-flow.png) +![Flow of navigation events for basic authentication for WebView2 apps](basic-authentication-images/basic-auth-page-nav-flow.png) diff --git a/microsoft-edge/webview2/concepts/distribution.md b/microsoft-edge/webview2/concepts/distribution.md index 5e91e0e01a..64a632f9b6 100644 --- a/microsoft-edge/webview2/concepts/distribution.md +++ b/microsoft-edge/webview2/concepts/distribution.md @@ -63,7 +63,7 @@ Cons: The [Download the WebView2 Runtime](https://developer.microsoft.com/microsoft-edge/webview2#download-section) section of the **Microsoft Edge WebView2** page provides several options for distributing the WebView2 Runtime onto client machines. Understanding the options at this page provides a good introduction, to help decide which approach you want to use. -![Options for distributing and updating the WebView2 Runtime.](../media/runtime-distrib-options.png) +![Options for distributing and updating the WebView2 Runtime](../media/runtime-distrib-options.png) The Evergreen distribution mode is recommended for most apps. @@ -332,7 +332,7 @@ To use the Fixed Version distribution mode: 1. To confirm that PlayReady is installed correctly, in the **Security** tab of the **Fixed Version** folder, make sure permissions are granted for `ALL APPLICATION PACKAGES` and `ALL RESTRICTED APPLICATION PACKAGES`, as shown below: - ![Permission for PlayReady.](../media/play-ready-permission.png) + ![Permission for PlayReady](../media/play-ready-permission.png) diff --git a/microsoft-edge/webview2/concepts/navigation-events.md b/microsoft-edge/webview2/concepts/navigation-events.md index fba0180e48..b55617a87e 100644 --- a/microsoft-edge/webview2/concepts/navigation-events.md +++ b/microsoft-edge/webview2/concepts/navigation-events.md @@ -41,7 +41,7 @@ The normal sequence of navigation events is: The following events describe the state of WebView2 during each navigation action: -![WebView2 Navigation Events.](../media/navigation-graph.png) +![WebView2 Navigation Events](../media/navigation-graph.png) | Sequence | Event name | Details | | --- | --- | --- | diff --git a/microsoft-edge/webview2/concepts/process-model.md b/microsoft-edge/webview2/concepts/process-model.md index 55d48865a3..4a345588c6 100644 --- a/microsoft-edge/webview2/concepts/process-model.md +++ b/microsoft-edge/webview2/concepts/process-model.md @@ -24,7 +24,7 @@ A _WebView2 process group_ is a collection of WebView2 Runtime processes. A Web * One or more renderer processes. * Other helper processes, such as the GPU process and the Audio service process. -![Process 1.](../media/process-model-1.png) +![Process 1](../media/process-model-1.png) The number and presence of processes in a WebView2 process group can change as a WebView2 application makes use of WebView2 features. (However, there's only a single, specific browser process in a WebView2 process group.) For example, creating a new WebView2 instance from the same `CoreWebView2Environment`, but with a different domain in the `Source` property, will usually start a new renderer process. @@ -44,7 +44,7 @@ All processes in a WebView2 Runtime processes collection are tied to the browser A user data folder can be shared by multiple applications, but be sure to consider the implications on performance and management, as described in [Manage user data folders](user-data-folder.md). -![Process 2.](../media/process-model-2.png) +![Process 2](../media/process-model-2.png) To make use of multiple user data folders, a WebView2 application needs to create different `CoreWebView2Environment` objects. A `WebView2` instance is created for a given user data folder through the configured `CoreWebView2Environment` object. Each `CoreWebView2Environment` object needs to be configured with a different user data folder value. diff --git a/microsoft-edge/webview2/concepts/threading-model.md b/microsoft-edge/webview2/concepts/threading-model.md index 2e451b9c4c..310a3606cb 100644 --- a/microsoft-edge/webview2/concepts/threading-model.md +++ b/microsoft-edge/webview2/concepts/threading-model.md @@ -74,7 +74,7 @@ private void CoreWebView2_WebMessageReceived(object sender, CoreWebView2WebMessa > 1. In **Solution Explorer**, right-click the WebView2 project and then select **Properties**. > 1. Select the **Debug** tab, and then select the **Enable native code debugging** checkbox, as shown below. -![Enabling native code debugging in Visual Studio.](../media/webview-enable-native-debug.png) +![Enabling native code debugging in Visual Studio](../media/webview-enable-native-debug.png) diff --git a/microsoft-edge/webview2/get-started/get-started.md b/microsoft-edge/webview2/get-started/get-started.md index 618af357ac..c5fefa586b 100644 --- a/microsoft-edge/webview2/get-started/get-started.md +++ b/microsoft-edge/webview2/get-started/get-started.md @@ -10,20 +10,20 @@ ms.date: 01/24/2022 --- # Getting Started tutorials -These articles cover how to set up your development tools and create an initial WebView2 app, and learn about WebView2 concepts along the way. +These articles cover how to set up your development tools and create an initial WebView2 app, like a Hello World app with basic functionality. Learn about WebView2 concepts along the way. -| Framework | Article | Completed project | +| Article | Completed project | Description | |---|---|---| -| WinUI 2 (UWP) | [Get started with WebView2 in WinUI 2 (UWP) apps](winui2.md) | n/a | -| WinUI 3 (Windows App SDK) | [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) | -| WPF | [Get started with WebView2 in WPF apps](wpf.md) | [WPF_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WPF_GettingStarted) | -| WinForms | [Get started with WebView2 in WinForms apps](winforms.md) | [WinForms_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinForms_GettingStarted) | -| Win32 | [Get started with WebView2 in Win32 apps](win32.md) | [Win32_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) | +| [Get started with WebView2 in WinUI 2 (UWP) apps](winui2.md) | n/a | 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 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. | ## See also -* [Sample apps](../code-samples-links.md) * [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2) - initial introduction to WebView2, at `developer.microsoft.com`. -* [WebView2Samples repo > Readme](https://github.com/MicrosoftEdge/WebView2Samples#readme) +* [Sample apps](../code-samples-links.md) - framework-specific sample apps that showcase more of the WebView2 APIs than the Getting Started tutorials. +* [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples#readme) - contains completed Visual Studio projects that result from following the steps in these Getting Started tutorials, as well as sample apps and deployment samples. diff --git a/microsoft-edge/webview2/get-started/media/vs2022-create-a-new-project.png b/microsoft-edge/webview2/get-started/media/vs2022-create-a-new-project.png deleted file mode 100644 index 8079da2489..0000000000 Binary files a/microsoft-edge/webview2/get-started/media/vs2022-create-a-new-project.png and /dev/null differ diff --git a/microsoft-edge/webview2/get-started/media/wpf-getting-started-mng-nuget.png b/microsoft-edge/webview2/get-started/media/wpf-getting-started-mng-nuget.png deleted file mode 100644 index 7ac62a2635..0000000000 Binary files a/microsoft-edge/webview2/get-started/media/wpf-getting-started-mng-nuget.png and /dev/null differ diff --git a/microsoft-edge/webview2/get-started/win32.md b/microsoft-edge/webview2/get-started/win32.md index 669391eeda..2741ead2bf 100644 --- a/microsoft-edge/webview2/get-started/win32.md +++ b/microsoft-edge/webview2/get-started/win32.md @@ -6,20 +6,32 @@ ms.author: msedgedevrel ms.topic: conceptual ms.prod: microsoft-edge ms.technology: webview -ms.date: 04/27/2022 +ms.date: 07/29/2022 --- # Get started with WebView2 in Win32 apps -In this article, you set up your development tools (if not done already), add WebView2 code to the Win32 app, and learn about WebView2 concepts along the way. + -The project uses the [Win32_GettingStarted / WebView2GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) directory that's part of the `WebView2Samples` repo. To use this article, you do the following: -1. Download or clone the `WebView2Samples` repo to your local drive. +In this article, you set up your development tools (if not done already), learn how to add WebView2 code to a Win32 app project, and learn about WebView2 concepts along the way. + +This tutorial starts by opening an existing Win32 app project that has WebView2 code added. The project uses the [Win32_GettingStarted (WebView2GettingStarted.sln)](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) directory that's part of the `WebView2Samples` repo. To use this article, you do the following: +1. Clone or download the `WebView2Samples` repo to your local drive. 1. Run the completed project. -1. Optionally delete the WebView2 code from `HelloWebView.cpp`. +1. Optionally delete the WebView2 code from `HelloWebView.cpp` to restore the Win32 baseline app. 1. Follow the remaining steps in this article about adding and understanding the WebView2 code. + + +This tutorial does not have you create a new project; you don't use a project template in Visual Studio to create a new project. Instead, you start with the completed project that's in the repo. + -* Corresponding, completed, runnable Get Started sample at GitHub: [Getting Started with WebView2 for Win32 apps (Win32_GettingStarted/WebView2GettingStarted.sln)](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted#readme). +#### Completed project + +The completed tutorial project is available in the **WebView2Samples** repo: + +* Sample name: **Win32_GettingStarted** +* Repo directory: [Win32_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) +* Solution file: **WebView2GettingStarted.sln** @@ -41,7 +53,7 @@ Then continue below. -## Step 3 - Download or clone the WebView2Samples repo +## Step 3 - Clone or download the WebView2Samples repo The code that you add in this tutorial's steps, has already been added to the sample repo, for you. An optional step below allows you to delete the WebView2 code from `HelloWebView.cpp`, so that you can add it yourself, if you want. @@ -51,15 +63,15 @@ The existing Visual Studio project we'll start with is part of the sample code f --- -Download or clone the WebView2Samples repo, as follows: +Clone or download the WebView2Samples repo, as follows: -1. If you haven't already, download or clone the `WebView2Samples` repo. To do this, in a separate window or tab, follow the steps in [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) or [Clone the WebView2Samples repo](../how-to/machine-setup.md#clone-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. +1. If you haven't already, clone or download the `WebView2Samples` repo. To do this, in a separate window or tab, follow the steps in [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) or [Clone the WebView2Samples repo](../how-to/machine-setup.md#clone-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Then return here after you've copied the repo to your local drive, and continue with the steps below. -## Step 4 - Open the existing Win32 single-window app (WebView2GettingStarted.sln) +## Step 4 - Open the finished solution (WebView2GettingStarted.sln) You start with a basic desktop project that contains a single main window. We'll start with an existing app project from the **WebView2Samples** repo, which you cloned or downloaded from GitHub in the previous step. @@ -73,7 +85,7 @@ You start with a basic desktop project that contains a single main window. We'l Visual Studio Installer might open and prompt you to install a Workload: -![Visual Studio Installer prompting to install the 'Desktop development with C++' workload.](../media/installer-prompt-desktop-cpp-workload.png) +![Visual Studio Installer prompting to install the 'Desktop development with C++' workload](../media/installer-prompt-desktop-cpp-workload.png) If Visual Studio Installer prompts you to install a Workload: @@ -90,7 +102,7 @@ The Installer closes. The Visual Studio **Review Solution Actions** dialog might appear, prompting you whether you want to **Retarget Projects**: -![Visual Studio's 'Review Solution Actions' dialog box, prompting to Retarget Projects.](../media/review-solution-actions-retarget-projects.png) +![Visual Studio's 'Review Solution Actions' dialog box, prompting to Retarget Projects](../media/review-solution-actions-retarget-projects.png) 1. If that dialog appears, you can click **OK**. @@ -108,7 +120,7 @@ If the **WebView2GettingStarted** project isn't open in Visual Studio, open it i `HelloWebView.cpp` opens in the code editor of Visual Studio. - ![The 'WebView2GettingStarted.sln' file from the cloned or downloaded WebView2 repo, opened in Visual Studio, in Solution Explorer.](../media/webview2gettingstarted-sln-in-solution-explorer.png) + ![The 'WebView2GettingStarted.sln' file from the cloned or downloaded WebView2 repo, opened in Visual Studio, in Solution Explorer](../media/webview2gettingstarted-sln-in-solution-explorer.png) The above screenshot shows some WebView2 code (`#include "WebView2.h"`), that's already present in the file immediately after cloning (downloading) the repo. @@ -131,17 +143,42 @@ This step is only needed for older versions of Visual Studio, so it's likely you Here's a Visual Studio 2017 screenshot showing some valid settings: - ![In Visual Studio 2017, set Windows SDK Version to 10, and Platform Toolset to Visual Studio.](../media/tool-version.png) + ![In Visual Studio 2017, set Windows SDK Version to 10, and Platform Toolset to Visual Studio](../media/tool-version.png) The following is a Visual Studio 2022 screenshot; the values were already correct, so no change was required: - ![In Visual Studio 2022, Windows SDK Version is already 10, and Platform Toolset is already Visual Studio.](../media/tool-version-2022.png) + ![In Visual Studio 2022, Windows SDK Version is already 10, and Platform Toolset is already Visual Studio](../media/tool-version-2022.png) Continue with the steps below. -## Step 7 - Install the Windows Implementation Libraries (WIL) +## Step 7 - Build and run the repo's finished project + +At this point, your Dev environment is set up to run Win32 WebView2 apps in debug mode in Visual Studio and add WebView2 features. + +--- + +To confirm that your system is set up for WebView2 coding, run the project in Debug mode, as follows: + +1. Select **Debug** > **Start debugging** (`F5`) to build and run the project. + + The sample app first opens a pop-up window, which displays the URL that will be loaded, along with an **OK** button: + + ![The sample app displays a pop-up window with URL and OK button over an empty WebView2 window](../media/show-url.png) + +1. Click the **OK** button to dismiss the pop-window and continue to the URL: + + The WebView2 window now displays webpage content: the Bing website, `http://www.bing.com`. + + + ![The sample app now displays the Bing website](../media/bing-window.png) + +1. Close the **WebView sample** window. + + + +## Step 8 - Update or install the Windows Implementation Libraries (WIL) WIL is already installed into the project at the repo, but walk through these steps to learn about setup and to check the project's setup. @@ -157,7 +194,7 @@ Install the Windows Implementation Libraries (WIL) from within Visual Studio, as 1. In **Solution Explorer**, right-click the **WebView2GettingStarted** project node (not the solution node) and then select **Manage NuGet Packages**. - ![Manage NuGet packages.](../media/manage-nuget-packages.png) + ![Manage NuGet packages](../media/manage-nuget-packages.png) 1. In the **NuGet** window, click the **Browse** tab. @@ -169,7 +206,7 @@ Install the Windows Implementation Libraries (WIL) from within Visual Studio, as Selecting the **Microsoft.Windows.ImplementationLibrary** package in NuGet Package Manager in Visual Studio: - ![Selecting the 'Microsoft.Windows.ImplementationLibrary' package in NuGet Package Manager in Visual Studio.](../media/wil.png) + ![Selecting the 'Microsoft.Windows.ImplementationLibrary' package in NuGet Package Manager in Visual Studio](../media/wil.png) _To zoom, right-click > **Open image in new tab**._ @@ -192,13 +229,15 @@ Continue with the steps below. [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_ --> -## Step 8 - Install the WebView2 SDK +## Step 9 - Update or install the WebView2 SDK -Next, you'll install the WebView2 SDK. The WebView2 SDK includes the WebView2 control, which is powered by Microsoft Edge, and enables you to embed web technologies (HTML, CSS, and JavaScript) in your native applications. +The finished project in the repo already has a version of the WebView2 SDK installed for the project. If you were creating a project from scratch by starting by using a Win32 project template, you'd need to install the WebView SDK package for the project, as described here. + +Next, update (or install) the WebView2 SDK. The WebView2 SDK includes the WebView2 control, which is powered by Microsoft Edge, and enables you to embed web technologies (HTML, CSS, and JavaScript) in your native applications. --- -Install the WebView2 SDK, as follows: +Update (or install) the WebView2 SDK, as follows: 1. In Visual Studio, make sure that the **WebView2GettingStarted** solution is open, as described above. @@ -206,9 +245,11 @@ Install the WebView2 SDK, as follows: The **NuGet Package Manager** tab and panel opens in Visual Studio. - ![Manage NuGet packages.](../media/manage-nuget-packages.png) + ![Manage NuGet packages](../media/manage-nuget-packages.png) -1. In the **NuGet** window, click the **Browse** tab. +1. If the WebView2 SDK is already installed for the project, as is the case with the repo project, in the **NuGet** window, click the **Installed** tab or the **Update** tab. + +1. Or, if you're installing the WebView2 SDK in a new project, click the **Browse** tab. 1. On the right of the search bar, clear the **Include prerelease** checkbox (unless you know that you want a prerelease version of the SDK). @@ -218,44 +259,17 @@ Install the WebView2 SDK, as follows: Microsoft.Web.WebView2 ``` -1. In the right-hand side window, click **Install** (or **Update**). NuGet downloads the WebView2 SDK to your machine. +1. In the right-hand side window, click **Update** (or **Install**). NuGet downloads the WebView2 SDK to your machine. - ![Selecting the 'Microsoft.Web.WebView2' package in NuGet Package Manager in Visual Studio.](../media/nuget.png) - - _To zoom, right-click > **Open image in new tab**._ + ![Selecting the 'Microsoft.Web.WebView2' package in NuGet Package Manager in Visual Studio](../media/nuget.png) 1. Close the **NuGet Package Manager** tab. -The WebView2 SDK is now installed, so your development environment is now set up to add WebView2 features to your Win32 app. +The WebView2 SDK is now updated or installed, so your development environment is now set up to add WebView2 features to your Win32 app. Continue with the steps below. - -## Step 9 - Run the finished project - -At this point, your Dev environment is set up to run Win32 WebView2 apps in debug mode in Visual Studio and add WebView2 features. - ---- - -To confirm that your system is set up for WebView2 coding, run the project in Debug mode, as follows: - -1. Select **Debug** > **Start debugging** (`F5`) to build and run the project. - - The sample app first opens a pop-up window, which displays the URL that will be loaded, along with an **OK** button: - - ![The sample app displays a pop-up window with URL and OK button over an empty WebView2 window.](../media/show-url.png) - -1. Click the **OK** button to dismiss the pop-window and continue to the URL: - - The WebView2 window now displays webpage content: the Bing website, `http://www.bing.com`. - - - ![The sample app now displays the Bing website.](../media/bing-window.png) - -1. Close the **WebView sample** window. - - ## Step 10 - Optionally delete the WebView2 code from HelloWebView.cpp @@ -263,104 +277,23 @@ If you want to follow the steps below to add the WebView2 code to `HelloWebView. 1. In `HelloWebView.cpp`, delete the following code: - ```cpp - // include WebView2 header - #include "WebView2.h" - ``` - -1. In `HelloWebView.cpp`, delete the following code: + :::code language="cpp" source="../code/sample/GettingStartedGuides/Win32_GettingStarted/HelloWebView.cpp" id="IncludeHeader"::: -```cpp -// Step 3 - Create a single WebView within the parent window -// Locate the browser and set up the environment for WebView -CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr, - Callback( - [hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT { - - // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd - env->CreateCoreWebView2Controller(hWnd, Callback( - [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT { - if (controller != nullptr) { - webviewController = controller; - webviewController->get_CoreWebView2(&webviewWindow); - } - - // Add a few settings for the webview - // The demo step is redundant since the values are the default settings - ICoreWebView2Settings* Settings; - webviewWindow->get_Settings(&Settings); - Settings->put_IsScriptEnabled(TRUE); - Settings->put_AreDefaultScriptDialogsEnabled(TRUE); - Settings->put_IsWebMessageEnabled(TRUE); - - // Resize WebView to fit the bounds of the parent window - RECT bounds; - GetClientRect(hWnd, &bounds); - webviewController->put_Bounds(bounds); - - // Schedule an async task to navigate to Bing - webviewWindow->Navigate(L"https://www.bing.com/"); - - // Step 4 - Navigation events - // register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation - EventRegistrationToken token; - webviewWindow->add_NavigationStarting(Callback( - [](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT { - PWSTR uri; - args->get_Uri(&uri); - std::wstring source(uri); - if (source.substr(0, 5) != L"https") { - args->put_Cancel(true); - } - CoTaskMemFree(uri); - return S_OK; - }).Get(), &token); - - // Step 5 - Scripting - // Schedule an async task to add initialization script that freezes the Object object - webviewWindow->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr); - // Schedule an async task to get the document URL - webviewWindow->ExecuteScript(L"window.document.URL;", Callback( - [](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT { - LPCWSTR URL = resultObjectAsJson; - //doSomethingWithURL(URL); - return S_OK; - }).Get()); - - // Step 6 - Communication between host and web content - // Set an event handler for the host to return received message back to the web content - webviewWindow->add_WebMessageReceived(Callback( - [](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs* args) -> HRESULT { - PWSTR message; - args->TryGetWebMessageAsString(&message); - // processMessage(&message); - webview->PostWebMessageAsString(message); - CoTaskMemFree(message); - return S_OK; - }).Get(), &token); - - // Schedule an async task to add initialization script that - // 1) Add an listener to print message from the host - // 2) Post document URL to the host - webviewWindow->AddScriptToExecuteOnDocumentCreated( - L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \ - L"window.chrome.webview.postMessage(window.document.URL);", - nullptr); - - return S_OK; - }).Get()); - return S_OK; - }).Get()); -``` +1. In `HelloWebView.cpp`, delete the lines of code that are in between these two comment lines, but keep these two comment lines: + ```cpp + // <-- WebView2 sample code starts here --> + ... + // <-- WebView2 sample code ends here --> + ``` ## Step 11 - Include the WebView2.h header in HelloWebView.cpp Above, we did the following: -* Cloned or downloaded an existing project that contains a standard C++ Windows desktop application. -* Installed the Windows Implementation Library (WIL). -* Installed the WebView2 SDK, to add WebView2 features. +* Cloned or downloaded the samples repo including an existing project that contains a standard C++ Windows desktop application. +* Updated or installed the Windows Implementation Library (WIL). +* Updated or installed the WebView2 SDK, to add WebView2 features. * Optionally deleted the WebView2 code from `HelloWebView.cpp`. --- @@ -373,10 +306,7 @@ Next, add WebView2 features to the app, as follows: 1. If the following code isn't already present, paste the following code in `HelloWebView.cpp`, after the last `#include` line: - ```cpp - // include WebView2 header - #include "WebView2.h" - ``` + :::code language="cpp" source="../code/sample/GettingStartedGuides/Win32_GettingStarted/HelloWebView.cpp" id="IncludeHeader"::: Make sure that the `include` section looks like the following: @@ -410,7 +340,7 @@ Continue with the steps below. The sample app opens and displays an empty window: - ![The sample app displays an empty window.](../media/empty-app.png) + ![The sample app displays an empty window](../media/empty-app.png) You now have a running, empty Win32 desktop app with potential WebView2 capabilities. @@ -446,12 +376,12 @@ Now to do the above, in the callback, you'll: 1. In `HelloWebView.cpp`, locate the following code: -```cpp - UpdateWindow(hWnd); - - // <-- WebView2 sample code starts here --> -``` - + ```cpp + UpdateWindow(hWnd); + + // <-- WebView2 sample code starts here --> + ``` + 1. If the following code isn't already present, paste the following code into `HelloWebView.cpp`. Paste the code in between the lines `// <-- WebView2 sample code starts here -->` and `// <-- WebView2 sample code ends here -->`: ```cpp @@ -461,40 +391,40 @@ Now to do the above, in the callback, you'll: Callback( [hWnd](HRESULT result, ICoreWebView2Environment* env) -> HRESULT { - // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd - env->CreateCoreWebView2Controller(hWnd, Callback( - [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT { + // Create a CoreWebView2Controller and get the associated CoreWebView2 whose parent is the main window hWnd + env->CreateCoreWebView2Controller(hWnd, Callback( + [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT { if (controller != nullptr) { webviewController = controller; - webviewController->get_CoreWebView2(&webviewWindow); + webviewController->get_CoreWebView2(&webview); } // Add a few settings for the webview // The demo step is redundant since the values are the default settings - ICoreWebView2Settings* Settings; - webviewWindow->get_Settings(&Settings); - Settings->put_IsScriptEnabled(TRUE); - Settings->put_AreDefaultScriptDialogsEnabled(TRUE); - Settings->put_IsWebMessageEnabled(TRUE); + wil::com_ptr settings; + webview->get_Settings(&settings); + settings->put_IsScriptEnabled(TRUE); + settings->put_AreDefaultScriptDialogsEnabled(TRUE); + settings->put_IsWebMessageEnabled(TRUE); - // Resize the WebView2 control to fit the bounds of the parent window + // Resize WebView to fit the bounds of the parent window RECT bounds; GetClientRect(hWnd, &bounds); webviewController->put_Bounds(bounds); // Schedule an async task to navigate to Bing - webviewWindow->Navigate(L"https://www.bing.com/"); + webview->Navigate(L"https://www.bing.com/"); - // 4 - Navigation events + // Step 4 - Navigation events - // 5 - Scripting + // Step 5 - Scripting - // 6 - Communication between host and web content + // Step 6 - Communication between host and web content return S_OK; }).Get()); - return S_OK; - }).Get()); + return S_OK; + }).Get()); ``` 1. Select **File** > **Save All** (`Ctrl`+`Shift`+`S`) to save the project. @@ -506,13 +436,13 @@ Now to do the above, in the callback, you'll: If you started by deleting all of the WebView2 code, at this point, you now have a Win32 window that's filled with a WebView2 control that's filled with webpage content: - ![Bing window.](../media/bing-window.png) + ![Bing window](../media/bing-window.png) 1. Close the **WebView sample** app window. Or, if you kept all of the WebView2 code, at this point, a pop-up WebView2 window with an alert dialog from Bing opens, over an empty WebView2 window. Click the **OK** button to close the Bing dialog box. Now the WebView2 control is filled by Bing page content: - ![The sample app displays an initially empty window with a Bing dialog box.](../media/empty-app-with-bing-dialog.png) + ![The sample app displays an initially empty window with a Bing dialog box](../media/empty-app-with-bing-dialog.png) 1. If the **WebView sample** app window is open, close it. @@ -536,7 +466,7 @@ In the previous step, we discussed navigating to URL by using the `ICoreWebView2 If you want more information now, in a new window or tab, see [Navigation events for WebView2 apps](../concepts/navigation-events.md). -![Navigation events.](../media/navigation-events.png) +![Navigation events](../media/navigation-events.png) In error cases, one or more of the following events may occur, depending on whether the navigation continued to an error webpage: @@ -552,22 +482,7 @@ As an example of using navigation events, register a handler for the `Navigation 1. If it's not already present, paste the following code into `HelloWebView.cpp`, below the Step 3 code: - ```cpp - // Step 4 - Navigation events - // register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation - EventRegistrationToken token; - webviewWindow->add_NavigationStarting(Callback( - [](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs * args) -> HRESULT { - PWSTR uri; - args->get_Uri(&uri); - std::wstring source(uri); - if (source.substr(0, 5) != L"https") { - args->put_Cancel(true); - } - CoTaskMemFree(uri); - return S_OK; - }).Get(), &token); - ``` + :::code language="cpp" source="../code/sample/GettingStartedGuides/Win32_GettingStarted/HelloWebView.cpp" id="NavigationEvents"::: Now the app doesn't open any non-https sites. You can use a similar mechanism to accomplish other tasks, such as restricting navigation to within your own domain. @@ -590,18 +505,7 @@ The injected JavaScript is run with specific timing: 1. If the following code isn't present already, paste the following code into `HelloWebView.cpp`: - ```cpp - // Step 5 - Scripting - // Schedule an async task to add initialization script that freezes the Object object - webviewWindow->AddScriptToExecuteOnDocumentCreated(L"Object.freeze(Object);", nullptr); - // Schedule an async task to get the document URL - webviewWindow->ExecuteScript(L"window.document.URL;", Callback( - [](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT { - LPCWSTR URL = resultObjectAsJson; - //doSomethingWithURL(URL); - return S_OK; - }).Get()); - ``` + :::code language="cpp" source="../code/sample/GettingStartedGuides/Win32_GettingStarted/HelloWebView.cpp" id="Scripting"::: 1. Select **File** > **Save All** (`Ctrl`+`Shift`+`S`) to save the project. @@ -644,27 +548,7 @@ Have the host app and web content communicate through `postMessage`, as follows: 1. If it's not already present, paste the following code into `HelloWebView.cpp`: - ```cpp - // Step 6 - Communication between host and web content - // Set an event handler for the host to return received message back to the web content - webviewWindow->add_WebMessageReceived(Callback( - [](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs * args) -> HRESULT { - PWSTR message; - args->TryGetWebMessageAsString(&message); - // processMessage(&message); - webview->PostWebMessageAsString(message); - CoTaskMemFree(message); - return S_OK; - }).Get(), &token); - - // Schedule an async task to add initialization script that - // 1) Add an listener to print message from the host - // 2) Post document URL to the host - webviewWindow->AddScriptToExecuteOnDocumentCreated( - L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \ - L"window.chrome.webview.postMessage(window.document.URL);", - nullptr); - ``` + :::code language="cpp" source="../code/sample/GettingStartedGuides/Win32_GettingStarted/HelloWebView.cpp" id="CommunicationHostWeb"::: 1. Select **File** > **Save All** (`Ctrl`+`Shift`+`S`) to save the project. @@ -672,19 +556,19 @@ Have the host app and web content communicate through `postMessage`, as follows: The sample app first opens a pop-up window, which displays the URL that will be loaded, along with an **OK** button: - ![The sample app displays a pop-up window with URL and OK button over an empty WebView2 window.](../media/show-url.png) + ![The sample app displays a pop-up window with URL and OK button over an empty WebView2 window](../media/show-url.png) 1. Click the **OK** button to dismiss the pop-window and continue to the URL: The WebView2 window now displays webpage content: the Bing website, `http://www.bing.com`. - ![The sample app now displays the Bing website.](../media/bing-window.png) + ![The sample app now displays the Bing website](../media/bing-window.png) 1. When you are ready, close the **WebView sample** window. -Congratulations, you built your first WebView2 app! Your development environment is now set up for WebView2 app development, to include the WebView2 control in your Win32 apps. You've also had an introduction to WebView2 programming concepts. +Congratulations, you've built a Win32 app that hosts and uses the WebView2 control! Your development environment is now set up for WebView2 app development, to include the WebView2 control in your Win32 apps. You've also had an introduction to WebView2 programming concepts. @@ -697,25 +581,6 @@ Congratulations, you built your first WebView2 app! Your development environmen ## See also -developer.microsoft.com: -* [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2) - initial introduction to WebView2 features at developer.microsoft.com. - -Local pages: -* [Win32 sample app](../samples/webview2apissample.md) -* [Manage user data folders](../concepts/user-data-folder.md) -* [Sample Code for WebView2](../code-samples-links.md) - a guide to the samples in the **WebView2Samples** repo. -* [Development best practices for WebView2 apps](../concepts/developer-guide.md) - -WebView2Samples repo: -* [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples) -* [Win32 Sample Code](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) - the code used in this tutorial. -* [WebView2 API Sample](https://github.com/MicrosoftEdge/WebView2Samples/blob/main/SampleApps/WebView2APISample/README.md) - a comprehensive example of WebView2 capabilities. -* [WebView2Browser](https://github.com/MicrosoftEdge/WebView2Browser) - a WebView2 sample app. - -Libraries: +* [Sample Code for WebView2](../code-samples-links.md) * [Windows Runtime C++ Template Library (WRL)](/cpp/cppcx/wrl/windows-runtime-cpp-template-library-wrl?view=vs-2019&preserve-view=true) * [Windows Implementation Libraries (WIL)](https://github.com/Microsoft/wil) GitHub repo. - - diff --git a/microsoft-edge/webview2/get-started/winforms.md b/microsoft-edge/webview2/get-started/winforms.md index c9c983881b..83950e0eaf 100644 --- a/microsoft-edge/webview2/get-started/winforms.md +++ b/microsoft-edge/webview2/get-started/winforms.md @@ -15,19 +15,30 @@ todo: errors experienced with vs2022 by following these instructions: * The addressbar text box & Go button shift to the right when alt+tab to the Form1 window. --> -This article covers how to set up your development tools and create an initial WebView2 app for the WinForms platform, and learn about WebView2 concepts along the way. +This tutorial helps you: +* Set up your development tools. +* Use the **C# Windows Forms App (.NET Framework)** Visual Studio project template to create a WinForms project. +* Install the **Microsoft.Web.WebView2** SDK package for the WinForms project. +* Learn about WebView2 concepts along the way. + + +#### Completed project + +A completed version of this tutorial project is available in the **WebView2Samples** repo: + +* Sample name: **Win32_GettingStarted** +* Repo directory: [Win32_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/Win32_GettingStarted) +* Solution file: **WebView2GettingStarted.sln** -## Step 1 - Optionally download or clone the WebView2Samples repo +## Step 1 - Optionally clone or download the WebView2Samples repo Do either of the following: -* Create a new project in Visual Studio, using the steps below. If you want to see the completed project, you can see the [WinForms_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinForms_GettingStarted) directory in the `WebView2Samples` repo. +* Create a new project in Visual Studio starting from a project template, using the steps below. -* Download or clone the `WebView2Samples` repo, open the completed project in Visual Studio, and follow the steps in this article to understand creating the WinForms project and understand the added WebView2 code. - -The corresponding Get Started sample at GitHub: [WinForms_GettingStarted/WinForms_GettingStarted.sln](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinForms_GettingStarted) (no readme file). +* Clone or download the `WebView2Samples` repo, open the completed project in Visual Studio, and follow the steps in this article to understand creating the WinForms project and understand the added WebView2 code. See [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. A completed version of this tutorial project is available in the WebView2Samples repo directory [WinForms_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinForms_GettingStarted). @@ -43,6 +54,8 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor ## Step 3 - Install a preview channel of Microsoft Edge + + 1. Install any [Microsoft Edge Insider (preview) Channel](https://www.microsoftedgeinsider.com/download) (Beta, Dev, or Canary) on a supported operating system (OS): * Windows 7 * Windows 8.1 @@ -55,7 +68,9 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor ## Step 4 - Install the WebView2 Runtime (optional) -1. Optionally, install the WebView2 Runtime. See [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2). + + +1. Optionally, install the WebView2 Runtime. Go to [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2), click the **Download Now** link. In the **Fixed Version** section, select a version and architecture, and then click the **Download** button. A file such as `Microsoft.WebView2.FixedVersionRuntime.103.0.1264.71.x64.cab` is placed in your **Downloads** directory. If unsure, skip this step; you can use the Microsoft Edge preview channel from the previous step instead. @@ -77,13 +92,9 @@ Start with a basic desktop project that contains a single main window. The Visual Studio **Open recent** window appears: - ![The Visual Studio opening panel displays the Create a new project card.](media/winforms-opening-panel.png) + ![The Visual Studio opening panel displays the Create a new project card](media/winforms-opening-panel.png) -1. On the right, click the **Create a new project** card. - - The Visual Studio **Create a new project** window appears: - - ![The Visual Studio 'Create a new project' window.](media/vs2022-create-a-new-project.png) +1. On the right, click the **Create a new project** card. The Visual Studio **Create a new project** window opens. 1. In the **Search** text box, paste or start typing the following: @@ -93,9 +104,9 @@ Start with a basic desktop project that contains a single main window. Search results appear, listing project types. -1. Select the **C# Windows Forms App (.NET Framework)** card, and then click the **Next** button: +1. Select the **C# Windows Forms App (.NET Framework)** card. Make sure the name matches, with a **C#** icon and then the name **Windows Forms App (.NET Framework)**. Then click the **Next** button: - ![In the 'Create a new project' panel, select 'C# > Windows Forms App (.NET Framework)'.](media/winforms-new-project.png) + ![In the 'Create a new project' panel, select 'C# > Windows Forms App (.NET Framework)'](media/winforms-new-project.png) 1. In the **Project name** text box, enter a project name. This tutorial article uses the name **WinForms_GettingStarted**, like the [repo's directory name](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinForms_GettingStarted) for the completed project. @@ -103,13 +114,13 @@ Start with a basic desktop project that contains a single main window. 1. In the **Framework** dropdown list, select **.NET Framework 4.7.2** or later, such as **.NET Framework 4.8**: - ![Filling in the 'Configure your new project' window.](media/winforms-start-proj.png) + ![Filling in the 'Configure your new project' window](media/winforms-start-proj.png) 1. Click the **Create** button. The Visual Studio window opens, showing the baseline WinForms project in the Solution Explorer, and showing a Form Designer window: - ![The Visual Studio window, showing the baseline WinForms project and a Forms Designer.](media/vs2022-new-empty-winforms-gettingstarted-project.png) + ![The Visual Studio window, showing the baseline WinForms project and a Forms Designer](media/vs2022-new-empty-winforms-gettingstarted-project.png) 1. Select **File** > **Save All** (`Ctrl`+`Shift`+`S`). @@ -118,7 +129,7 @@ Start with a basic desktop project that contains a single main window. An empty **Form1** window opens, from the fresh WinForms project: - ![The empty Form1 window from the fresh WinForms project.](media/form1-empty-window-fresh-winforms-project.png) + ![The empty Form1 window from the fresh WinForms project](media/form1-empty-window-fresh-winforms-project.png) 1. Close the **Form1** window. @@ -131,13 +142,13 @@ You now have an empty WinForms project that runs. Next, set up the project to a ## Step 6 - Install the WebView2 SDK -For every WebView2 project, you use the NuGet package manager within Visual Studio to add the WebView2 SDK to the project. You install the Microsoft.Web.WebView2 SDK NuGet package for use by the current project. +For every WebView2 project, you use the NuGet package manager within Visual Studio to add the WebView2 SDK to the project. You install the **Microsoft.Web.WebView2** SDK NuGet package for use by the current project. Use NuGet to add the WebView2 SDK to the project, as follows: 1. In **Solution Explorer**, right-click the project name (not the solution name above it), and then select **Manage NuGet Packages**: - ![Manage NuGet Packages.](media/winforms-getting-started-mng-nuget.png) + ![Manage NuGet Packages](media/winforms-getting-started-mng-nuget.png) The NuGet Package Manager opens in Visual Studio. @@ -147,13 +158,13 @@ Use NuGet to add the WebView2 SDK to the project, as follows: 1. In the search bar, type **WebView2**, and then below the search bar, click **Microsoft.Web.WebView2** to select it: - ![The NuGet Package Manager in Visual Studio, installing the Microsoft.Web.WebView2 SDK NuGet package for the current project.](media/winforms-project-nuget-webview2-install.png) + ![The NuGet Package Manager in Visual Studio, installing the Microsoft.Web.WebView2 SDK NuGet package for the current project](media/winforms-project-nuget-webview2-install.png) _To zoom, right-click > **Open image in new tab**._ 1. Click the **Install** (or **Update**) button. The **Preview Changes** dialog box opens: - ![The Preview Changes dialog box.](media/winforms-install-webview2-preview.png) + ![The Preview Changes dialog box](media/winforms-install-webview2-preview.png) 1. Click the **OK** button. @@ -166,10 +177,10 @@ Use NuGet to add the WebView2 SDK to the project, as follows: The running project displays the same empty window as before: - ![The empty Form1 window from the fresh WinForms project.](media/form1-empty-window-fresh-winforms-project.png) + ![The empty Form1 window from the fresh WinForms project](media/form1-empty-window-fresh-winforms-project.png) + ![Sample app displays an empty window](media/winforms-empty-app.png) --> 1. Close the **Form1** window. @@ -189,11 +200,11 @@ The starter project has a `Form1.cs` form already, but we'll add another, as `Fo 1. On the right, select **Form (Windows Forms)**, and then click the **Add** button: - ![The 'Add New Item' window, expanded to 'Visual C# Items' > 'Windows Forms', selecting 'Form (Windows Forms)'.](media/add-new-item-form-windows-forms.png) + ![The 'Add New Item' window, expanded to 'Visual C# Items' > 'Windows Forms', selecting 'Form (Windows Forms)'](media/add-new-item-form-windows-forms.png) The project now has an additional form, with filename `Form2.cs`, shown in the Form Designer and in Solution Explorer: - ![The added form, Form2.cs, in the Form Designer and in Solution Explorer.](media/winforms-added-form2.png) + ![The added form, Form2.cs, in the Form Designer and in Solution Explorer](media/winforms-added-form2.png) 1. Click the **Form1** canvas. We won't use **Form2**. @@ -207,13 +218,13 @@ The starter project has a `Form1.cs` form already, but we'll add another, as `Fo 1. In the **Toolbox**, click or drag the **WebView2** control onto the Forms Designer canvas of the control you added, such as `Form2.cs`: - ![Toolbox displaying WebView2.](media/winforms-toolbox.png) + ![Toolbox displaying WebView2](media/winforms-toolbox.png) 1. Drag the sides of the WebView2 control to make it fill almost all of the canvas. 1. Make sure the new **WebView2** control on the form is selected. In the **Properties** panel, in the **Design** section, set the **(Name)** property to **webView** (lowercase 'w', capital 'V', no numeric suffix). The control might initially be named something else, such as **webView21**. Use the **Categorized** and **Alphabetical** sort option buttons as needed to find properties: - ![Properties of the WebView2 control.](media/winforms-properties.png) + ![Properties of the WebView2 control](media/winforms-properties.png) 1. In the **Properties** panel, in the **Misc** section, set the **Source** property to `https://www.microsoft.com`. The **Source** property sets the initial URL that will be displayed in the WebView2 control. @@ -223,13 +234,13 @@ The starter project has a `Form1.cs` form already, but we'll add another, as `Fo The WebView2 control displays content from https://www.microsoft.com, in a WebView2 control in the Windows Forms form, with a **Skip to main content** link if you pressed `Alt`+`Tab` to switch to the window: - ![Alt+Tab causes the sample app to initially display a 'Skip to main content' link.](media/winforms-hello-webview-skip-to-main-content.png) + ![Alt+Tab causes the sample app to initially display a 'Skip to main content' link](media/winforms-hello-webview-skip-to-main-content.png) 1. If needed, click the **Skip to main content** link. The WebView2 control displays content from https://www.microsoft.com, in a WebView2 control in the Windows Forms form: - ![The sample app displays the Microsoft website.](media/winforms-hello-webview.png) + ![The sample app displays the Microsoft website](media/winforms-hello-webview.png) 1. Close the **Form1** window. @@ -270,11 +281,11 @@ Add more controls to your Windows Forms form from the toolbox, and then process 1. Position the text box on the left side of the form, vertically aligned with the button, as shown below: - ![WinForms designer.](media/winforms-designer.png) + ![WinForms designer](media/winforms-designer.png) 1. Resize the text box as shown: - ![WinForms designer textbox and button.](media/winforms-designer-txtbtn.png) + ![WinForms designer textbox and button](media/winforms-designer-txtbtn.png) 1. Click **View** > **Code** to open `Form1.cs`. @@ -307,7 +318,7 @@ Add more controls to your Windows Forms form from the toolbox, and then process } ``` - ![Form_Resize code added.](media/winforms-form-resize-code-added.png) + ![Form_Resize code added](media/winforms-form-resize-code-added.png) 1. Select **File** > **Save All** (`Ctrl`+`Shift`+`S`) to save the project. @@ -315,7 +326,7 @@ Add more controls to your Windows Forms form from the toolbox, and then process A **Form1** window appears, displaying webpage content from https://www.microsoft.com: - ![A Form1 WinForm window displaying webpage content from microsoft.com.](media/winforms-app.png) + ![A Form1 WinForm window displaying webpage content from microsoft.com](media/winforms-app.png) If you press `Alt`+`Tab` to switch to the **Form1** window, you may need to click the **Skip to main content** link that's added. @@ -361,13 +372,13 @@ Enable users to change the URL that the WebView2 control displays, by reading th 1. In the address bar, enter a URL that starts with `https`, such as `https://www.bing.com`, and then click the **Go!** button: - ![bing.com.](media/winforms-bing.png) + ![bing.com](media/winforms-bing.png) The WebView2 control shows the webpage content for the URL. 1. In the address bar, enter a string that doesn't start with `http`, such as `www.bing.com`, and then click the **Go!** button. - ![Argument exception due to entering a non-URL.](media/winforms-non-url-arg-exception.png) + ![Argument exception due to entering a non-URL](media/winforms-non-url-arg-exception.png) An `ArgumentException` is thrown if the URL doesn't start with `http://` or `https://`. @@ -393,7 +404,7 @@ During webpage navigation, the WebView2 control raises events. The app that host For more information, see [Navigation events for WebView2 apps](../concepts/navigation-events.md). -![Navigation events.](../media/navigation-events.png) +![Navigation events](../media/navigation-events.png) When an error occurs, the following events are raised and may depend on navigation to an error webpage: @@ -486,7 +497,7 @@ For example, add a script that sends an alert when a user navigates to a non-HTT The app displays an alert: - ![An http alert, that says try https instead.](media/winforms-https.png) + ![An http alert, that says try https instead](media/winforms-https.png) @@ -565,7 +576,7 @@ In your project, when the WebView2 control navigates to a URL, it displays the U 1. Enter a URL, such as `https://www.bing.com`: - ![The updated address bar URL initially is displayed in an alert box.](media/winforms-update-addr-bar-alert.png) + ![The updated address bar URL initially is displayed in an alert box](media/winforms-update-addr-bar-alert.png) An alert initially appears, showing the resulting URL that's sent from the host website. @@ -573,7 +584,7 @@ In your project, when the WebView2 control navigates to a URL, it displays the U The WebView2 control now displays the new URL in the address bar, and webpage content from the URL is displayed in the WebView2 control in the WinForms window: - ![The application displays the URL in the address bar.](media/winforms-final-app.png) + ![The application displays the URL in the address bar](media/winforms-final-app.png) * When the app starts, the default URL is `https://www.microsoft.com`, and the resulting displayed address shows the locale, such as `https://www.microsoft.com/en-us/`. @@ -585,22 +596,6 @@ Congratulations, you built your first WebView2 app! ## See also -developer.microsoft.com: -* [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2) - initial introduction to WebView2 features at developer.microsoft.com. - -Local pages: * [WinForms sample app](../samples/webview2windowsformsbrowser.md) - Demonstrates more WebView2 APIs than the present tutorial. -* [Manage user data folders](../concepts/user-data-folder.md) -* [Sample Code for WebView2](../code-samples-links.md) - a guide to the `WebView2Samples` repo. -* [Development best practices for WebView2 apps](../concepts/developer-guide.md) * [See also](../index.md#see-also) in _Introduction to Microsoft Edge WebView2_ - Conceptual and how-to articles about building and deploying WebView2 apps. - -GitHub: -* [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples) - a comprehensive example of WebView2 capabilities. - -API Reference: -* [API Reference: Microsoft.Web.WebView2.WinForms Namespace](/dotnet/api/microsoft.web.webview2.winforms) -* [WebView2 API reference](/dotnet/api/microsoft.web.webview2.winforms.webview2) - -NuGet: -* [Microsoft.Web.WebView2 SDK at nuget.org](https://www.nuget.org/packages/Microsoft.Web.WebView2) +* [Microsoft.Web.WebView2.WinForms](/dotnet/api/microsoft.web.webview2.winforms) - API Reference. diff --git a/microsoft-edge/webview2/get-started/winui.md b/microsoft-edge/webview2/get-started/winui.md index be40aa008e..dce82ec203 100644 --- a/microsoft-edge/webview2/get-started/winui.md +++ b/microsoft-edge/webview2/get-started/winui.md @@ -12,7 +12,20 @@ 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 start with the Visual Studio project template for a blank WinUI 3 project, and then 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. The completed sample is available at GitHub: [WebView2Samples repo > WinUI3_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WinUI3_GettingStarted). +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. + +![Sample app displaying the Bing website](winui-images/getting-started-bing.png) + + +#### Completed project + +A completed version of this tutorial project (as of 2020) is available in the **WebView2Samples** repo: + +* Sample name: **WinUI3_GettingStarted** +* Repo directory: [WinUI3_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/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. diff --git a/microsoft-edge/webview2/get-started/winui2.md b/microsoft-edge/webview2/get-started/winui2.md index 043ad91bc8..d3c8e1bb87 100644 --- a/microsoft-edge/webview2/get-started/winui2.md +++ b/microsoft-edge/webview2/get-started/winui2.md @@ -13,9 +13,12 @@ ms.date: 07/14/2022 In this tutorial, you: * Set up your development tools for creating UWP apps that use WebView2 to display web content. * Create an initial WinUI 2 (UWP) app. +* Install the **Microsoft.UI.Xaml** package (WinUI 2) for the project. * Add a WebView2 control that displays webpage content. * Learn about WebView2 concepts along the way. +You use the **C# Blank App (Universal Windows)** project template, then install the **Microsoft.UI.Xaml** package (WinUI 2) for this project. Installing that package installs the **Microsoft.Web.WebView2** package (the WebView2 SDK) as a dependency. + The **Microsoft.UI.Xaml** (WinUI 2) package is part of the Windows UI Library. This package provides Windows UI features, including: * UWP XAML controls. * Dense control styles. @@ -23,9 +26,17 @@ The **Microsoft.UI.Xaml** (WinUI 2) package is part of the Windows UI Library. WinUI 2 supports UWP only. These controls are backward-compatible. -Follow the major Step sections in sequence, below. - +#### Completed project + +Unlike some of the other tutorials, there isn't a completed version of this Getting Started tutorial in the WebView2Samples repo. + + +Follow the major Step sections in sequence, below. @@ -46,15 +57,15 @@ Visual Studio 2019 version 16.9 or later is required, for this tutorial. Visual 1. Open Microsoft Visual Studio. The opening option window appears: - ![Visual Studio 2022 opening option window.](media/winui2-vs2022-opening-option-window.png) + ![Visual Studio 2022 opening option window](media/winui2-vs2022-opening-option-window.png) 1. In the lower right, click **Continue without code**. Visual Studio opens, empty: - ![Visual Studio 2022 empty.](media/winui2-visual-studio-2022-empty.png) + ![Visual Studio 2022 empty](media/winui2-visual-studio-2022-empty.png) 1. Select **Tools** > **Get Tools and Features**. The **Visual Studio Installer** window opens, and then the **Modifying - Visual Studio** window opens over it: - ![The Modifying Visual Studio window, initial state.](media/winui2-modifying-vs-window.png) + ![The Modifying Visual Studio window, initial state](media/winui2-modifying-vs-window.png) If the **Modifying Visual Studio** window isn't open, in the **Visual Studio Installer** window, click the **Modify** button. @@ -65,7 +76,7 @@ Visual Studio 2019 version 16.9 or later is required, for this tutorial. Visual 1. On the right, in the **Installation details** section, expand **Universal Windows Platform development**, and then select **C++ (v143) Universal Windows Platform tools** or **C++ (v142) Universal Windows Platform tools**: - ![The 'Modifying Visual Studio 2019' dialog displays cards and installation details.](media/winui2-getting-started-install-workloads.png) + ![The 'Modifying Visual Studio 2019' dialog displays cards and installation details](media/winui2-getting-started-install-workloads.png) If all of these components have already been installed, you can click the **Close** button, close the **Visual Studio Installer** window, and skip to the next major section of steps below. @@ -77,13 +88,13 @@ Visual Studio 2019 version 16.9 or later is required, for this tutorial. Visual 1. A dialog box appears, "Before we get started, close Visual Studio": - ![Dialog box: Before we get started, close Visual Studio.](media/winui2-before-we-get-started.png) + ![Dialog box: Before we get started, close Visual Studio](media/winui2-before-we-get-started.png) 1. Click the **Continue** button. Visual Studio downloads, verifies, and installs the selected packages: - ![Visual Studio Installer working.](media/winui2-vs-installer-working.png) + ![Visual Studio Installer working](media/winui2-vs-installer-working.png) This can take several minutes. In a new window or tab, you can check out a top-level overview at [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2) - an initial introduction to WebView2 features at developer.microsoft.com. @@ -99,17 +110,17 @@ Visual Studio 2019 version 16.9 or later is required, for this tutorial. Visual Or, if Visual Studio is closed, open it, and then in the startup screen of Visual Studio, click the **Create a new project** card: - ![The startup screen of Visual Studio: click the 'Create a new project' card.](media/winui2-opening-win-create-new-project-card.png) + ![The startup screen of Visual Studio: click the 'Create a new project' card](media/winui2-opening-win-create-new-project-card.png) 1. In the **Search for templates** text box at the top, enter **C# Blank App (Universal Windows)**, and then select the **C# Blank App (Universal Windows)** card: - ![The 'Create a new project' dialog box displays the blank app (Universal Windows) card.](media/winui2-getting-started-create-project.png) + ![The 'Create a new project' dialog box displays the blank app (Universal Windows) card](media/winui2-getting-started-create-project.png) 1. Click the **Next** button. The **Configure your new project** dialog appears, for a **Blank App (Universal Windows)**: - ![The 'Configure your new project' dialog box displays text boxes for a Blank App (Universal Windows).](media/winui2-getting-started-config-new-project.png) + ![The 'Configure your new project' dialog box displays text boxes for a Blank App (Universal Windows)](media/winui2-getting-started-config-new-project.png) 1. In the **Project name** text box, enter a project name, such as `MyUWPGetStartApp`. @@ -120,12 +131,12 @@ Visual Studio 2019 version 16.9 or later is required, for this tutorial. Visual The **New Windows Project** dialog box appears: - ![The 'New Windows Project' dialog box.](media/winui2-new-windows-project.png) + ![The 'New Windows Project' dialog box](media/winui2-new-windows-project.png) 1. Accept the defaults, and click the **OK** button. @@ -134,7 +145,7 @@ Visual Studio 2019 version 16.9 or later is required, for this tutorial. Visual Visual Studio displays the newly created solution and project: - ![Visual Studio, containing the newly created WinUI 2 (UWP) project.](media/winui2-vs-after-new-project-created.png) + ![Visual Studio, containing the newly created WinUI 2 (UWP) project](media/winui2-vs-after-new-project-created.png) @@ -180,7 +191,7 @@ Next, you install the **Microsoft.UI.Xaml** package for this project. Microsoft The **Preview Changes** dialog box appears: - ![The 'Preview Changes' dialog box for installing the Microsoft.UI.Xaml package.](media/winui2-preview-changes-ui-xaml-pkg.png) + ![The 'Preview Changes' dialog box for installing the Microsoft.UI.Xaml package](media/winui2-preview-changes-ui-xaml-pkg.png) The above image shows 2.7.1, but these instructions are actually written for 2.8.0 or later, for General Availability of WebView2 in the Microsoft.UI.Xaml NuGet package. @@ -190,11 +201,11 @@ Next, you install the **Microsoft.UI.Xaml** package for this project. Microsoft 1. The **License Acceptance** dialog box appears: - ![The 'License Acceptance' dialog box for installing the Microsoft.UI.Xaml package.](media/winui2-license-acceptance-ui-xaml-pkg.png) + ![The 'License Acceptance' dialog box for installing the Microsoft.UI.Xaml package](media/winui2-license-acceptance-ui-xaml-pkg.png) 1. Click the **I Accept** button. In Visual Studio, the `readme.txt` file is displayed, saying that you've installed the WinUI package: - ![The readme.txt file after installing the Microsoft.UI.Xaml package, reports that you installed the WinUI NuGet package.](media/winui2-readme-winui-pkg.png) + ![The readme.txt file after installing the Microsoft.UI.Xaml package, reports that you installed the WinUI NuGet package](media/winui2-readme-winui-pkg.png) The readme lists some lines of code that are similar to what we'll add. @@ -232,7 +243,7 @@ Now you are ready to add WebView2 code to the project. First, add a namespace r Above the `MainPage.xaml` file in the code editor, a preview of the WebView2 content might be displayed, or it might remain blank (white) until you first build the app: - ![Preview of the WebView2 content.](media/winui2-getting-started-preview-webview2-content.png) + ![Preview of the WebView2 content](media/winui2-getting-started-preview-webview2-content.png) The above image shows "control" on two lines; we recommend using the word "controls" on those lines instead. @@ -247,11 +258,11 @@ Now you are ready to add WebView2 code to the project. First, add a namespace r 1. Click **Debug** > **Start Debugging**. The app window opens, briefly showing the WebView2 WebUI grid: - ![During debugging, the WebView2 WebUI grid briefly appears.](media/winui2-getting-started-webview2-grid.png) + ![During debugging, the WebView2 WebUI grid briefly appears](media/winui2-getting-started-webview2-grid.png) 1. After a moment, the app window shows the Bing website in the WebView2 control for WebUI 2: - ![The sample app displays the Bing website.](media/winui2-getting-started-webview2-with-content.png) + ![The sample app displays the Bing website](media/winui2-getting-started-webview2-with-content.png) 1. In Visual Studio, click **Debug** > **Stop Debugging** to close the app window. diff --git a/microsoft-edge/webview2/get-started/wpf.md b/microsoft-edge/webview2/get-started/wpf.md index 653cb860c0..918cd99dab 100644 --- a/microsoft-edge/webview2/get-started/wpf.md +++ b/microsoft-edge/webview2/get-started/wpf.md @@ -12,7 +12,15 @@ 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. -A completed version of this tutorial project is available in the WebView2Samples repo: [Getting Started with WebView2 in WPF (WPF_GettingStarted/WPFSample.sln)](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WPF_GettingStarted#readme). +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. + + +#### Completed project + +A completed version of this tutorial project is available in the **WebView2Samples** repo: +* Sample name: **WPF_GettingStarted** +* Repo directory: [WPF_GettingStarted](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/GettingStartedGuides/WPF_GettingStarted#readme) +* Solution file: **WPFSample.sln** @@ -52,27 +60,27 @@ Start with a basic desktop project that contains a single main window. The highlighted card in the following image is **WPF Application: .NET Core WPF Application**: - ![The 'Create a new project' panel with the card selected, 'WPF Application: .NET Core WPF Application'.](media/wpf-getting-started-wpf-core.png) + ![The 'Create a new project' panel with the card selected, 'WPF Application: .NET Core WPF Application'](media/wpf-getting-started-wpf-core.png) Alternatively, the highlighted card in the following image is **WPF App (.NET Framework): Windows Presentation Foundation client application**: - ![The 'Create a new project' panel with the card selected, 'WPF App (.NET Framework): Windows Presentation Foundation client application'.](media/wpf-getting-started-wpf-fw.png) + ![The 'Create a new project' panel with the card selected, 'WPF App (.NET Framework): Windows Presentation Foundation client application'](media/wpf-getting-started-wpf-fw.png) The **Configure your new project** WPF application dialog box appears. - ![The 'Configure your new project' WPF application dialog box.](media/wpf-getting-started-create-core.png) + ![The 'Configure your new project' WPF application dialog box](media/wpf-getting-started-create-core.png) 1. Enter values for **Project name** and **Location**, and then click **Next**. The **Additional information** dialog box appears, with a **Target Framework** dropdown list: - ![The 'Additional information' dialog with a 'Target Framework' dropdown list.](media/wpf-getting-started-create-core-add-info.png) + ![The 'Additional information' dialog with a 'Target Framework' dropdown list](media/wpf-getting-started-create-core-add-info.png) 1. 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)**: - ![Configure your new project WPF app .NET framework dialog box displays project name, location, and solution name text boxes.](media/wpf-getting-started-create-fw.png) + ![Configure your new project WPF app .NET framework dialog box displays project name, location, and solution name text boxes](media/wpf-getting-started-create-fw.png) 1. Enter values for **Project name** and **Location**. @@ -91,18 +99,13 @@ Start with a basic desktop project that contains a single main window. Use NuGet to add the WebView2 SDK to the project. -1. In **Solution Explorer**, right-click the project name, and then select **Manage NuGet Packages**: - - ![The 'Manage NuGet packages' command on the right-click menu.](media/wpf-getting-started-mng-nuget.png) - - - _(The above image is supposed to show the WPF project instead of the WinForms project.)_ +1. In **Solution Explorer**, right-click the project name (not the solution node), and then select **Manage NuGet Packages**. The **NuGet Package Manager** window opens. 1. 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. - ![NuGet package manager dialog box displays the Microsoft.Web.WebView2 card.](media/install-nuget.png) + ![NuGet package manager dialog box displays the Microsoft.Web.WebView2 card](media/install-nuget.png) 1. Accept the default version, and then click the **Install** button. @@ -114,7 +117,7 @@ Use NuGet to add the WebView2 SDK to 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: - ![Empty app window.](media/winforms-empty-app.png) + ![Empty app window](media/winforms-empty-app.png) @@ -165,7 +168,7 @@ Add a WebView2 control to your app. 1. Make sure your WebView2 control displays [https://www.microsoft.com](https://www.microsoft.com): - ![The WebView2 control, displaying webpage content from microsoft.com.](media/wpf-getting-started-microsoft.png) + ![The WebView2 control, displaying webpage content from microsoft.com](media/wpf-getting-started-microsoft.png) @@ -255,7 +258,7 @@ Enable users to change the URL that the WebView2 control displays, by adding an The sample app displays the Bing website with the URL `https://www.bing.com` in the address bar: - ![The app displays the Bing website.](media/wpf-getting-started-bing.png) + ![The app displays the Bing website](media/wpf-getting-started-bing.png) @@ -445,7 +448,7 @@ In your project, when the WebView2 control navigates to a URL, it displays the U The sample app displays the URI in the address bar and the Microsoft website, https://www.microsoft.com: - ![The sample app displays the URI in the address bar and the Microsoft website.](media/wpf-getting-started-searchbar.png) + ![The sample app displays the URI in the address bar and the Microsoft website](media/wpf-getting-started-searchbar.png) Congratulations, you built your first WebView2 app! diff --git a/microsoft-edge/webview2/how-to/chromium-devtools-protocol.md b/microsoft-edge/webview2/how-to/chromium-devtools-protocol.md index 5e3a2e321b..f49556d409 100644 --- a/microsoft-edge/webview2/how-to/chromium-devtools-protocol.md +++ b/microsoft-edge/webview2/how-to/chromium-devtools-protocol.md @@ -83,7 +83,7 @@ To create an `HTML file` to find your geolocation, complete following the action 1. To display your latitude and longitude coordinates, click the **Display Location** button. To verify and compare your geolocation, copy and paste your coordinates in [https://www.bing.com/maps](https://www.bing.com/maps). - ![Displaying the user's geolocation coordinates in Microsoft Edge.](./media/geolocater-browser.png) + ![Displaying the user's geolocation coordinates in Microsoft Edge](./media/geolocater-browser.png) @@ -103,7 +103,7 @@ To create an `HTML file` to find your geolocation, complete following the action 1. Make sure the `geolocation.html` file is displayed in your WebView2 control app: - ![The geolocation.html file, displayed in your WebView2 control app.](./media/initial-geolocate.png) + ![The geolocation.html file, displayed in your WebView2 control app](./media/initial-geolocate.png) @@ -119,7 +119,7 @@ To install the package: 1. Make sure **Microsoft.Web.WebView2.DevToolsProtocolExtension** is displayed in the Visual Studio NuGet Package Manager: - ![Making sure Microsoft.Web.WebView2.DevToolsProtocolExtension is displayed in the Visual Studio NuGet Package Manager.](./media/cdp-nuget.png) + ![Making sure Microsoft.Web.WebView2.DevToolsProtocolExtension is displayed in the Visual Studio NuGet Package Manager](./media/cdp-nuget.png) @@ -166,7 +166,7 @@ To install the package: 1. To display the coordinates of Paris, France, click the **Display Location** button: - ![Display the .html file in a WebView2 control with the coordinates for Paris.](./media/final-location-cdp.png) + ![Display the .html file in a WebView2 control with the coordinates for Paris](./media/final-location-cdp.png) diff --git a/microsoft-edge/webview2/how-to/hostobject.md b/microsoft-edge/webview2/how-to/hostobject.md index b290667ce8..f3a3d2a30a 100644 --- a/microsoft-edge/webview2/how-to/hostobject.md +++ b/microsoft-edge/webview2/how-to/hostobject.md @@ -39,7 +39,7 @@ Scenarios that may benefit from using host objects in script: * JavaScript is sandboxed, limiting its ability on the native side. For example, if you need to access a file on the native side, you must use the native file system. If you have a native object exposed to JavaScript via `AddHostObjectToScript`, you can use it to manipulate files on the native file system. -This article uses the [WebView2 Win32 sample app](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample) to demonstrate some practical applications of `AddHostObjectToScript`. For more information about how to embed web content into native applications, see [Embed web content into native applications](/microsoft-edge/webview2/how-to/communicate-btwn-web-native). +This article uses the [Win32 sample app](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample) to demonstrate some practical applications of `AddHostObjectToScript`. For more information about how to embed web content into native applications, see [Embed web content into native applications](/microsoft-edge/webview2/how-to/communicate-btwn-web-native). #### Preview of the major steps in this article diff --git a/microsoft-edge/webview2/how-to/machine-setup.md b/microsoft-edge/webview2/how-to/machine-setup.md index e2e0719514..30409ac0d6 100644 --- a/microsoft-edge/webview2/how-to/machine-setup.md +++ b/microsoft-edge/webview2/how-to/machine-setup.md @@ -16,11 +16,11 @@ This article covers general-purpose setup of your development environment for We ## Install Visual Studio -1. Install [Visual Studio](https://visualstudio.microsoft.com) 2015 or later, such as Visual Studio Professional 2022. +1. Install [Visual Studio](https://visualstudio.microsoft.com) 2015 or later, such as Visual Studio Professional 2019. Most of the WebView2 samples were created and tested using Visual Studio 2019. If a sample was created using Visual Studio 2019, you should build and run the sample in Visual Studio 2019, before using the sample in Visual Studio 2022. The WebView2 samples are designed for Microsoft **Visual Studio**, not Microsoft **Visual Studio Code**. - If you are installing Visual Studio 2022, you can accept the defaults for now; you can click **Install**, and decline installing the Workloads at this time. Visual Studio will prompt you later, when you open a particular `.sln` file, to install the platform-appropriate workloads. + If you are installing Visual Studio, you can accept the defaults for now; you can click **Install**, and then decline installing the Workloads at this time. Visual Studio will prompt you later, when you open a particular `.sln` file, to install the platform-appropriate workloads. @@ -45,11 +45,15 @@ If unsure, skip this step; you can use the Microsoft Edge preview channel from t See [Understand the different WebView2 SDK versions](../concepts/versioning.md). - + ## Download the WebView2Samples repo -You can download the repo as a `.zip` file, or clone the repo. +There are two repos containing WebView2 samples: +* [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples) +* [WebView2Browser repo](https://github.com/MicrosoftEdge/WebView2Browser) + +You can download a repo as a `.zip` file, or clone the repo. * If you download the repo (as a `.zip` file), you get a snapshot copy of the repo. You can then download another, updated copy of the repo later. @@ -58,7 +62,7 @@ You can download the repo as a `.zip` file, or clone the repo. To download the repo (as a `.zip` file): -1. Open the [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples) in a new window or tab. +1. Open the [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples) (or the [WebView2Browser repo](https://github.com/MicrosoftEdge/WebView2Browser)) in a new window or tab. 1. Click the green **Code** button in the upper right of the GitHub repo, and then click **Download ZIP**. @@ -87,7 +91,7 @@ To download the repo (as a `.zip` file): 1. Recommended: Rename the root directory from `WebView2Samples-main` to `WebView2Samples`, to match the repo name and path. - + ## Clone the WebView2Samples repo @@ -98,7 +102,7 @@ You can download the repo as a `.zip` file, or clone the repo. * If you clone the repo, you can update your local copy using git commands or features of various Dev apps. -To clone the `WebView2Samples` repo, you must first install git. You can download the repo, as described above, or clone it. +To clone the `WebView2Samples` repo (or the `WebView2Browser` repo), you must first install git. You can download the repo, as described above, or clone it. ### Install git @@ -177,7 +181,7 @@ If you instead want to clone the repo by using a Git Bash shell or command promp ## Open a WebView2Samples .sln file in Visual Studio -After you download or clone the `WebView2Samples` repo, open a `.sln` file in Visual Studio. +After you clone or download the `WebView2Samples` repo, open a `.sln` file in Visual Studio. 1. In your local copy of the repo directory structure, locate a `.sln` file. The [top-level README file in the WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples#readme) gives a similar overview. @@ -245,7 +249,7 @@ The WebView2 SDK includes the WebView2 control, which is powered by Microsoft Ed You install the WebView2 SDK once per project node of each `.sln` file. The WebView2 SDK installation applies only to the project that it's installed on. -Instead of downloading the `Microsoft.Web.WebView2` SDK NuGet package from nuget.org, you install the WebView2 SDK NuGet package through the **NuGet Package Manager** panel in Visual Studio. After you Download or clone the WebView2Samples repo, you then open one of the repo's `.sln` files in Visual Studio, and right-click a project node within the solution. You use the **NuGet Package Manager** panel to install the `Microsoft.Web.WebView2` SDK as a NuGet package. +Instead of downloading the `Microsoft.Web.WebView2` SDK NuGet package from nuget.org, you install the WebView2 SDK NuGet package through the **NuGet Package Manager** panel in Visual Studio. After you clone or download the WebView2Samples repo, you then open one of the repo's `.sln` files in Visual Studio, and right-click a project node within the solution. You use the **NuGet Package Manager** panel to install the `Microsoft.Web.WebView2` SDK as a NuGet package. The `Microsoft.Web.WebView2` SDK is available in Release and Prerelease versions. To get started, a Release version is recommended. diff --git a/microsoft-edge/webview2/how-to/winrt-from-js.md b/microsoft-edge/webview2/how-to/winrt-from-js.md index df8566a3e8..66739eaeb4 100644 --- a/microsoft-edge/webview2/how-to/winrt-from-js.md +++ b/microsoft-edge/webview2/how-to/winrt-from-js.md @@ -82,7 +82,7 @@ Let's get started! If you have your own app code base already, you can open that project in Visual Studio, instead of starting with the **webview2_sample_uwp** sample from the `WebView2Samples` repo. -1. If not done already, download or clone the `WebView2Samples` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +1. If not done already, clone or download the `WebView2Samples` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. 1. On your local drive, open the `.sln` file in Visual Studio, in a directory such as: diff --git a/microsoft-edge/webview2/index.md b/microsoft-edge/webview2/index.md index 565586a950..8029b5f233 100644 --- a/microsoft-edge/webview2/index.md +++ b/microsoft-edge/webview2/index.md @@ -15,7 +15,7 @@ The Microsoft Edge WebView2 control allows you to embed web technologies (HTML, With WebView2, you can embed web code in different parts of your native app, or build all of the native app within a single WebView2 instance. -![Diagram of an app with native UI areas in the left and top left, and WebView2 UI areas in the top right and bottom.](media/webview2/what-webview.png) +![Diagram of an app with native UI areas in the left and top left, and WebView2 UI areas in the top right and bottom](media/webview2/what-webview.png) To start building a WebView2 app, see [Get started with WebView2](get-started/get-started.md). @@ -31,7 +31,7 @@ Developers must often decide between building a web app or a native app. This d The following diagram shows the spectrum of apps, from maximum reach, to maximum power: -![The spectrum of apps, from maximum reach but less power, to an optimal hybrid blend, to maximum power but less reach.](media/webview2/web-native.png) +![The spectrum of apps, from maximum reach but less power, to an optimal hybrid blend, to maximum power but less reach](media/webview2/web-native.png) * Wide **reach** includes websites and Progressive Web Apps. @@ -98,13 +98,9 @@ WebView2 apps can run on the following versions of Windows: ## See also - - * [Overview of WebView2 features and APIs](concepts/overview-features-apis.md) -* [Understand the different WebView2 SDK versions](concepts/versioning.md) +* [Getting Started tutorials](get-started/get-started.md) * [Distribute your app and the WebView2 Runtime](concepts/distribution.md) -* [Best practices for developing secure WebView2 apps](concepts/security.md) -* [Manage user data folders](concepts/user-data-folder.md) -* [How to Debug with WebView2](how-to/debug.md) -* [Automating and testing WebView2 with Microsoft Edge WebDriver](how-to/webdriver.md) -* [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples) - Samples that demonstrate WebView2 SDK features and API usage patterns, including recently added WebView2 features. + +developer.microsoft.com: +* [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2) - initial introduction to WebView2 features at developer.microsoft.com. diff --git a/microsoft-edge/webview2/samples/deployment-samples.md b/microsoft-edge/webview2/samples/deployment-samples.md index cc82321086..b228401b10 100644 --- a/microsoft-edge/webview2/samples/deployment-samples.md +++ b/microsoft-edge/webview2/samples/deployment-samples.md @@ -10,16 +10,17 @@ ms.date: 07/11/2022 --- # Deployment samples -For each deployment sample in the WebView2Samples repo, there's an article in the regular docs, as well as a Readme, directory, and (if appropriate) a project file in the repo. +These samples demonstrate how to deploy the Evergreen WebView2 Runtime with your app that uses the WebView2 control. -| Article | Sample | -|---|---| -| [WebView2 Deployment Visual Studio installer](wv2deploymentvsinstallersample.md) | [WV2DeploymentVSInstallerSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentVSInstallerSample) | -| [WiX Burn Bundle to deploy the Runtime](wv2deploymentwixburnbundlesample.md) | [WV2DeploymentWiXBurnBundleSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample) | -| [WiX Custom Action to deploy the Runtime](wv2deploymentwixcustomactionsample.md) | [WV2DeploymentWiXCustomActionSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample) | +| Article | Sample | Description | +|---|---|---| +| [WebView2 Deployment Visual Studio installer](wv2deploymentvsinstallersample.md) | [WV2DeploymentVSInstallerSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentVSInstallerSample) | Uses the Microsoft Visual Studio Installer Projects to create an installer for **WebView2APISample** and chain-install the Evergreen WebView2 Runtime. | +| [WiX Burn Bundle to deploy the Runtime](wv2deploymentwixburnbundlesample.md) | [WV2DeploymentWiXBurnBundleSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample) | Creates a WiX installer for **WebView2APISample** and uses WiX Burn Bundle to chain-install the Evergreen WebView2 Runtime. | +| [WiX Custom Action to deploy the Runtime](wv2deploymentwixcustomactionsample.md) | [WV2DeploymentWiXCustomActionSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample) | Creates a WiX installer for **WebView2APISample** and uses WiX Custom Action to chain-install the Evergreen WebView2 Runtime. | ## See also -* [WebView2Samples repo > Readme](https://github.com/MicrosoftEdge/WebView2Samples#readme) +* [Deploying the Evergreen WebView2 Runtime](../concepts/distribution.md#deploying-the-evergreen-webview2-runtime) in _Distribute your app and the WebView2 Runtime_. +* [WebView2Samples repo](https://github.com/MicrosoftEdge/WebView2Samples#readme) diff --git a/microsoft-edge/webview2/samples/media/unsupported-review-project-dialog.png b/microsoft-edge/webview2/samples/media/unsupported-review-project-dialog.png new file mode 100644 index 0000000000..a2f240075b Binary files /dev/null and b/microsoft-edge/webview2/samples/media/unsupported-review-project-dialog.png differ diff --git a/microsoft-edge/webview2/samples/media/webview2apisample-app-window.png b/microsoft-edge/webview2/samples/media/webview2apisample-app-window.png deleted file mode 100644 index 1444d82b7b..0000000000 Binary files a/microsoft-edge/webview2/samples/media/webview2apisample-app-window.png and /dev/null differ diff --git a/microsoft-edge/webview2/samples/media/webview2apisample-in-solution-explorer.png b/microsoft-edge/webview2/samples/media/webview2apisample-in-solution-explorer.png deleted file mode 100644 index 26b64e11ee..0000000000 Binary files a/microsoft-edge/webview2/samples/media/webview2apisample-in-solution-explorer.png and /dev/null differ diff --git a/microsoft-edge/webview2/samples/media/webview2apisample-pkg-mgr-prerelease-webview2.png b/microsoft-edge/webview2/samples/media/webview2apisample-pkg-mgr-prerelease-webview2.png deleted file mode 100644 index 705f0ab672..0000000000 Binary files a/microsoft-edge/webview2/samples/media/webview2apisample-pkg-mgr-prerelease-webview2.png and /dev/null differ diff --git a/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/dotnet-version-not-installed.png b/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/dotnet-version-not-installed.png new file mode 100644 index 0000000000..2e2bf1f7d7 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/dotnet-version-not-installed.png differ diff --git a/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/dotnet5-out-of-support.png b/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/dotnet5-out-of-support.png new file mode 100644 index 0000000000..fb4a34c3d9 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/dotnet5-out-of-support.png differ diff --git a/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/initial-solution-opened.png b/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/initial-solution-opened.png new file mode 100644 index 0000000000..34fa37fad3 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2-3winui3-sample-images/initial-solution-opened.png differ diff --git a/microsoft-edge/webview2/samples/webview2-winui3-sample.md b/microsoft-edge/webview2/samples/webview2-winui3-sample.md new file mode 100644 index 0000000000..ffa40c2446 --- /dev/null +++ b/microsoft-edge/webview2/samples/webview2-winui3-sample.md @@ -0,0 +1,39 @@ +--- +title: WinUI 3 sample app +description: This WebView2 sample demonstrates how to host the WebView2 control in a WinUI 3 (Windows App SDK) app. +author: MSEdgeTeam +ms.author: msedgedevrel +ms.topic: conceptual +ms.prod: microsoft-edge +ms.technology: webview +ms.date: 07/26/2022 +--- +# WinUI 3 sample app + +This sample demonstrates using a WebView2 control in a WinUI 3 Windows SDK Packaged application. + +* Sample name: **WebView2_WinUI3_Sample** +* Repo folder: [WebView2_WinUI3_Sample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2_WinUI3_Sample) +* Solution file: `SampleApps/WebView2_WinUI3_Sample/WebView2_WinUI3_Sample.sln` + +This sample also shows how to optionally update the application to ship packaged together with a fixed version of the WebView2 Runtime, instead of using the version of the WebView2 Runtime that's installed on the user's computer. + +This sample was created using Visual Studio 2022. To build and run this sample, see the [Readme](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2_WinUI3_Sample#readme). + + diff --git a/microsoft-edge/webview2/samples/webview2_sample_uwp.md b/microsoft-edge/webview2/samples/webview2_sample_uwp.md index a9760eda48..143f0860e4 100644 --- a/microsoft-edge/webview2/samples/webview2_sample_uwp.md +++ b/microsoft-edge/webview2/samples/webview2_sample_uwp.md @@ -10,15 +10,10 @@ ms.date: 07/13/2022 --- # WinUI 2 (UWP) sample app - - This WebView2 sample demonstrates how to use the WebView2 control and WebView2 APIs to implement a web browser in a WinUI 2 (UWP) app. * Sample name: **webview2_sample_uwp** -* Repo directory: **webview2_sample_uwp** +* Repo directory: [webview2_sample_uwp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp) * Solution file: **webview2_sample_uwp.sln** @@ -32,27 +27,11 @@ This sample includes the following NuGet packages: To demonstrate the latest features, this sample in the WebView2Samples repo is set up to use a prerelease version of the WinUI 2 SDK (listed as **Microsoft.UI.Xaml** in NuGet Package Manager), rather than a Stable version. The WinUI 2 SDK includes a compatible version of the WebView2 SDK, as a dependency of **Microsoft.UI.Xaml**. - - -## Step 1 - View the Readme - -1. In a separate window or tab, briefly read the rendered README.md file for this project at GitHub: [README file for webview2_sample_uwp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp#readme). Then return to this page and continue the steps below. - - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp#prerequisites) - - * [README > Build the WebView2 UWP WinUi2 browser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp#build-the-webview2-uwp-winui2-browser) - - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: - - `/WebView2Samples/SampleApps/webview2_sample_uwp/README.md` - - or: - - `/WebView2Samples-main/SampleApps/webview2_sample_uwp/README.md` +See also [README file for webview2_sample_uwp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/webview2_sample_uwp#readme). -## Step 2 - Install Visual Studio +## Step 1 - Install Visual Studio Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. @@ -60,19 +39,19 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor -## Step 3 - Install a preview channel of Microsoft Edge +## Step 2 - Install a preview channel of Microsoft Edge 1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 4 - Download or clone the WebView2Samples repo +## Step 3 - Clone or download the WebView2Samples repo -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +1. If not done already, clone or download the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 5 - Open the solution in Visual Studio +## Step 4 - Open the solution in Visual Studio 1. On your local drive, open the `.sln` file in Visual Studio, in the directory: @@ -84,13 +63,13 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor -## Step 6 - Install workloads if prompted +## Step 5 - Install workloads if prompted 1. If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 7 - Build and run the project using the initial NuGet packages +## Step 6 - Build and run the project using pre-installed packages Solution Explorer shows the **webview2_sample_uwp** project: @@ -120,12 +99,11 @@ Build and run the project, using the versions of the NuGet packages that were in 1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. - Next, update the NuGet packages for the project, per the following sections. -## Step 8 - Update the NuGet packages +## Step 7 - Update the NuGet packages In this step, we'll update the project's NuGet packages, to get the latest prerelease version of the WinUI 2 SDK. The WinUI 2 SDK includes a compatible prerelease or release version of the WebView2 SDK. @@ -188,7 +166,7 @@ Update the project's NuGet packages: -## Step 9 - Build and run the project with updated packages +## Step 8 - Build and run the project with updated packages Now that the NuGet packages have been updated, build and run the project again: @@ -210,7 +188,7 @@ Now that the NuGet packages have been updated, build and run the project again: -## Step 10 - Inspect the code +## Step 9 - Inspect the code 1. In the Visual Studio code editor, inspect the code: diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/all-projects-in-solution-explorer.png b/microsoft-edge/webview2/samples/webview2apissample-images/all-projects-in-solution-explorer.png new file mode 100644 index 0000000000..8b2b10fb66 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/all-projects-in-solution-explorer.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/modifying-vs2019-initial.png b/microsoft-edge/webview2/samples/webview2apissample-images/modifying-vs2019-initial.png new file mode 100644 index 0000000000..4fe9e41ee3 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/modifying-vs2019-initial.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/retarget-projects-22621.png b/microsoft-edge/webview2/samples/webview2apissample-images/retarget-projects-22621.png new file mode 100644 index 0000000000..5a20d143b0 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/retarget-projects-22621.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/retarget-projects.png b/microsoft-edge/webview2/samples/webview2apissample-images/retarget-projects.png new file mode 100644 index 0000000000..f7a6cd4774 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/retarget-projects.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/review-project-changes-unsupported-wix.png b/microsoft-edge/webview2/samples/webview2apissample-images/review-project-changes-unsupported-wix.png new file mode 100644 index 0000000000..4a4536a8a6 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/review-project-changes-unsupported-wix.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/sample-app-layout-diagram.png b/microsoft-edge/webview2/samples/webview2apissample-images/sample-app-layout-diagram.png new file mode 100644 index 0000000000..5f2566bc69 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/sample-app-layout-diagram.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/sample-app-webmessaging-screenshot.png b/microsoft-edge/webview2/samples/webview2apissample-images/sample-app-webmessaging-screenshot.png new file mode 100644 index 0000000000..88f1ac1409 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/sample-app-webmessaging-screenshot.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/solution-opened.png b/microsoft-edge/webview2/samples/webview2apissample-images/solution-opened.png new file mode 100644 index 0000000000..dd9543ed47 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/solution-opened.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/turn-windows-features-on.png b/microsoft-edge/webview2/samples/webview2apissample-images/turn-windows-features-on.png new file mode 100644 index 0000000000..9ff50561e2 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/turn-windows-features-on.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/v143-not-installed.png b/microsoft-edge/webview2/samples/webview2apissample-images/v143-not-installed.png new file mode 100644 index 0000000000..1d2ebd94c2 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/v143-not-installed.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-app-window.png b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-app-window.png new file mode 100644 index 0000000000..a1264d4608 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-app-window.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-in-solution-explorer.png b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-in-solution-explorer.png new file mode 100644 index 0000000000..5f02661dcb Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-in-solution-explorer.png differ diff --git a/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-pkg-mgr-prerelease-webview2.png b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-pkg-mgr-prerelease-webview2.png new file mode 100644 index 0000000000..e2a453013d Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-pkg-mgr-prerelease-webview2.png differ diff --git a/microsoft-edge/webview2/samples/media/webview2apisample-project-selected.png b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-project-selected.png similarity index 100% rename from microsoft-edge/webview2/samples/media/webview2apisample-project-selected.png rename to microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-project-selected.png diff --git a/microsoft-edge/webview2/samples/media/webview2apisample-unable-to-start-program-cannot-find-path.png b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-unable-to-start-program-cannot-find-path.png similarity index 100% rename from microsoft-edge/webview2/samples/media/webview2apisample-unable-to-start-program-cannot-find-path.png rename to microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-unable-to-start-program-cannot-find-path.png diff --git a/microsoft-edge/webview2/samples/media/webview2apisample-webview2-pkg-preview-changes.png b/microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-webview2-pkg-preview-changes.png similarity index 100% rename from microsoft-edge/webview2/samples/media/webview2apisample-webview2-pkg-preview-changes.png rename to microsoft-edge/webview2/samples/webview2apissample-images/webview2apisample-webview2-pkg-preview-changes.png diff --git a/microsoft-edge/webview2/samples/webview2apissample.md b/microsoft-edge/webview2/samples/webview2apissample.md index ed2a47a2c7..7a9daf3869 100644 --- a/microsoft-edge/webview2/samples/webview2apissample.md +++ b/microsoft-edge/webview2/samples/webview2apissample.md @@ -6,66 +6,73 @@ ms.author: msedgedevrel ms.topic: conceptual ms.prod: microsoft-edge ms.technology: webview -ms.date: 04/27/2022 +ms.date: 07/29/2022 --- # Win32 sample app -This WebView2 sample demonstrates how to use the WebView2 control and WebView2 APIs to add features to a Win32 C++ app. - -The WebView2APISample is an example of an application that embeds a WebView2 control within a Win32 native application. It is built as a Win32 Visual Studio project and makes use of both C++ and HTML/CSS/JavaScript in the WebView2 environment. - -The API Sample showcases a selection of WebView2's event handlers and API methods that allow a native Win32 application to directly interact with a WebView2 control and vice versa. +This sample, **WebView2APISample**, demonstrates how to use the WebView2 control and WebView2 APIs to add features to a Win32 C++ app. * Sample name: **WebView2APISample** -* Repo directory: **WebView2APISample** -* Solution file: **WebView2Samples.sln** (in parent directory) +* Repo directory: [WebView2APISample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample) +* Solution file: **WebView2Samples.sln** (located in the parent directory, `\SampleApps\`) * Project name in Solution Explorer: **WebView2APISample** +**WebView2APISample** embeds a WebView2 control within a Win32 native application. - -## Step 1 - View the Readme +This sample is built as a Win32 Visual Studio 2019 project. It uses C++ and HTML/CSS/JavaScript in the WebView2 environment. + -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. +**WebView2APISample** showcases a selection of WebView2's event handlers and API methods that allow a native Win32 application to directly interact with a WebView2 control and vice versa. -1. In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WebView2APISample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample#readme). Then return to this page and continue the steps below. +This sample and its solution file are unique: it contains a copy of other samples, in Solution Explorer. - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample#prerequisites) +**WebView2APISample** is a hybrid application built with the Microsoft Edge WebView2 control; that is, this app combines a native side and a browser web app side. See [Hybrid app approach](../index.md#hybrid-app-approach) in _Introduction to Microsoft Edge WebView2_. - * [README > Build the WebView2 API Sample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample#build-the-webview2-api-sample) +The running **WebView2APISample** app window shows the WebView2 SDK version and also the WebView2 Runtime version and path. There are many useful menus and menuitems provided for you: - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: - - `/WebView2Samples/SampleApps/README.md` +![WebView2APISample app window showing WebView2 SDK version and WebView2 Runtime version and path](./webview2apissample-images/webview2apisample-app-window.png) + - or: +If this is your first time using WebView, we recommend first following the tutorial [Get started with WebView2 in Win32 apps](../get-started/win32.md), which goes over how to create a WebView2 app and walks through some basic WebView2 functionality. That particular tutorial doesn't start with you creating a new Win32 project using a project template; instead, it starts with a finished project in the WebView2Samples repo, and walks you through how to optionally re-add the WebView2 code. + - `/WebView2Samples-main/SampleApps/README.md` +For details of events and API handlers in WebView2, see [WebView2 API Reference](../webview2-api-reference.md). -## Step 2 - Install Visual Studio +## Step 1 - Install a preview channel of Microsoft Edge -Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. +Next, make sure a preview channel of Microsoft Edge in installed, on a supported OS. Currently we recommend the latest version of the Canary channel. -1. If Visual Studio (minimum required version) is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 3 - Install a preview channel of Microsoft Edge +## Step 2 - Install Visual Studio 2019 -1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. This repo sample is a Visual Studio 2019 project. + +1. If Visual Studio 2019 (minimum required version) is not already installed with C++ support, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section to install Visual Studio 2019 with C++ support, and then return to this page and continue the steps below. + +If you want to use Visual Studio 2017, after you open the solution in Visual Studio 2017, change the project's Platform Toolset in **Project Properties > Configuration properties > General > Platform Toolset**. + +To use Visual Studio 2017, you might also need to install a recent Windows SDK on your machine. -## Step 4 - Download or clone the WebView2Samples repo +## Step 3 - Clone the WebView2Samples repo + +1. If not done already, clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +1. If you previously cloned the repo, pull the latest commits to your local copy of the repo. -## Step 5 - Open .sln in Visual Studio +## Step 4 - Open the solution in Visual Studio -1. On your local drive, open the `.sln` file in Visual Studio, in the directory: +1. On your local drive, open the `.sln` file in Visual Studio: * `/WebView2Samples/SampleApps/WebView2Samples.sln` @@ -73,61 +80,63 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor * `/WebView2Samples-main/SampleApps/WebView2Samples.sln` +The **WebView2APISample** sample and project is the main Win32 sample. - -## Step 6 - Install workloads if prompted +Unlike some other samples, there's not a dedicated `.sln` file in the sample repo directory that contains this sample's Readme. Instead, the `.sln` file for this sample (including other sample projects as well) is in the parent directory. -1. **Visual Studio workloads** - If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +![All projects in the solution in Solution Explorer](./webview2apissample-images/all-projects-in-solution-explorer.png) -## Step 7 - View the opened project - -Solution Explorer shows several projects, including the **WebView2APISample** project: +## Step 5 - Install workloads if prompted -![The WebView2APISample opened in Visual Studio in Solution Explorer.](media/webview2apisample-in-solution-explorer.png) +1. **Visual Studio workloads** - If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + - -## Step 8 - Install or update the prerelease WebView2 SDK + -Install or update the _prerelease_ WebView2 SDK for the project, as follows: + -1. In Solution Explorer, right-click the project (not the solution node above it), and then select **Manage NuGet Packages**. + - The **NuGet Package Manager** panel opens in Visual Studio. +Continue the steps below. -1. In the **NuGet Package Manager**, click the **Browse** tab. -1. To the right of the search text box, select the **Include prerelease** check box. + +## Step 6 - View the opened project -1. In the search text box, enter **Microsoft.Web.WebView2**. +1. On your local drive, open again the **WebView2Samples** solution in the same version of Visual Studio that you set up, such as Visual Studio 2019: - The **Microsoft.Web.WebView2** card appears in the search results. + * `/WebView2Samples/SampleApps/WebView2Samples.sln` -1. Click the **Microsoft.Web.WebView2** card below the search box. + or: -1. On the right, in the **Version** dropdown list, make sure **Latest prerelease** is selected: + * `/WebView2Samples-main/SampleApps/WebView2Samples.sln` - ![NuGet Package Manager with WebView2 SDK prerelease selected.](media/webview2apisample-pkg-mgr-prerelease-webview2.png) + - _The above image is from another project, but is similar. To zoom, right-click > **Open image in new tab**._ + -1. Click the **Install** (or **Update**) button. +1. Click the **OK** button. The **Retarget Projects** dialog might open: - The **Preview Changes** dialog box appears: + ![Retarget Projects dialog](./webview2apissample-images/retarget-projects.png) - ![The Preview Changes dialog box for the WebView2 NugGet package.](media/webview2apisample-webview2-pkg-preview-changes.png) + Example of installed versions: - _The above image is from another project, but is similar._ + ![Retarget - SDKs installed](./webview2apissample-images/retarget-projects-22621.png) 1. Click the **OK** button. -The WebView2 SDK is now installed for this project. +Solution Explorer shows several projects, including the **WebView2APISample** project: + +![The WebView2APISample project in Solution Explorer](./webview2apissample-images/webview2apisample-in-solution-explorer.png) + + -## Step 9 - Build the project +## Step 7 - Build the project using the installed SDK version At the top of Visual Studio, set the build target, as follows: @@ -137,7 +146,7 @@ At the top of Visual Studio, set the build target, as follows: 1. In **Solution Explorer**, right-click the **WebView2APISample** project, and then select **Build**. - ![The WebView2APISample project selected in Solution Explorer.](media/webview2apisample-project-selected.png) + ![The WebView2APISample project selected in Solution Explorer](./webview2apissample-images/webview2apisample-project-selected.png) _To zoom, right-click > **Open image in new tab**._ @@ -145,19 +154,19 @@ At the top of Visual Studio, set the build target, as follows: -## Step 10 - Run (debug) the project +## Step 8 - Run (debug) the project 1. Select **Debug** > **Start Debugging** (`F5`). Troubleshooting: if you skip the build step and immediately select **Debug** > **Start Debugging** (`F5`), a dialog box might appear, "Unable to start program: Cannot find the path specified": - ![Dialog box: Unable to start program: Cannot find the path specified.](media/webview2apisample-unable-to-start-program-cannot-find-path.png) + ![Dialog box: Unable to start program: Cannot find the path specified](./webview2apissample-images/webview2apisample-unable-to-start-program-cannot-find-path.png) To fix this problem: in **Solution Explorer**, right-click the **WebView2APISample** project, and then select **Build**. The **WebView2APISample** app window opens: - ![The WebView2APISample app window.](media/webview2apisample-app-window.png) + ![The WebView2APISample app window](./webview2apissample-images/webview2apisample-app-window.png) _To zoom, right-click > **Open image in new tab**._ @@ -166,15 +175,387 @@ At the top of Visual Studio, set the build target, as follows: 1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. + +## Step 9 - Update the prerelease WebView2 SDK + +After you initially build & run this project, update the WebView2 SDK and then re-build the project. + +To quickly see which version of the WebView2 SDK is installed in the repo's copy of the sample app at GitHub, see [packages.config](https://github.com/MicrosoftEdge/WebView2Samples/blob/main/SampleApps/WebView2APISample/packages.config). + +The repo version of this sample has a pre-release version of the WebView2 SDK installed. Below, you'll update it to the latest pre-release version of the WebView2 SDK, or confirm that the latest SDK is installed. Using a pre-release SDK gives you access to the latest functionality. + +Examine and possibly update the installed NuGet packages, as follows: + +1. In Solution Explorer, right-click the **WebView2APISample** project (not the solution node above it), and then select **Manage NuGet Packages**. + + The **NuGet Package Manager** panel opens in Visual Studio. + +1. To the right of the search text box, select the **Include prerelease** check box. + +1. In the **NuGet Package Manager**, click the **Installed** tab. On the right side of each package, check whether there is a newer version number listed as well as the existing version number. + +1. Click the **Update** tab. If updates are available for WebView2 or WIL packages, if you want, you can update the package here. + +1. On the right, in the **Version** dropdown list, make sure **Latest prerelease** is selected, if you want to be able to try the latest APIs: + + ![NuGet Package Manager with WebView2 SDK prerelease selected](./webview2apissample-images/webview2apisample-pkg-mgr-prerelease-webview2.png) + + _The above image is from another project, but is similar. To zoom, right-click > **Open image in new tab**._ + +1. Click the **Update** button. + + The **Preview Changes** dialog box appears: + + ![The Preview Changes dialog box for the WebView2 NugGet package](./webview2apissample-images/webview2apisample-webview2-pkg-preview-changes.png) + + _The above image is from another project, but is similar._ + +1. Click the **OK** button. + +The latest version of the WebView2 SDK is now installed for this project. + + + +## Step 10 - Build and run the project with updated SDK + + +1. In **Solution Explorer**, right-click the **WebView2APISample** project, and then select **Build**. + + ![WebView2APISample project selected in Solution Explorer](./webview2apissample-images/webview2apisample-project-selected.png) + +1. Select **Debug** > **Start Debugging** (`F5`). + + The **WebView2APISample** app window opens: + + ![The WebView2APISample app window](./webview2apissample-images/webview2apisample-app-window.png) + +1. Use the sample app. + +1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. + + ## Step 11 - Inspect the code -1. In the Visual Studio code editor, inspect the code. +1. In the Visual Studio code editor, inspect the code, per the following sections. - + +## Application architecture + +The API Sample App is an example of a hybrid application. It has two parts: a Win32 native part and a WebView part. +* The Win32 part can access native Windows APIs. +* The WebView container can utilize standard web technologies (HTML, CSS, JavaScript). + +This hybrid approach allows you to create and iterate faster using web technologies, while still being able to take advantage of native functionalities. The Sample App specifically demonstrates how both components can interact with each other. + +Both of these parts of the Sample App are displayed in the image below: + +![Hybrid app](./webview2apissample-images/sample-app-layout-diagram.png) + + + +1. Section One: The top part of the Sample App is a Win32 component written in C++. This part of the application takes in UI inputs from the user and uses them to control the WebView. + +2. Section Two: The main part of the Sample App is a WebView that can be repurposed using standard web technologies (HTML/CSS/JavaScript). It can be navigated to websites or local content. + + + +## Project Files + +This section briefly explains some key files within the repository. The WebView2APISample is divided vertically into components, instead of horizontally into layers. Each component implements the whole workflow of a category of example features, from listening for menu commands, to calling WebView API methods to implement them. + +#### 1. App.cpp + +This is the top-level file that runs the Sample App. It reads command line options, sets up the process environment, and handles the app's threading model. + +#### 2. AppWindow.cpp + +This file implements the application window. In this file, we first set up all the Win32 controls. Second, we initialize the WebView Environment and the WebView. Third, we add some event handlers to the WebView and create all the components that handle various features of the application. The `AppWindow` class itself handles commands from the application's Window menu. + +#### 3. FileComponent.cpp + +This component handles commands from the File menu (except for Exit), as well as the `DocumentTitleChanged` event. + +#### 4. ScriptComponent.cpp + +This component handles commands from the Script menu, which involve interacting with the WebView by injecting JavaScript, posting WebMessages, adding native objects to the webpage, or using the DevTools protocol to communicate with the webpage. + +#### 5. ProcessComponent.cpp + +This component handles commands from the Process menu, which involve interaction with the browser's process. It also handles the ProcessFailed event, in case the browser process or one of its render process crashes or is unresponsive. + +#### 6. SettingsComponent.cpp + +This component handles commands from the Settings menu, and is also in charge of copying settings from an old WebView when a new one is created. Most code that interacts with the `ICoreWebView2Settings` interface can be found here. + +#### 7. ViewComponent.cpp + +This component handles commands from the View menu, and any functionality related to sizing and visibility of the WebView. When the app window is resized, minimized, or restored, `ViewComponent` will resize, hide, or show the WebView in response. It also responds to the `ZoomFactorChanged` event. + +#### 8. ScenarioWebMessage.cpp and ScenarioWebMessage.html + +This component is created when you select the Scenario/Web Messaging menu item. It implements an example application with a C++ part and an HTML+JavaScript part, which communicate with each other by asynchronously posting and receiving messages. + +![Web Messaging: Posting and receiving messages](./webview2apissample-images/sample-app-webmessaging-screenshot.png) + + + +#### 9. ScenarioAddHostObject.cpp and ScenarioAddHostObject.html + +This component is created when you select the Scenario/Host Objects menu item. It demonstrates communication between the native app and the HTML webpage by means of host object injection. The interface of the host object is declared in `HostObjectSample.idl`, and the object itself is implemented in `HostObjectSampleImpl.cpp`. + + + +## Key Functions + +The section below briefly explains some of the key functions in the Sample App. + + +### AppWindow.cpp + +#### InitializeWebView() + +In the AppWindow file, we use the InitializeWebView() function to create the WebView2 environment by using [CreateCoreWebView2EnvironmentWithOptions](/microsoft-edge/webview2/reference/win32/webview2-idl#createcorewebview2environmentwithoptions). + +Once we've created the environment, we create the WebView by using `CreateCoreWebView2Controller`. + +To see these API calls in action, refer to the following code snippet from `InitializeWebView()`. + +```cpp +HRESULT hr = CreateCoreWebView2EnvironmentWithOptions( + subFolder, nullptr, options.Get(), + Callback( + this, &AppWindow::OnCreateEnvironmentCompleted) + .Get()); +if (!SUCCEEDED(hr)) +{ + if (hr == HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND)) + { + MessageBox( + m_mainWindow, + L"Couldn't find Edge installation. " + "Do you have a version installed that's compatible with this " + "WebView2 SDK version?", + nullptr, MB_OK); + } + else + { + ShowFailure(hr, L"Failed to create webview environment"); + } +} +``` + +#### OnCreateEnvironmentCompleted() + +This callback function is passed to `CreateCoreWebView2EnvironmentWithOptions` in `InitializeWebView()`. It stored the environment pointer and then uses it to create a new WebView. + +```cpp +HRESULT AppWindow::OnCreateEnvironmentCompleted( + HRESULT result, ICoreWebView2Environment* environment) +{ + CHECK_FAILURE(result); + + m_webViewEnvironment = environment; + + CHECK_FAILURE(m_webViewEnvironment->CreateCoreWebView2Controller( + m_mainWindow, Callback( + this, &AppWindow::OnCreateCoreWebView2ControllerCompleted) + .Get())); + return S_OK; +} +``` + +#### OnCreateCoreWebView2ControllerCompleted() + +This callback function is passed to `CreateCoreWebView2Controller` in `InitializeWebView()`. Here, we initialize the WebView-related state, register some event handlers, and create the app components. + +#### RegisterEventHandlers() + +This function is called within `CreateCoreWebView2Controller`. It sets up some of the event handlers used by the application, and adds them to the WebView. + +To read more about event handlers in WebView2, you can refer to this [documentation](/microsoft-edge/webview2/reference/win32/icorewebview2). + +Below is a code snippet from `RegisterEventHandlers()`, where we set up an event handler for the `NewWindowRequested` event. This event is fired when JavaScript in the webpage calls `window.open()`, and our handler makes a new `AppWindow` and passes the new window's WebView back to the browser so it can return it from the `window.open()` call. Unlike our calls to `CreateCoreWebView2EnvironmentWithOptions` and `CreateCoreWebView2Controller`, instead of providing a method for the callback, we just provide a C++ lambda right then and there. + +```cpp +CHECK_FAILURE(m_webView->add_NewWindowRequested( + Callback( + [this]( + ICoreWebView2* sender, + ICoreWebView2NewWindowRequestedEventArgs* args) { + wil::com_ptr deferral; + CHECK_FAILURE(args->GetDeferral(&deferral)); + + auto newAppWindow = new AppWindow(L""); + newAppWindow->m_isPopupWindow = true; + newAppWindow->m_onWebViewFirstInitialized = [args, deferral, newAppWindow]() { + CHECK_FAILURE(args->put_NewWindow(newAppWindow->m_webView.get())); + CHECK_FAILURE(args->put_Handled(TRUE)); + CHECK_FAILURE(deferral->Complete()); + }; + + return S_OK; + }) + .Get(), + nullptr)); +``` + +### ScenarioWebMessage + +The `ScenarioWebMessage` files show how the Win32 Host can modify the WebView, how the WebView can modify the Win32Host, and how the WebView can modify itself by accessing information from the Win32 Host. This is done asynchronously. + +The following sections demonstrate how each discrete function works using the Sample App and then explains how to implement this functionality. + +First, navigate to the ScenarioWebMessage application within the Sample App, using the following steps: + +1. Open the Sample App +2. Click on Scenario +3. Click on Web Messaging + +The WebView should display a simple webpage titled: "WebMessage sample page". The code for this page can be found in the `ScenarioWebMessage.html` file. + +![Web Messaging for posting and receiving messages](./webview2apissample-images/sample-app-webmessaging-screenshot.png) + +To better understand ScenarioWebMessage functionality, you can either follow the instructions on the page or the steps detailed below. + +#### 1. Posting Messages (Win32 Host to WebView) + +The following steps show how the Win32 Host can modify a WebView. In this example, you will turn the text blue: + +1. Click on Script in the Toolbar +2. Click on Post Web Message JSON + +A dialog box with the pre-written code `{"SetColor":"blue"}` should appear. + +3. Click OK + +The text under Posting Messages should now be blue. + +Here's how it works: + +1. In `ScriptComponent.cpp`, we use [PostWebMessageAsJson](/microsoft-edge/webview2/reference/win32/icorewebview2#postwebmessageasjson) to post user input to the `ScenarioMessage.html` web application. + +```cpp +// Prompt the user for some JSON and then post it as a web message. +void ScriptComponent::SendJsonWebMessage() +{ + TextInputDialog dialog( + m_appWindow->GetMainWindow(), + L"Post Web Message JSON", + L"Web message JSON:", + L"Enter the web message as JSON.", + L"{\"SetColor\":\"blue\"}"); + if (dialog.confirmed) + { + m_webView->PostWebMessageAsJson(dialog.input.c_str()); + } +} +``` + +2. Within the web application, event listeners are used to receive and respond to the web message. The code snippet below is from `ScenarioWebMessage.html`. The event listener changes the color of the text if it reads "SetColor". + +```js +window.chrome.webview.addEventListener('message', arg => { + if ("SetColor" in arg.data) { + document.getElementById("colorable").style.color = arg.data.SetColor; + } +}); +``` + +#### 2. Receiving Messages (WebView to Win32 Host) + +The following steps show how the WebView can modify the Win32 Host App by changing the title of the Win32 App: + +1. Locate the Title of the Sample App - the top left of the window next to the icon. +2. Under the Receiving Message section, fill out the form with the new title of your choice. +3. Click Send + +Locate the Title of the Sample App, it should have changed to the title you have just inputted. + +Here's how it works: + +1. Within `ScenarioWebMessage.html`, we call [window.chrome.webview.postMessage()](https://developer.mozilla.org/docs/Web/API/Window/postMessage) to send the user input to the host application. Refer to code snippet below: + +```js +function SetTitleText() { + let titleText = document.getElementById("title-text"); + window.chrome.webview.postMessage(`SetTitleText ${titleText.value}`); +} +``` + +2. Within `ScenarioWebMessage.cpp`, we use [add_WebMessageReceived](/microsoft-edge/webview2/reference/win32/icorewebview2#add_webmessagereceived) to register the event handler. When we receive the event, after validating the input, we change the title of the App Window. + +```cpp +// Setup the web message received event handler before navigating to +// ensure we don't miss any messages. +CHECK_FAILURE(m_webview->add_WebMessageReceived( + Microsoft::WRL::Callback( + [this](ICoreWebView2* sender, ICoreWebView2WebMessageReceivedEventArgs* args) +{ + wil::unique_cotaskmem_string uri; + CHECK_FAILURE(args->get_Source(&uri)); + + // Always validate that the origin of the message is what you expect. + if (uri.get() != m_sampleUri) + { + return S_OK; + } + wil::unique_cotaskmem_string messageRaw; + CHECK_FAILURE(args->TryGetWebMessageAsString(&messageRaw)); + std::wstring message = messageRaw.get(); + + if (message.compare(0, 13, L"SetTitleText ") == 0) + { + m_appWindow->SetTitleText(message.substr(13).c_str()); + } + return S_OK; +}).Get(), &m_webMessageReceivedToken)); +``` + +#### 3. Roundtrip (WebView to WebView) + +The following steps show how the WebView can get information from the Win32 Host and modify itself by displaying the size of the Win32 App. + +1. Under RoundTrip, click GetWindowBounds + +The box underneath the button should display the bounds for the Sample App. + +Here's how it works: + +1. When the 'Get window bounds' button is clicked, the `GetWindowBounds` function in `ScenarioWebMessage.html` gets called. It uses [window.chrome.webview.postMessage()](https://developer.mozilla.org/docs/Web/API/Window/postMessage) to send a message to the host application. + +```js +function GetWindowBounds() { + window.chrome.webview.postMessage("GetWindowBounds"); + } +``` + +2. Within `ScenarioWebMessage.cpp`, we use [add_WebMessageReceived](/microsoft-edge/webview2/reference/win32/icorewebview2#add_webmessagereceived) to register the received event handler. After validating the input, the event handler gets window bounds from the App Window. [PostWebMessageAsJson](/microsoft-edge/webview2/reference/win32/icorewebview2#postwebmessageasjson) sends the bounds to the web application. + +```cpp +if (message.compare(L"GetWindowBounds") == 0) +{ + RECT bounds = m_appWindow->GetWindowBounds(); + std::wstring reply = + L"{\"WindowBounds\":\"Left:" + std::to_wstring(bounds.left) + + L"\\nTop:" + std::to_wstring(bounds.top) + + L"\\nRight:" + std::to_wstring(bounds.right) + + L"\\nBottom:" + std::to_wstring(bounds.bottom) + + L"\"}"; + CHECK_FAILURE(sender->PostWebMessageAsJson(reply.c_str())); +} +``` + +3. Within `ScenarioWebMessage.html`, an event listener responds to the WindowBounds message and displays the bounds of the window: + +```js +window.chrome.webview.addEventListener('message', arg => { + if ("WindowBounds" in arg.data) { + document.getElementById("window-bounds").value = arg.data.WindowBounds; + } +}); +``` diff --git a/microsoft-edge/webview2/samples/webview2browser-images/WebView2Browser.png b/microsoft-edge/webview2/samples/webview2browser-images/WebView2Browser.png new file mode 100644 index 0000000000..e9f8f0aea4 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2browser-images/WebView2Browser.png differ diff --git a/microsoft-edge/webview2/samples/webview2browser-images/layout.png b/microsoft-edge/webview2/samples/webview2browser-images/layout.png new file mode 100644 index 0000000000..68bfb620a1 Binary files /dev/null and b/microsoft-edge/webview2/samples/webview2browser-images/layout.png differ diff --git a/microsoft-edge/webview2/samples/webview2browser.md b/microsoft-edge/webview2/samples/webview2browser.md new file mode 100644 index 0000000000..35bac34742 --- /dev/null +++ b/microsoft-edge/webview2/samples/webview2browser.md @@ -0,0 +1,877 @@ +--- +title: Win32 sample WebView2Browser +description: "A web browser built with the Microsoft Edge WebView2 control." +author: MSEdgeTeam +ms.author: msedgedevrel +ms.topic: conceptual +ms.prod: microsoft-edge +ms.technology: webview +ms.date: 07/18/2022 +--- +# Win32 sample WebView2Browser + + + +This sample, **WebView2Browser**, is a web browser built with the [Microsoft Edge WebView2](https://aka.ms/webview2) control. + +This sample has its own dedicated repo. + +* Sample name: **WebView2Browser** +* Repo: [WebView2Browser](https://github.com/MicrosoftEdge/WebView2Browser) +* Solution file: **WebViewBrowserApp.sln** + +![The WebView2Browser sample app](./webview2browser-images/WebView2Browser.png) + + + + +**WebView2Browser** is a sample Windows desktop application demonstrating the capabilities of the WebView2 control. The **WebView2Browser** sample app uses multiple WebView2 instances. + +This sample is built as a Win32 [Visual Studio 2019](https://visualstudio.microsoft.com/vs/) project. It uses C++ and JavaScript in the WebView2 environment. + +**WebView2Browser** shows some of the simplest uses of WebView2, such as creating and navigating a WebView, but also some more complex workflows like using the [PostWebMessageAsJson API](/microsoft-edge/webview2/reference/win32/icorewebview2#postwebmessageasjson) to communicate across WebView2 controls in separate environments. This is a rich code sample to demonstrate how you can use WebView2 APIs to build your own app. + + + +## Step 1: Install a preview channel of Microsoft Edge + +* If not installed yet, install a [preview channel of Microsoft Edge](https://www.microsoftedgeinsider.com/download/) on a supported OS. + + + +## Step 2: Install Visual Studio + +1. Install [Visual Studio](https://visualstudio.microsoft.com/vs/), including C++ support. + +The [WebView2 Runtime](https://developer.microsoft.com/microsoft-edge/webview2/) is recommended for the installation. The minimum version is 86.0.622.38. + + + +## Step 3: Clone the WebView2Samples repo + +* Clone (or download as `.zip`) the **WebView2Samples** repo. See [Clone the WebView2Samples repo](../how-to/machine-setup.md#clone-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. + + + +## Step 4: Open the solution in Visual Studio + +1. Open the solution in Visual Studio 2019. The WebView2 SDK is already included as a NuGet package in the project. If you want to use Visual Studio 2017, change the project's Platform Toolset in **Project Properties > Configuration properties > General > Platform Toolset**. You might also need to change the Windows SDK to the latest version. + +1. Make the changes listed below, if you're using a Windows version below Windows 10. + +#### Using versions below Windows 10 + +If you want to build and run the browser in versions of Windows before Windows 10, make the following changes. This is required because of how DPI is handled in Windows 10 vs previous versions of Windows. + +1. If you want to build and run the browser in versions of Windows before Windows 10: In `WebViewBrowserApp.cpp`, change `SetProcessDpiAwarenessContext` to `SetProcessDPIAware`: + +```cpp +int APIENTRY wWinMain(_In_ HINSTANCE hInstance, + _In_opt_ HINSTANCE hPrevInstance, + _In_ LPWSTR lpCmdLine, + _In_ int nCmdShow) +{ + UNREFERENCED_PARAMETER(hPrevInstance); + UNREFERENCED_PARAMETER(lpCmdLine); + + // Call SetProcessDPIAware() instead when using Windows 7 or any version + // below 1703 (Windows 10). + SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2); + + BrowserWindow::RegisterClass(hInstance); + + // ... +``` + +1. If you want to build and run the browser in versions of Windows before Windows 10: In `BrowserWindow.cpp`, remove or comment out the following call to `GetDpiForWindow`: + +```cpp +int BrowserWindow::GetDPIAwareBound(int bound) +{ + // Remove the GetDpiForWindow call when using Windows 7 or any version + // below 1607 (Windows 10). You will also have to make sure the build + // directory is clean before building again. + return (bound * GetDpiForWindow(m_hWnd) / DEFAULT_DPI); +} +``` + + + +## Step 5: Build and run the app + +1. Set the target you want to build (such as Debug or Release, targeting x86 or x64). + +1. Build the solution. + +1. Run (or Debug) the app. + +1. Close the app. + + + +## Step 6: Update the WebView2 SDK + +* Update the version of the WebView2 SDK, in Visual Studio. To do this, right-click the project and then click **Manage NuGet Packages**. + + + +## Step 7: Build and run the app with updated WebView2 SDK + +* Build and run the app again. + + + +## Browser layout + + +The WebView2Browser sample app uses multiple WebView2 instances. + +WebView2Browser has a multi-WebView approach to integrate web content and application UI into a Windows Desktop application. This allows the browser to use standard web technologies (HTML, CSS, JavaScript) to light up the interface but also enables the app to fetch favicons from the web and use IndexedDB for storing favorites and history. + +The multi-WebView approach involves using two separate WebView environments (each with its own user data directory): one for the UI WebViews and the other for all content WebViews. UI WebViews (controls and options dropdown) use the UI environment while web content WebViews (one per tab) use the content environment. + +![Browser layout](./webview2browser-images/layout.png) + + + + +## Features + +The **WebView2Browser** sample provides all the functionalities to make a basic web browser, but there's plenty of room for you to play around. + +The **WebView2Browser** sample implements the following features: +* Go back/forward +* Reload page +* Cancel navigation +* Multiple tabs +* History +* Favorites +* Search from the address bar +* Page security status +* Clearing cache and cookies + + + +## WebView2 APIs + +WebView2Browser makes use of a handful of the APIs available in WebView2. For the APIs not used here, you can find more about them in the [Microsoft Edge WebView2 Reference](/microsoft-edge/webview2/reference/win32). The following is a list of the most interesting APIs WebView2Browser uses and the features they enable. + +API | Features +:--- | :--- +`CreateCoreWebView2EnvironmentWithOptions` | Used to create the environments for UI and content WebViews. Different user data directories are passed to isolate UI from web content. | +`ICoreWebView2` | There are several WebViews in WebView2Browser and most features make use of members in this interface, the table below shows how they're used. +`ICoreWebView2DevToolsProtocolEventReceivedEventHandler` | Used along with add_DevToolsProtocolEventReceived to listen for CDP security events to update the lock icon in the browser UI. | +`ICoreWebView2DevToolsProtocolEventReceiver` | Used along with add_DevToolsProtocolEventReceived to listen for CDP security events to update the lock icon in the browser UI. | +`ICoreWebView2ExecuteScriptCompletedHandler` | Used along with ExecuteScript to get the title and favicon from the visited page. | +`ICoreWebView2FocusChangedEventHandler` | Used along with add_LostFocus to hide the browser options dropdown when it loses focus. +`ICoreWebView2HistoryChangedEventHandler` | Used along with add_HistoryChanged to update the navigation buttons in the browser UI. | +`ICoreWebView2Controller` | There are several WebViewControllers in WebView2Browser and we fetch the associated WebViews from them. +`ICoreWebView2NavigationCompletedEventHandler` | Used along with add_NavigationCompleted to update the reload button in the browser UI. +`ICoreWebView2Settings` | Used to disable DevTools in the browser UI. +`ICoreWebView2SourceChangedEventHandler` | Used along with add_SourceChanged to update the address bar in the browser UI. | +`ICoreWebView2WebMessageReceivedEventHandler` | This is one of the most important APIs to WebView2Browser. Most functionalities involving communication across WebViews use this. + +ICoreWebView2 API | Features +:--- | :--- +`add_NavigationStarting` | Used to display the cancel navigation button in the controls WebView. +`add_SourceChanged` | Used to update the address bar. +`add_HistoryChanged` | Used to update go back/forward buttons. +`add_NavigationCompleted` | Used to display the reload button once a navigation completes. +`ExecuteScript` | Used to get the title and favicon of a visited page. +`PostWebMessageAsJson` | Used to communicate WebViews. All messages use JSON to pass parameters needed. +`add_WebMessageReceived` | Used to handle web messages posted to the WebView. +`CallDevToolsProtocolMethod` | Used to enable listening for security events, which will notify of security status changes in a document. + +ICoreWebView2Controller API | Feature(s) +:--- | :--- +`get_CoreWebView2` | Used to get the CoreWebView2 associated with this CoreWebView2Controller. +`add_LostFocus` | Used to hide the options dropdown when the user clicks away from it. + + + +## Implementing the features + +The sections below describe how some of the features in WebView2Browser were implemented. You can look at the source code for more details about how everything works here. + +**Contents:** + +* [The basics](#the-basics) + * [Set up the environment, create a WebView](#set-up-the-environment-create-a-webview) + * [Navigate to web page](#navigate-to-web-page) + * [Updating the address bar](#updating-the-address-bar) + * [Going back, going forward](#going-back-going-forward) +* [Some interesting features](#some-interesting-features) + * [Communicating the WebViews](#communicating-the-webviews) + * [Tab handling](#tab-handling) + * [Updating the security icon](#updating-the-security-icon) + * [Populating the history](#populating-the-history) +* [Handling JSON and URIs](#handling-json-and-uris) + + + +## The basics + +### Set up the environment, create a WebView + +WebView2 allows you to host web content in your Windows app. It exposes the globals [CreateCoreWebView2Environment](/microsoft-edge/webview2/reference/win32/webview2-idl#createcorewebview2environment) and [CreateCoreWebView2EnvironmentWithOptions](/microsoft-edge/webview2/reference/win32/webview2-idl#createcorewebview2environmentwithoptions) from which we can create the two separate environments for the browser's UI and content. + +```cpp + // Get directory for user data. This will be kept separated from the + // directory for the browser UI data. + std::wstring userDataDirectory = GetAppDataDirectory(); + userDataDirectory.append(L"\\User Data"); + + // Create WebView environment for web content requested by the user. All + // tabs will be created from this environment and kept isolated from the + // browser UI. This environment is created first so the UI can request new + // tabs when it's ready. + HRESULT hr = CreateCoreWebView2EnvironmentWithOptions(nullptr, userDataDirectory.c_str(), + L"", Callback( + [this](HRESULT result, ICoreWebView2Environment* env) -> HRESULT + { + RETURN_IF_FAILED(result); + + m_contentEnv = env; + HRESULT hr = InitUIWebViews(); + + if (!SUCCEEDED(hr)) + { + OutputDebugString(L"UI WebViews environment creation failed\n"); + } + + return hr; + }).Get()); +``` + +```cpp +HRESULT BrowserWindow::InitUIWebViews() +{ + // Get data directory for browser UI data + std::wstring browserDataDirectory = GetAppDataDirectory(); + browserDataDirectory.append(L"\\Browser Data"); + + // Create WebView environment for browser UI. A separate data directory is + // used to isolate the browser UI from web content requested by the user. + return CreateCoreWebView2EnvironmentWithOptions(nullptr, browserDataDirectory.c_str(), + L"", Callback( + [this](HRESULT result, ICoreWebView2Environment* env) -> HRESULT + { + // Environment is ready, create the WebView + m_uiEnv = env; + + RETURN_IF_FAILED(CreateBrowserControlsWebView()); + RETURN_IF_FAILED(CreateBrowserOptionsWebView()); + + return S_OK; + }).Get()); +} +``` + +We use the [ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler](/microsoft-edge/webview2/reference/win32/icorewebview2createcorewebview2environmentcompletedhandler) to create the UI WebViews once the environment is ready. + +```cpp +HRESULT BrowserWindow::CreateBrowserControlsWebView() +{ + return m_uiEnv->CreateCoreWebView2Controller(m_hWnd, Callback( + [this](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT + { + if (!SUCCEEDED(result)) + { + OutputDebugString(L"Controls WebView creation failed\n"); + return result; + } + // WebView created + m_controlsController = controller; + CheckFailure(m_controlsController->get_CoreWebView2(&m_controlsWebView), L""); + + wil::com_ptr settings; + RETURN_IF_FAILED(m_controlsWebView->get_Settings(&settings)); + RETURN_IF_FAILED(settings->put_AreDevToolsEnabled(FALSE)); + + RETURN_IF_FAILED(m_controlsController->add_ZoomFactorChanged(Callback( + [](ICoreWebView2Controller* controller, IUnknown* args) -> HRESULT + { + controller->put_ZoomFactor(1.0); + return S_OK; + } + ).Get(), &m_controlsZoomToken)); + + RETURN_IF_FAILED(m_controlsWebView->add_WebMessageReceived(m_uiMessageBroker.Get(), &m_controlsUIMessageBrokerToken)); + RETURN_IF_FAILED(ResizeUIWebViews()); + + std::wstring controlsPath = GetFullPathFor(L"wvbrowser_ui\\controls_ui\\default.html"); + RETURN_IF_FAILED(m_controlsWebView->Navigate(controlsPath.c_str())); + + return S_OK; + }).Get()); +} +``` + +We're setting up a few things here. The [ICoreWebView2Settings](/microsoft-edge/webview2/reference/win32/icorewebview2settings) interface is used to disable DevTools in the WebView powering the browser controls. We're also adding a handler for received web messages. This handler will enable us to do something when the user interacts with the controls in this WebView. + + +#### Navigate to web page + +You can navigate to a web page by entering its URI in the address bar. When pressing Enter, the controls WebView will post a web message to the host app so it can navigate the active tab to the specified location. Code below shows how the host Win32 application will handle that message. + +```cpp + case MG_NAVIGATE: + { + std::wstring uri(args.at(L"uri").as_string()); + std::wstring browserScheme(L"browser://"); + + if (uri.substr(0, browserScheme.size()).compare(browserScheme) == 0) + { + // No encoded search URI + std::wstring path = uri.substr(browserScheme.size()); + if (path.compare(L"favorites") == 0 || + path.compare(L"settings") == 0 || + path.compare(L"history") == 0) + { + std::wstring filePath(L"wvbrowser_ui\\content_ui\\"); + filePath.append(path); + filePath.append(L".html"); + std::wstring fullPath = GetFullPathFor(filePath.c_str()); + CheckFailure(m_tabs.at(m_activeTabId)->m_contentWebView->Navigate(fullPath.c_str()), L"Can't navigate to browser page."); + } + else + { + OutputDebugString(L"Requested unknown browser page\n"); + } + } + else if (!SUCCEEDED(m_tabs.at(m_activeTabId)->m_contentWebView->Navigate(uri.c_str()))) + { + CheckFailure(m_tabs.at(m_activeTabId)->m_contentWebView->Navigate(args.at(L"encodedSearchURI").as_string().c_str()), L"Can't navigate to requested page."); + } + } + break; +``` + +WebView2Browser will check the URI against browser pages (i.e. favorites, settings, history) and navigate to the requested location or use the provided URI to search Bing as a fallback. + + +#### Updating the address bar + +The address bar is updated every time there is a change in the active tab's document source and along with other controls when switching tabs. Each WebView will fire an event when the state of the document changes, we can use this event to get the new source on updates and forward the change to the controls WebView (we'll also update the go back and go forward buttons). + +```cpp + // Register event handler for doc state change + RETURN_IF_FAILED(m_contentWebView->add_SourceChanged(Callback( + [this, browserWindow](ICoreWebView2* webview, ICoreWebView2SourceChangedEventArgs* args) -> HRESULT + { + BrowserWindow::CheckFailure(browserWindow->HandleTabURIUpdate(m_tabId, webview), L"Can't update address bar"); + + return S_OK; + }).Get(), &m_uriUpdateForwarderToken)); +``` + +```cpp +HRESULT BrowserWindow::HandleTabURIUpdate(size_t tabId, ICoreWebView2* webview) +{ + wil::unique_cotaskmem_string source; + RETURN_IF_FAILED(webview->get_Source(&source)); + + web::json::value jsonObj = web::json::value::parse(L"{}"); + jsonObj[L"message"] = web::json::value(MG_UPDATE_URI); + jsonObj[L"args"] = web::json::value::parse(L"{}"); + jsonObj[L"args"][L"tabId"] = web::json::value::number(tabId); + jsonObj[L"args"][L"uri"] = web::json::value(source.get()); + + // ... + + RETURN_IF_FAILED(PostJsonToWebView(jsonObj, m_controlsWebView.Get())); + + return S_OK; +} + +HRESULT BrowserWindow::HandleTabHistoryUpdate(size_t tabId, ICoreWebView2* webview) +{ + // ... + + BOOL canGoForward = FALSE; + RETURN_IF_FAILED(webview->get_CanGoForward(&canGoForward)); + jsonObj[L"args"][L"canGoForward"] = web::json::value::boolean(canGoForward); + + BOOL canGoBack = FALSE; + RETURN_IF_FAILED(webview->get_CanGoBack(&canGoBack)); + jsonObj[L"args"][L"canGoBack"] = web::json::value::boolean(canGoBack); + + RETURN_IF_FAILED(PostJsonToWebView(jsonObj, m_controlsWebView.Get())); + + return S_OK; +} +``` + +We have sent the `MG_UPDATE_URI` message along with the URI to the controls WebView. Now we want to reflect those changes on the tab state and update the UI if necessary. + +```javascript + case commands.MG_UPDATE_URI: + if (isValidTabId(args.tabId)) { + const tab = tabs.get(args.tabId); + let previousURI = tab.uri; + + // Update the tab state + tab.uri = args.uri; + tab.uriToShow = args.uriToShow; + tab.canGoBack = args.canGoBack; + tab.canGoForward = args.canGoForward; + + // If the tab is active, update the controls UI + if (args.tabId == activeTabId) { + updateNavigationUI(message); + } + + // ... + } + break; +``` + + +#### Going back, going forward + +Each WebView will keep a history for the navigations it has performed so we only need to connect the browser UI with the corresponding methods. If the active tab's WebView can be navigated back/forward, the buttons will post a web message to the host application when clicked. + +The JavaScript side: + +```javascript + document.querySelector('#btn-forward').addEventListener('click', function(e) { + if (document.getElementById('btn-forward').className === 'btn') { + var message = { + message: commands.MG_GO_FORWARD, + args: {} + }; + window.chrome.webview.postMessage(message); + } + }); + + document.querySelector('#btn-back').addEventListener('click', function(e) { + if (document.getElementById('btn-back').className === 'btn') { + var message = { + message: commands.MG_GO_BACK, + args: {} + }; + window.chrome.webview.postMessage(message); + } + }); +``` + +The host application side: + +```cpp + case MG_GO_FORWARD: + { + CheckFailure(m_tabs.at(m_activeTabId)->m_contentWebView->GoForward(), L""); + } + break; + case MG_GO_BACK: + { + CheckFailure(m_tabs.at(m_activeTabId)->m_contentWebView->GoBack(), L""); + } + break; +``` + + +#### Reloading, stop navigation + +We use the `NavigationStarting` event fired by a content WebView to update its associated tab loading state in the controls WebView. Similarly, when a WebView fires the `NavigationCompleted` event, we use that event to instruct the controls WebView to update the tab state. The active tab state in the controls WebView will determine whether to show the reload or the cancel button. Each of those will post a message back to the host application when clicked, so that the WebView for that tab can be reloaded or have its navigation canceled, accordingly. + +```javascript +function reloadActiveTabContent() { + var message = { + message: commands.MG_RELOAD, + args: {} + }; + window.chrome.webview.postMessage(message); +} + + // ... + + document.querySelector('#btn-reload').addEventListener('click', function(e) { + var btnReload = document.getElementById('btn-reload'); + if (btnReload.className === 'btn-cancel') { + var message = { + message: commands.MG_CANCEL, + args: {} + }; + window.chrome.webview.postMessage(message); + } else if (btnReload.className === 'btn') { + reloadActiveTabContent(); + } + }); +``` + +```cpp + case MG_RELOAD: + { + CheckFailure(m_tabs.at(m_activeTabId)->m_contentWebView->Reload(), L""); + } + break; + case MG_CANCEL: + { + CheckFailure(m_tabs.at(m_activeTabId)->m_contentWebView->CallDevToolsProtocolMethod(L"Page.stopLoading", L"{}", nullptr), L""); + } +``` + + + +## Some interesting features + + +#### Communicating the WebViews + +We need to communicate the WebViews that power the tabs and UI, so that user interactions in one tab's WebView have the desired effect in the other WebView. WebView2Browser makes use of set of very useful WebView2 APIs for this purpose, including [PostWebMessageAsJson](/microsoft-edge/webview2/reference/win32/icorewebview2#postwebmessageasjson), [add_WebMessageReceived](/microsoft-edge/webview2/reference/win32/icorewebview2#add_webmessagereceived) and [ICoreWebView2WebMessageReceivedEventHandler](/microsoft-edge/webview2/reference/win32/icorewebview2webmessagereceivedeventhandler). + +On the JavaScript side, we're making use of the `window.chrome.webview` object exposed to call the `postMessage` method and add an event lister for received messages. + +```cpp +HRESULT BrowserWindow::CreateBrowserControlsWebView() +{ + return m_uiEnv->CreateCoreWebView2Controller(m_hWnd, Callback( + [this](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT + { + // ... + + RETURN_IF_FAILED(m_controlsWebView->add_WebMessageReceived(m_uiMessageBroker.Get(), &m_controlsUIMessageBrokerToken)); + + // ... + + return S_OK; + }).Get()); +} +``` + +```cpp +HRESULT BrowserWindow::PostJsonToWebView(web::json::value jsonObj, ICoreWebView2* webview) +{ + utility::stringstream_t stream; + jsonObj.serialize(stream); + + return webview->PostWebMessageAsJson(stream.str().c_str()); +} + +// ... + +HRESULT BrowserWindow::HandleTabNavStarting(size_t tabId, ICoreWebView2* webview) +{ + web::json::value jsonObj = web::json::value::parse(L"{}"); + jsonObj[L"message"] = web::json::value(MG_NAV_STARTING); + jsonObj[L"args"] = web::json::value::parse(L"{}"); + jsonObj[L"args"][L"tabId"] = web::json::value::number(tabId); + + return PostJsonToWebView(jsonObj, m_controlsWebView.Get()); +} +``` + +```javascript +function init() { + window.chrome.webview.addEventListener('message', messageHandler); + refreshControls(); + refreshTabs(); + + createNewTab(true); +} + +// ... + +function reloadActiveTabContent() { + var message = { + message: commands.MG_RELOAD, + args: {} + }; + window.chrome.webview.postMessage(message); +} +``` + +#### Tab handling + +A new tab will be created whenever the user clicks on the **new tab** button to the right of the open tabs. The control's WebView will post a message to the host application to create the WebView for that tab and create an object tracking its state. + +```javascript +function createNewTab(shouldBeActive) { + const tabId = getNewTabId(); + + var message = { + message: commands.MG_CREATE_TAB, + args: { + tabId: parseInt(tabId), + active: shouldBeActive || false + } + }; + + window.chrome.webview.postMessage(message); + + tabs.set(parseInt(tabId), { + title: 'New Tab', + uri: '', + uriToShow: '', + favicon: 'img/favicon.png', + isFavorite: false, + isLoading: false, + canGoBack: false, + canGoForward: false, + securityState: 'unknown', + historyItemId: INVALID_HISTORY_ID + }); + + loadTabUI(tabId); + + if (shouldBeActive) { + switchToTab(tabId, false); + } +} +``` + +On the host app side, the registered [ICoreWebView2WebMessageReceivedEventHandler](/microsoft-edge/webview2/reference/win32/icorewebview2webmessagereceivedeventhandler) will catch the message and create the WebView for that tab. + +```cpp + case MG_CREATE_TAB: + { + size_t id = args.at(L"tabId").as_number().to_uint32(); + bool shouldBeActive = args.at(L"active").as_bool(); + std::unique_ptr newTab = Tab::CreateNewTab(m_hWnd, m_contentEnv.Get(), id, shouldBeActive); + + std::map>::iterator it = m_tabs.find(id); + if (it == m_tabs.end()) + { + m_tabs.insert(std::pair>(id, std::move(newTab))); + } + else + { + m_tabs.at(id)->m_contentWebView->Close(); + it->second = std::move(newTab); + } + } + break; +``` + +```cpp +std::unique_ptr Tab::CreateNewTab(HWND hWnd, ICoreWebView2Environment* env, size_t id, bool shouldBeActive) +{ + std::unique_ptr tab = std::make_unique(); + + tab->m_parentHWnd = hWnd; + tab->m_tabId = id; + tab->SetMessageBroker(); + tab->Init(env, shouldBeActive); + + return tab; +} + +HRESULT Tab::Init(ICoreWebView2Environment* env, bool shouldBeActive) +{ + return env->CreateCoreWebView2Controller(m_parentHWnd, Callback( + [this, shouldBeActive](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT { + if (!SUCCEEDED(result)) + { + OutputDebugString(L"Tab WebView creation failed\n"); + return result; + } + m_contentController = controller; + BrowserWindow::CheckFailure(m_contentController->get_CoreWebView2(&m_contentWebView), L""); + BrowserWindow* browserWindow = reinterpret_cast(GetWindowLongPtr(m_parentHWnd, GWLP_USERDATA)); + RETURN_IF_FAILED(m_contentWebView->add_WebMessageReceived(m_messageBroker.Get(), &m_messageBrokerToken)); + + // Register event handler for history change + RETURN_IF_FAILED(m_contentWebView->add_HistoryChanged(Callback( + [this, browserWindow](ICoreWebView2* webview, IUnknown* args) -> HRESULT + { + BrowserWindow::CheckFailure(browserWindow->HandleTabHistoryUpdate(m_tabId, webview), L"Can't update go back/forward buttons."); + + return S_OK; + }).Get(), &m_historyUpdateForwarderToken)); + + // Register event handler for source change + RETURN_IF_FAILED(m_contentWebView->add_SourceChanged(Callback( + [this, browserWindow](ICoreWebView2* webview, ICoreWebView2SourceChangedEventArgs* args) -> HRESULT + { + BrowserWindow::CheckFailure(browserWindow->HandleTabURIUpdate(m_tabId, webview), L"Can't update address bar"); + + return S_OK; + }).Get(), &m_uriUpdateForwarderToken)); + + RETURN_IF_FAILED(m_contentWebView->add_NavigationStarting(Callback( + [this, browserWindow](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs* args) -> HRESULT + { + BrowserWindow::CheckFailure(browserWindow->HandleTabNavStarting(m_tabId, webview), L"Can't update reload button"); + + return S_OK; + }).Get(), &m_navStartingToken)); + + RETURN_IF_FAILED(m_contentWebView->add_NavigationCompleted(Callback( + [this, browserWindow](ICoreWebView2* webview, ICoreWebView2NavigationCompletedEventArgs* args) -> HRESULT + { + BrowserWindow::CheckFailure(browserWindow->HandleTabNavCompleted(m_tabId, webview, args), L"Can't update reload button"); + return S_OK; + }).Get(), &m_navCompletedToken)); + + // Handle security state updates + + RETURN_IF_FAILED(m_contentWebView->Navigate(L"https://www.bing.com")); + browserWindow->HandleTabCreated(m_tabId, shouldBeActive); + + return S_OK; + }).Get()); +} +``` + +The tab registers all handlers so it can forward updates to the controls WebView when events fire. The tab is ready and will be shown on the content area of the browser. Clicking on a tab in the controls WebView will post a message to the host application, which will in turn hide the WebView for the previously active tab and show the one for the clicked tab. + +```cpp +HRESULT BrowserWindow::SwitchToTab(size_t tabId) +{ + size_t previousActiveTab = m_activeTabId; + + RETURN_IF_FAILED(m_tabs.at(tabId)->ResizeWebView()); + RETURN_IF_FAILED(m_tabs.at(tabId)->m_contentWebView->put_IsVisible(TRUE)); + m_activeTabId = tabId; + + if (previousActiveTab != INVALID_TAB_ID && previousActiveTab != m_activeTabId) + { + RETURN_IF_FAILED(m_tabs.at(previousActiveTab)->m_contentWebView->put_IsVisible(FALSE)); + } + + return S_OK; +} +``` + +#### Updating the security icon + +We use the [CallDevToolsProtocolMethod](/microsoft-edge/webview2/reference/win32/icorewebview2#calldevtoolsprotocolmethod) to enable listening for security events. Whenever a `securityStateChanged` event is fired, we will use the new state to update the security icon on the controls WebView. + +```cpp + // Enable listening for security events to update secure icon + RETURN_IF_FAILED(m_contentWebView->CallDevToolsProtocolMethod(L"Security.enable", L"{}", nullptr)); + + BrowserWindow::CheckFailure(m_contentWebView->GetDevToolsProtocolEventReceiver(L"Security.securityStateChanged", &m_securityStateChangedReceiver), L""); + + // Forward security status updates to browser + RETURN_IF_FAILED(m_securityStateChangedReceiver->add_DevToolsProtocolEventReceived(Callback( + [this, browserWindow](ICoreWebView2* webview, ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT + { + BrowserWindow::CheckFailure(browserWindow->HandleTabSecurityUpdate(m_tabId, webview, args), L"Can't update security icon"); + return S_OK; + }).Get(), &m_securityUpdateToken)); +``` + +```cpp +HRESULT BrowserWindow::HandleTabSecurityUpdate(size_t tabId, ICoreWebView2* webview, ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) +{ + wil::unique_cotaskmem_string jsonArgs; + RETURN_IF_FAILED(args->get_ParameterObjectAsJson(&jsonArgs)); + web::json::value securityEvent = web::json::value::parse(jsonArgs.get()); + + web::json::value jsonObj = web::json::value::parse(L"{}"); + jsonObj[L"message"] = web::json::value(MG_SECURITY_UPDATE); + jsonObj[L"args"] = web::json::value::parse(L"{}"); + jsonObj[L"args"][L"tabId"] = web::json::value::number(tabId); + jsonObj[L"args"][L"state"] = securityEvent.at(L"securityState"); + + return PostJsonToWebView(jsonObj, m_controlsWebView.Get()); +} +``` + +```javascript + case commands.MG_SECURITY_UPDATE: + if (isValidTabId(args.tabId)) { + const tab = tabs.get(args.tabId); + tab.securityState = args.state; + + if (args.tabId == activeTabId) { + updateNavigationUI(message); + } + } + break; +``` + +#### Populating the history + +WebView2Browser uses IndexedDB in the controls WebView to store history items, just an example of how WebView2 enables you to access standard web technologies as you would in the browser. The item for a navigation will be created as soon as the URI is updated. These items are then retrieved by the history UI in a tab making use of `window.chrome.postMessage`. + +In this case, most functionality is implemented using JavaScript on both ends (controls WebView and content WebView loading the UI) so the host application is only acting as a message broker to communicate those ends. + +```javascript + case commands.MG_UPDATE_URI: + if (isValidTabId(args.tabId)) { + // ... + + // Don't add history entry if URI has not changed + if (tab.uri == previousURI) { + break; + } + + // Filter URIs that should not appear in history + if (!tab.uri || tab.uri == 'about:blank') { + tab.historyItemId = INVALID_HISTORY_ID; + break; + } + + if (tab.uriToShow && tab.uriToShow.substring(0, 10) == 'browser://') { + tab.historyItemId = INVALID_HISTORY_ID; + break; + } + + addHistoryItem(historyItemFromTab(args.tabId), (id) => { + tab.historyItemId = id; + }); + } + break; +``` + +```javascript +function addHistoryItem(item, callback) { + queryDB((db) => { + let transaction = db.transaction(['history'], 'readwrite'); + let historyStore = transaction.objectStore('history'); + + // Check if an item for this URI exists on this day + let currentDate = new Date(); + let year = currentDate.getFullYear(); + let month = currentDate.getMonth(); + let date = currentDate.getDate(); + let todayDate = new Date(year, month, date); + + let existingItemsIndex = historyStore.index('stampedURI'); + let lowerBound = [item.uri, todayDate]; + let upperBound = [item.uri, currentDate]; + let range = IDBKeyRange.bound(lowerBound, upperBound); + let request = existingItemsIndex.openCursor(range); + + request.onsuccess = function(event) { + let cursor = event.target.result; + if (cursor) { + // There's an entry for this URI, update the item + cursor.value.timestamp = item.timestamp; + let updateRequest = cursor.update(cursor.value); + + updateRequest.onsuccess = function(event) { + if (callback) { + callback(event.target.result.primaryKey); + } + }; + } else { + // No entry for this URI, add item + let addItemRequest = historyStore.add(item); + + addItemRequest.onsuccess = function(event) { + if (callback) { + callback(event.target.result); + } + }; + } + }; + + }); +} +``` + + + +## Handling JSON and URIs + +WebView2Browser uses Microsoft's [cpprestsdk (Casablanca)](https://github.com/Microsoft/cpprestsdk) to handle all JSON in the C++ side of things. IUri and CreateUri are also used to parse file paths into URIs and can be used to for other URIs as well. diff --git a/microsoft-edge/webview2/samples/webview2samplewincomp.md b/microsoft-edge/webview2/samples/webview2samplewincomp.md index cff6a0f445..3849729afb 100644 --- a/microsoft-edge/webview2/samples/webview2samplewincomp.md +++ b/microsoft-edge/webview2/samples/webview2samplewincomp.md @@ -10,63 +10,60 @@ ms.date: 06/14/2022 --- # Win32 sample app with Visual Composition -This WebView2 sample demonstrates creating an application that embeds a WebView2 control within a Win32 native application. - -It is built as a Win32 Visual Studio 2019 project and makes use of both C++ and HTML/CSS/JavaScript in the WebView2 environment. - -It also uses Windows Runtime Composition APIs (also called the Visual layer) to take advantage of the Windows UI features and create a better look, feel, and functionality in C++ Win32 applications. - +This WebView2 sample embeds a WebView2 control within a Win32 native application. * Sample name: **WebView2SampleWinComp** -* Repo directory: **WebView2SampleWinComp** +* Repo directory: [WebView2SampleWinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp) * Solution file: **WebView2SampleWinComp.sln** +This sample is built as a Win32 Visual Studio 2019 project. It uses C++ and HTML/CSS/JavaScript in the WebView2 environment. -**To use this sample (general-purpose steps):** - -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. - - - -## Step 1 - View the Readme +This sample uses the [Windows Runtime Composition APIs](/uwp/api/windows.ui.composition) (also called the Visual layer) to take advantage of the Windows UI features and create a better look, feel, and functionality in C++ Win32 applications. -1. In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WebView2SampleWinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp#readme). Then return to this page and continue the steps below. +This sample showcases a selection of WebView2's event handlers and API methods that allow a native Win32 application to directly interact with a WebView and vice versa. - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp#prerequisites) +If this is your first time using WebView, we recommend first following the tutorial [Get started with WebView2 in Win32 apps](../get-started/win32.md), which goes over how to create a WebView2 and walks through some basic WebView2 functionality. - * [README > Build the WebView2 Sample WinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp#build-the-webview2-sample-wincomp) +See also [Readme file for WebView2SampleWinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp#readme). - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: - `/WebView2Samples/SampleApps/WebView2SampleWinComp/README.md` + +## Step 1 - Install a preview channel of Microsoft Edge - or: +We recommend the latest version of the Edge Canary channel. - `/WebView2Samples-main/SampleApps/WebView2SampleWinComp/README.md` +1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 2 - Install Visual Studio +## Step 2 - Install Visual Studio with C++ support Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. +This sample is built as a Win32 Visual Studio 2019 project. + 1. If Visual Studio (minimum required version) is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. If you want to use Visual Studio 2017, change the project's **Platform Toolset** in **Project Properties > Configuration properties > General > Platform Toolset**. You might also need to change the Windows SDK to the latest version available to you. - -## Step 3 - Install a preview channel of Microsoft Edge -1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +#### Other prerequisites + +* WebView2 SDK - A prerelease version of the WebView2 SDK is already installed in this sample project. Steps are shown below to optionally update the SDK. + +* Windows 10 SDK - By default, this sample app will use the latest Window 10 SDK version that's installed on your machine. However, there is an issue with Windows 10 SDK, version 2004 (10.0.19041.0) that will stop this sample app from building. Steps are provided below to install a compatible version of the Windows 10 SDK. -## Step 4 - Download or clone the WebView2Samples repo +## Step 3 - Clone or download the WebView2Samples repo -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +The first step to build this sample is to get a local copy of the samples repo. + +1. If not done already, clone or download the `WebView2Samples` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 5 - Open the Solution and set the Windows SDK target +## Step 4 - Open the Solution and set the Windows SDK target 1. On your local drive, open the `.sln` file in Visual Studio, in the directory: @@ -78,7 +75,7 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor A **Review Solution Actions** dialog box might open, prompting you for which installed Windows SDK to retarget the project to: - ![The 'Review Solution Actions' dialog box.](webview2samplewincomp-images/review-solution-actions.png) + ![The 'Review Solution Actions' dialog box](webview2samplewincomp-images/review-solution-actions.png) 1. In the **Windows SDK Version** dropdown list, select **10.0.20348.0** or later, or **10.0.18362.0** or earlier; do not select **10.0.19041.0**. Then click the **OK** button. If those versions aren't available, do the steps in the "Install the Windows SDK" section below. Otherwise, skip to the section below that. @@ -88,7 +85,7 @@ If the solution is already open, you can change the target as follows: -## Step 6 - Install the Windows SDK +## Step 5 - Install the Windows SDK By default, this sample app uses the latest Window 10 SDK version you have installed. There's an issue with Windows 10 SDK, version 2004 (10.0.**19041**.0) that will stop this sample app from building. If you run into this issue, either install (and retarget this project to use) a later version, such as Windows 10 SDK version 2104 (10.0.**20348**.0), or an earlier version, such as 10.0.**18362**.1. @@ -106,11 +103,11 @@ To install a Windows 10 SDK: 1. The **Windows SDK setup** window opens: - ![Windows SDK setup.](webview2samplewincomp-images/windows-sdk-setup.png) + ![Windows SDK setup](webview2samplewincomp-images/windows-sdk-setup.png) 1. Click the **Next** button and then follow the prompts. You can accept the defaults. At the end of installing, the Windows SDK Welcome screen for whichever version that you selected appears: - ![Welcome to the Windows SDK.](webview2samplewincomp-images/welcome-winsdk.png) + ![Welcome to the Windows SDK](webview2samplewincomp-images/welcome-winsdk.png) 1. Click the **Close** button. @@ -118,86 +115,73 @@ Do the previous step, "Open the Solution and set the Windows SDK target". Or, i -## Step 7 - Install workloads if prompted +## Step 6 - Install workloads if prompted * If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 8 - View the opened project - -The project opens in Visual Studio, showing the **WebView2SampleWinComp** project in Solution Explorer: +## Step 7 - Build and run the project -![The WebView2SampleWinComp project in Visual Studio.](webview2samplewincomp-images/project-in-sln-explorer.png) +After opening the solution in Visual Studio (above) and responding to any setup or installation prompts, the project opens in Visual Studio, showing the **WebView2SampleWinComp** project in Solution Explorer: -_To zoom the screenshot, right-click > **Open image in new tab**._ +![The WebView2SampleWinComp project in Visual Studio](webview2samplewincomp-images/project-in-sln-explorer.png) +At the top of Visual Studio, set the build target, as follows: - -## Step 9 - Install or update the WebView2 prerelease SDK +1. In the **Solution Configurations** dropdown list, select **Debug** or **Release**. -This step is optional. The sample has preinstalled a version of the WebView2 prerelease SDK. +1. In the **Solution Platforms** dropdown list, select **x86**, **x64**, or **ARM64**. -1. In **Solution Explorer**, right-click the **WebView2SampleWinComp** project (not the Solution node), and then select **Manage NuGet Packages**. The **NuGet Package Manager** tab opens. +1. In **Solution Explorer**, right-click the **WebView2SampleWinComp** project, and then select **Build**. -1. Select the **Include prerelease** checkbox. + This builds the project file `SampleApps/WebView2SampleWinComp/WebView2SampleWinComp.vcxproj`. -1. Click the **Updates** tab. +1. Select **Debug** > **Start Debugging** (`F5`). -1. If a newer prerelease of the **Microsoft.Web.WebView2** SDK is listed, click the **Update** button. A prerelease has a "-prerelease" suffix, such as **1.0.1248-prerelease**. If you want to see details about this step, in a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + The sample app window opens: -![The Updates tab of NuGet Package Manager after initially opening the WebView2SampleWinComp solution.](webview2samplewincomp-images/updates-tab-initial-state.png) + ![The WebView2SampleWinComp app window](webview2samplewincomp-images/app-window.png) -_To zoom the screenshot, right-click > **Open image in new tab**._ +1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. -## Step 10 - Install or update the Windows Implementation Libraries (WIL) +## Step 8 - Update the installed packages -This step is optional. The sample has preinstalled a version of the Windows Implementation Libraries (WIL). +This step is optional. The sample has preinstalled: +* A version of the WebView2 prerelease SDK. +* A version of the Windows Implementation Libraries (WIL). 1. In **Solution Explorer**, right-click the **WebView2SampleWinComp** project (not the Solution node), and then select **Manage NuGet Packages**. The **NuGet Package Manager** tab opens. -1. Install or update the Windows Implementation Libraries (WIL) on the project node (not the solution node) in Solution Explorer. If the WebView2 prerelease SDK is already installed, and a newer prerelease is listed in the Update tab, update it. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. - - - -## Step 11 - Build the project - -At the top of Visual Studio, set the build target, as follows: - -1. In the **Solution Configurations** dropdown list, select **Debug** or **Release**. - -1. In the **Solution Platforms** dropdown list, select **x86**, **x64**, or **ARM64**. - -1. In **Solution Explorer**, right-click the **WebView2SampleWinComp** project, and then select **Build**. - - This builds the project file `SampleApps/WebView2SampleWinComp/WebView2SampleWinComp.vcxproj`. +1. Select the **Include prerelease** checkbox. +1. Click the **Installed** tab. For each package, note whether there are two versions listed (the current version and an available updated version number). - -## Step 12 - Run (debug) the project +1. Click the **Updates** tab. -1. In Visual Studio, after building the project, select **Debug** > **Start Debugging** (`F5`). +1. If a newer prerelease of the **Microsoft.Web.WebView2** SDK is listed, you can optionally click the **Update** button. A prerelease has a "-prerelease" suffix, such as **1.0.1248-prerelease**. If you want to see details about this step, in a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. - The sample app window opens: + ![The Updates tab of NuGet Package Manager after initially opening the WebView2SampleWinComp solution](webview2samplewincomp-images/updates-tab-initial-state.png) - ![The WebView2SampleWinComp app window.](webview2samplewincomp-images/app-window.png) +1. If a newer release of the Windows Implementation Libraries (WIL) is listed, you can optionally click the **Update** button. -1. Use the sample app; see [README file for WebView2SampleWinComp](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2SampleWinComp#readme). +1. Follow the prompts to continue updating the packages. -1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. +1. Build and run the project again, now using the updated packages. -## Step 13 - Inspect the code +## Step 9 - Inspect the code 1. In the Visual Studio code editor, inspect the code: - ![The WebView2SampleWinComp project in Visual Studio](webview2samplewincomp-images/inspect-code-visual-studio.png) + ![WebView2SampleWinComp project in Visual Studio](webview2samplewincomp-images/inspect-code-visual-studio.png) ## See also * [Get started with WebView2 in Win32 apps](../get-started/win32.md) +* [WebView2 Reference Documentation](/microsoft-edge/webview2/webview2-api-reference) diff --git a/microsoft-edge/webview2/samples/webview2windowsformsbrowser.md b/microsoft-edge/webview2/samples/webview2windowsformsbrowser.md index f854c8a6b7..c042650451 100644 --- a/microsoft-edge/webview2/samples/webview2windowsformsbrowser.md +++ b/microsoft-edge/webview2/samples/webview2windowsformsbrowser.md @@ -10,38 +10,23 @@ ms.date: 04/27/2022 --- # WinForms sample app -This WebView2 sample demonstrates how to use the WebView2 control and WebView2 APIs to implement a web browser in a WinForms app. + +This sample, **WebView2WindowsFormsBrowser**, demonstrates how to use the WebView2 control and WebView2 APIs to implement a web browser in a WinForms app. * Sample name: **WebView2WindowsFormsBrowser** -* Repo directory: **WebView2WindowsFormsBrowser** +* Repo directory: [WebView2WindowsFormsBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser) * Solution file: **WebView2WindowsFormsBrowser.sln** +![WebView2WindowsFormsBrowser app window](media/webview2windowsformsbrowser-app-window.png) - -## Step 1 - View the Readme - -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. - -To use this sample, follow the steps below in order. - -1. In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WebView2WindowsFormsBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser#readme). Then return to this page and continue the steps below. - - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser#prerequisites) - - * [README > Build the WebView2 Windows Forms Browser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser#build-the-webview2-windows-forms-browser) - - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: - - `/WebView2Samples/SampleApps/WebView2WindowsFormsBrowser/README.md` - - or: - - `/WebView2Samples-main/SampleApps/WebView2WindowsFormsBrowser/README.md` +* The **Control** menu has toggle menuitems for **Accelerator Keys** and **Allow External Drop**. +* The **View** menu has **Zoom** and **Background Color** submenus. +* The **Events** button opens the **EventMonitor** window. -## Step 2 - Install Visual Studio +## Step 1 - Install Visual Studio Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. @@ -49,19 +34,19 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor -## Step 3 - Install a preview channel of Microsoft Edge +## Step 2 - Install a preview channel of Microsoft Edge 1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 4 - Download or clone the WebView2Samples repo +## Step 3 - Clone or download the WebView2Samples repo -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +1. If not done already, clone or download the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 5 - Open .sln in Visual Studio +## Step 4 - Open .sln in Visual Studio 1. On your local drive, open the `.sln` file in Visual Studio, in the directory: @@ -72,53 +57,41 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor * `/WebView2Samples-main/SampleApps/WebView2WindowsFormsBrowser/WebView2WindowsFormsBrowser.sln` -## Step 6 - Install workloads if prompted +## Step 5 - Install workloads if prompted 1. If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 7 - View the opened project - - Solution Explorer shows the **WebView2WindowsFormsBrowser** project. - - +## Step 6 - Build and run the project - - +The **WebView2WindowsFormsBrowser** project is now open in Visual Studio, from doing the above steps. At the top of Visual Studio, set the build target, as follows: +1. In the **Solution Configurations** dropdown list, select **Debug** or **Release**. - -## Step 8 - Install or update the WebView2 SDK - - - -1. **WebView2 SDK** - Install or update the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. - - - ![The WebView2WindowsFormsBrowser project in Visual Studio](media/webview2windowsformsbrowser-in-visual-studio.png) +1. In the **Solution Platforms** dropdown list, select **Any CPU**. - _To zoom, right-click > **Open image in new tab**._ +1. In **Solution Explorer**, right-click the **WebView2WindowsFormsBrowser** project, and then select **Build**. + This builds the project file `SampleApps/WebView2WindowsFormsBrowser/WebView2WindowsFormsBrowser.vcxproj`. This might take a couple minutes. - -## Step 9 - Install .NET Framework 4.6.2 Developer Pack + If you get error messages about missing .NET Framework 4.6.2 Developer Pack, follow the steps below. Otherwise, skip to the next major section below. -To build this project, .NET Framework 4.6.2 Developer Pack is required. +1. In Visual Studio, select **Debug** > **Start Debugging** (`F5`). -To test whether .NET Framework 4.6.2 Developer Pack is installed: + The sample app window opens: -At the top of Visual Studio, set the build target, as follows: + ![The WebView2WindowsFormsBrowser app window](media/webview2windowsformsbrowser-app-window.png) -1. In the **Solution Configurations** dropdown list, select **Debug** or **Release**. +1. Use the sample app; see [README file for WebView2WindowsFormsBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser#readme). -1. In the **Solution Platforms** dropdown list, select **Any CPU**. +1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. -1. In **Solution Explorer**, right-click the **WebView2WindowsFormsBrowser** project, and then select **Build**. - This builds the project file `SampleApps/WebView2WindowsFormsBrowser/WebView2WindowsFormsBrowser.vcxproj`. This might take a couple minutes. + +## Step 7 - Install .NET Framework 4.6.2 Developer Pack - If you get error messages about missing .NET Framework 4.6.2 Developer Pack, follow the steps below. Otherwise, skip to the next major section below. +If you build the **WebView2WindowsFormsBrowser** project and get error messages about missing .NET Framework 4.6.2 Developer Pack, follow the steps below. Otherwise, skip to the next major section below. 1. Go to [Download .NET Framework](https://dotnet.microsoft.com/download/dotnet-framework/), select v4.6.2, and then click the **Download .NET Framework 4.6.2 Developer Pack** button: @@ -132,8 +105,8 @@ At the top of Visual Studio, set the build target, as follows: The **Microsoft .NET Framework Developer Pack** license agreement dialog box appears: - ![The Microsoft .NET Framework Developer Pack license agreement dialog box.](media/webview2windowsformsbrowser-net-fwk-license-462.png) - + ![The Microsoft .NET Framework Developer Pack license agreement dialog box](media/webview2windowsformsbrowser-net-fwk-license-462.png) + 1. Select the **I agree to the license terms and conditions** checkbox, and then click the **Install** button. @@ -143,8 +116,8 @@ At the top of Visual Studio, set the build target, as follows: The Microsoft .NET Framework Developer Pack **Setup Successful** dialog box appears: - ![The Microsoft .NET Framework Developer Pack 'Setup Successful' dialog box.](media/webview2windowsformsbrowser-net-dev-pak-success-462.png) - + ![The Microsoft .NET Framework Developer Pack 'Setup Successful' dialog box](media/webview2windowsformsbrowser-net-dev-pak-success-462.png) + 1. Click the **Close** button. @@ -152,7 +125,18 @@ Microsoft .NET Framework 4.6.2 Developer Pack is now installed on your machine. -## Step 10 - Build the project +## Step 8 - Update or install the WebView2 SDK + + + +1. **WebView2 SDK** - Update or install the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + + + ![The WebView2WindowsFormsBrowser project in Visual Studio](media/webview2windowsformsbrowser-in-visual-studio.png) + + + +## Step 9 - Build and run the updated project 1. If you just now installed .NET Framework 4.6.2 Developer Pack above, close Visual Studio, and then open the solution file in Visual Studio again, from the directory: @@ -172,31 +156,27 @@ At the top of Visual Studio, set the build target, as follows: This builds the project file `SampleApps/WebView2WindowsFormsBrowser/WebView2WindowsFormsBrowser.vcxproj`. - - -## Step 11 - Run (debug) the project - 1. In Visual Studio, select **Debug** > **Start Debugging** (`F5`). The sample app window opens: - ![The WebView2WindowsFormsBrowser app window.](media/webview2windowsformsbrowser-app-window.png) + ![The WebView2WindowsFormsBrowser app window](media/webview2windowsformsbrowser-app-window.png) -1. Use the sample app; see [README file for WebView2WindowsFormsBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WindowsFormsBrowser#readme). + * The **Control** menu has toggle menuitems for **Accelerator Keys** and **Allow External Drop**. + * The **View** menu has **Zoom** and **Background Color** submenus. + * The **Events** button opens the **EventMonitor** window. 1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. -## Step 12 - Inspect the code +## Step 10 - Inspect the code 1. In the Visual Studio code editor, inspect the code: ![The WebView2WindowsFormsBrowser project in Visual Studio](media/webview2windowsformsbrowser-in-visual-studio.png) - _To zoom, right-click > **Open image in new tab**._ - ## See also diff --git a/microsoft-edge/webview2/samples/webview2wpfbrowser.md b/microsoft-edge/webview2/samples/webview2wpfbrowser.md index 60e1c8bd87..ab3b738ade 100644 --- a/microsoft-edge/webview2/samples/webview2wpfbrowser.md +++ b/microsoft-edge/webview2/samples/webview2wpfbrowser.md @@ -10,56 +10,54 @@ ms.date: 04/27/2022 --- # WPF sample app -This WebView2 sample, available from the WebView2Samples repo, demonstrates how to use the WebView2 control and WebView2 APIs to implement a web browser in a WPF .NET app. + +This sample, **WebView2WpfBrowser**, is a WPF .NET app that demonstrates how to embed the WebView2 control and use WebView2 APIs to implement a web browser. * Sample name: **WebView2WpfBrowser** -* Repo directory: **WebView2WpfBrowser** +* Repo directory: [WebView2WpfBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser) * Solution file: **WebView2WpfBrowser.sln** +This sample is built as a WPF Visual Studio 2019 project. It uses C# and HTML/CSS/JavaScript in the WebView2 environment. - -## Step 1 - View the Readme - -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. +This sample showcases a selection of WebView2's event handlers and API methods that allow a WPF application to directly interact with a WebView and vice versa. -1. In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WebView2WpfBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser#readme). Then return to this page and continue the steps below. +![WebView2WpfBrowser sample app](media/webview2wpfbrowser-sample-app.png) - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser#prerequisites) +The **WebView2WpfBrowser** sample app has the following menus, containing many useful menuitems: +* **File** +* **View** +* **Settings** +* **Scenario** - * [README > Build the WebView2 WPF Browser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser#build-the-webview2-wpf-browser) +If this is your first time using WebView2, we recommend first following the Getting Started tutorial, which goes over how to create a WebView2 and walks through some basic WebView2 functionality. See [Get started with WebView2 in WPF apps](../get-started/wpf.md). - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: +For more information about events and API Handlers in WebView2, see [WebView2 API Reference](/microsoft-edge/webview2/webview2-api-reference). - `/WebView2Samples/SampleApps/WebView2WpfBrowser/README.md` - or: + +## Step 1 - Install a preview channel of Microsoft Edge - `/WebView2Samples-main/SampleApps/WebView2WpfBrowser/README.md` +1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 2 - Install Visual Studio +## Step 2 - Install Visual Studio 2019 with .NET support Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. -1. If Visual Studio (minimum required version) is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. If Visual Studio 2019 (minimum required version) with .NET support is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section to install Visual Studio 2019 with .NET support, and then return to this page and continue the steps below. + -## Step 3 - Install a preview channel of Microsoft Edge +## Step 3 - Clone or download the WebView2Samples repo -1.If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. If not done already, clone or download the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 4 - Download or clone the WebView2Samples repo - -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. - - - -## Step 5 - Open .sln in Visual Studio +## Step 4 - Open the solution in Visual Studio 1. On your local drive, open the `.sln` file in Visual Studio, in the directory: @@ -71,25 +69,17 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor -## Step 6 - Install workloads if prompted +## Step 5 - Install workloads if prompted 1. If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. The **WebView2WpfBrowser** project opens in Visual Studio: - ![The WebView2WpfBrowser project in Visual Studio.](media/webview2wpfbrowser-project-opened.png) - - _To zoom, right-click > **Open image in new tab**._ - - - -## Step 7 - Install or update the WebView2 SDK - -1. Install or update the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + ![The WebView2WpfBrowser project in Visual Studio](media/webview2wpfbrowser-project-opened.png) -## Step 8 - Build the project +## Step 6 - Build and run the project At the top of Visual Studio, set the build target, as follows: @@ -101,29 +91,35 @@ At the top of Visual Studio, set the build target, as follows: This builds the project file `WebView2WpfBrowser.csproj`. - - -## Step 9 - Run (debug) the project - 1. In Visual Studio, select **Debug** > **Start Debugging** (`F5`). The sample app window opens: - ![The WebView2WpfBrowser sample app.](media/webview2wpfbrowser-sample-app.png) - -1. Use the sample app; see [README file for WebView2WpfBrowser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2WpfBrowser#readme). + ![The WebView2WpfBrowser sample app](media/webview2wpfbrowser-sample-app.png) 1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. -## Step 10 - Inspect the code +## Step 7 - Update the WebView2 SDK + +1. Update the prerelease WebView2 SDK on the project node (not the solution node) in Solution Explorer. Install the latest prerelease of the WebView2 SDK, so that you can try the latest features. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + +1. Build and run the project again. -1. In the Visual Studio code editor, inspect the code: - ![WebView2WpfBrowser project's code in Visual Studio.](media/webview2wpfbrowser-code.png) + +## Step 8 - Explore the menus and inspect the code + +1. Explore the **WebView2WpfBrowser** sample app's menus, containing many useful menuitems: + * **File** + * **View** + * **Settings** + * **Scenario** + +1. In the Visual Studio code editor, inspect the code: - _To zoom, right-click > **Open image in new tab**._ + ![WebView2WpfBrowser project's code in Visual Studio](media/webview2wpfbrowser-code.png) diff --git a/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/cdp-extension-package.png b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/cdp-extension-package.png new file mode 100644 index 0000000000..e5f01fd989 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/cdp-extension-package.png differ diff --git a/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/devtools-commands-menu.png b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/devtools-commands-menu.png new file mode 100644 index 0000000000..da6857b45d Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/devtools-commands-menu.png differ diff --git a/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/devtools-events-menu.png b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/devtools-events-menu.png new file mode 100644 index 0000000000..c7f828b4b7 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/devtools-events-menu.png differ diff --git a/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/updating-packages.png b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/updating-packages.png new file mode 100644 index 0000000000..19513a6e6c Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample-images/updating-packages.png differ diff --git a/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample.md b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample.md index 2c4d3c2c56..9b5ef32c65 100644 --- a/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample.md +++ b/microsoft-edge/webview2/samples/wv2cdpextensionwpfsample.md @@ -6,60 +6,64 @@ ms.author: msedgedevrel ms.topic: conceptual ms.prod: microsoft-edge ms.technology: webview -ms.date: 04/27/2022 +ms.date: 07/20/2022 --- # WPF sample app with CDP extension -This WebView2 sample demonstrates how to use the WebView2 CDP extension to use the Chrome DevTools Protocol in a WPF app. + + +This WebView2 sample demonstrates how to use the WebView2 CDP extension to use the Chrome DevTools Protocol in a WPF app. * Sample name: **WV2CDPExtensionWPFSample** -* Repo directory: **WV2CDPExtensionWPFSample** +* Repo directory: [WV2CDPExtensionWPFSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample) * Solution file: **WV2CDPExtensionWPFSample.sln** +This sample, **WV2CDPExtensionWPFSample**, is built with the WebView2 CDP Extension (the **Microsoft.Web.WebView.DevToolsProtocolExtension** NuGet package). This sample calls Chrome DevTools Protocol (CDP) methods on a `DevToolsProtocolHelper` object in WebView2. - -## Step 1 - View the Readme - -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. +This sample is built as a WPF Visual Studio 2019 project. It uses C# in the WebView2 environment. -1. In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WV2CDPExtensionWPFSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample#readme). Then return to this page and continue the steps below. +![WV2CDPExtensionWPFSample sample app](media/wv2cdpextensionwpfsample-app-running.png) - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample#prerequisites) +The **DevTools Commands** menu: - * [README > Build the WebView2 WPF Browser](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample#build-the-webview2-wpf-browser) +![DevTools Commands menu of WV2CDPExtensionWPFSample app](./wv2cdpextensionwpfsample-images/devtools-commands-menu.png) - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: +The **DevTools Events** menu: - `/WebView2Samples/SampleApps/WV2CDPExtensionWPFSample/README.md` +![DevTools Events menu of WV2CDPExtensionWPFSample app](./wv2cdpextensionwpfsample-images/devtools-events-menu.png) - or: - `/WebView2Samples-main/SampleApps/WV2CDPExtensionWPFSample/README.md` +If this is your first time using WebView2, we recommend first following the [Get started with WebView2 in WPF apps](../get-started/wpf.md) tutorial. The tutorial walks you through creating a WebView2 and adding some basic WebView2 functionality. -## Step 2 - Install Visual Studio +## Step 1 - Install a preview channel of Microsoft Edge + + -Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. +We recommend the latest version of the Canary channel. -1. If Visual Studio (minimum required version) is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 3 - Install a preview channel of Microsoft Edge +## Step 2 - Install Visual Studio with .NET support -1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. + +Microsoft Visual Studio (with .NET support) is required. Microsoft Visual Studio Code is not supported for this sample. + +1. If Visual Studio (minimum required version) with .NET support is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 4 - Download or clone the WebView2Samples repo +## Step 3 - Clone or download the WebView2Samples repo -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +1. If not done already, clone or download the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. -## Step 5 - Open .sln in Visual Studio +## Step 4 - Open the solution in Visual Studio 1. On your local drive, open the `.sln` file in Visual Studio, in the directory: @@ -69,27 +73,26 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor * `/WebView2Samples-main/SampleApps/WV2CDPExtensionWPFSample/WV2CDPExtensionWPFSample.sln` +If you want to use Visual Studio 2017, in Visual Studio, change the project's Platform Toolset in **Project Properties > Configuration properties > General > Platform Toolset**. +To use Visual Studio 2017, you might also need to install a recent Windows SDK. + -## Step 6 - Install workloads if prompted +## Step 5 - Install workloads if prompted 1. If prompted, install any Visual Studio workloads that are requested. In a separate window or tab, see [Install Visual Studio workloads](../how-to/machine-setup.md#install-visual-studio-workloads) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. The **WV2CDPExtensionWPFSample** project opens in Visual Studio: - ![The WV2CDPExtensionWPFSample sample opened in Visual Studio in Solution Explorer.](media/wv2cdpextensionwpfsample-opened.png) + ![The WV2CDPExtensionWPFSample sample opened in Visual Studio in Solution Explorer](media/wv2cdpextensionwpfsample-opened.png) -## Step 7 - Install or update the WebView2 SDK - -1. Install or update the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +## Step 6 - Build and run the project with installed version of SDKs - At the top of Visual Studio, set the build target, as follows: +A version of the WebView2 SDK and the WebView2 DevToolsProtocolExtension are included as NuGet packages in this project. In a later step, you'll update these by using Visual Studio's NuGet Package Manager. - - -## Step 8 - Build the project +At the top of Visual Studio, set the build target, as follows: 1. In the **Solution Configurations** dropdown list, select **Debug** or **Release**. @@ -97,19 +100,65 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor 1. In **Solution Explorer**, right-click the **WV2CDPExtensionWPFSample** project, and then select **Build**. - This builds the project file `WV2CDPExtensionWPFSample.csproj`. + + +1. In Visual Studio, select **Debug** > **Start Debugging** (`F5`). + + The sample app window opens: + + ![The WV2CDPExtensionWPFSample sample app](media/wv2cdpextensionwpfsample-app-running.png) + +1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. -## Step 9 - Run (debug) the project +## Step 7 - Update the WebView2 SDK + + +1. In Solution Explorer, right-click the project (not the solution node) and then select **Manage NuGet Packages**. **NuGet Package Manager** opens. + +1. Click the **Installed** or **Updates** tab. + +1. Select or clear the **Include prerelease** checkbox. + + ![Updating packages](./wv2cdpextensionwpfsample-images/updating-packages.png) + + The above screenshot shows Visual Studio 2019, showing this sample in the context of the overarching **WebView2APIsSample** solution, rather than the present standalone solution. In this screenshot, the repo has a release version of the WebView2 SDK, and newer release and prerelease versions of the SDK are available. + +1. If a newer release of the **Microsoft.Web.WebView2** SDK is listed, click the **Update** button. A prerelease has a "-prerelease" suffix, such as **1.0.1248-prerelease**. Prerelease SDKs allow you to try the latest WebView2 features and APIs. + +If you want to see details about this step, in a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + +For more information, see [WebView2 SDK NuGet package](https://aka.ms/webviewnuget). + + + +## Step 8 - Update the WebView2 CDP Extension + +A prerequisite for this sample is the latest release version of the WebView2 CDP Extension (**Microsoft.Web.WebView.DevToolsProtocolExtension**), which is included in this project. The **Microsoft.Web.WebView.DevToolsProtocolExtension** package adds support for the Chrome DevTools Protocol API. + + +1. In Solution Explorer, right-click the project and then select **Manage NuGet Packages**. **NuGet Package Manager** opens. + +1. Click the **Installed** or **Updates** tab. + +1. Clear the **Include prerelease** checkbox. + + ![Checking for updates of the CDP Extension package](./wv2cdpextensionwpfsample-images/cdp-extension-package.png) + +1. If a newer release version of the **Microsoft.Web.WebView.DevToolsProtocolExtension** SDK is listed, click the **Update** button. + +For more information, see [WebView2 CDP Extension](https://aka.ms/webviewcdpnuget). + + + +## Step 9 - Build and run the project with updated packages 1. In Visual Studio, select **Debug** > **Start Debugging** (`F5`). The sample app window opens: - ![The WV2CDPExtensionWPFSample sample app.](media/wv2cdpextensionwpfsample-app-running.png) - -1. Use the sample app; see [README file for WV2CDPExtensionWPFSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2CDPExtensionWPFSample#readme). + ![The WV2CDPExtensionWPFSample app](media/wv2cdpextensionwpfsample-app-running.png) 1. In Visual Studio, select **Debug** > **Stop Debugging**. Visual Studio closes the app. @@ -119,9 +168,15 @@ Microsoft Visual Studio is required. Microsoft Visual Studio Code is not suppor 1. In the Visual Studio code editor, inspect the code: - ![WV2CDPExtensionWPFSample project's code in Visual Studio.](media/wv2cdpextensionwpfsample-code.png) + ![WV2CDPExtensionWPFSample project's code in Visual Studio](media/wv2cdpextensionwpfsample-code.png) + + The **DevTools Commands** menu: + + ![The DevTools Commands menu](./wv2cdpextensionwpfsample-images/devtools-commands-menu.png) + + The **DevTools Events** menu: - _To zoom, right-click > **Open image in new tab**._ + ![The DevTools Events menu](./wv2cdpextensionwpfsample-images/devtools-events-menu.png) diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/config-new-project.png b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/config-new-project.png new file mode 100644 index 0000000000..18965fdc32 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/config-new-project.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/new-empty-deployment-project-2019.png b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/new-empty-deployment-project-2019.png new file mode 100644 index 0000000000..75fb9c7c7c Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/new-empty-deployment-project-2019.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/product-xml-open-for-editing-unchanged.png b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/product-xml-open-for-editing-unchanged.png new file mode 100644 index 0000000000..feab8e0100 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/product-xml-open-for-editing-unchanged.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/select-prerequisites.png b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/select-prerequisites.png index bd6bf484fc..6c03afd13b 100644 Binary files a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/select-prerequisites.png and b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/select-prerequisites.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/setup-prerequisites.png b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/setup-prerequisites.png index 65f67bb574..ba24fb5206 100644 Binary files a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/setup-prerequisites.png and b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/setup-prerequisites.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/vsix-installer-vs-installer-projects-2019.png b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/vsix-installer-vs-installer-projects-2019.png new file mode 100644 index 0000000000..1c8e4459f7 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample-images/vsix-installer-vs-installer-projects-2019.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample.md b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample.md index 61175635b9..f7e760faad 100644 --- a/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample.md +++ b/microsoft-edge/webview2/samples/wv2deploymentvsinstallersample.md @@ -10,133 +10,219 @@ ms.date: 06/17/2022 --- # WebView2 Deployment Visual Studio installer -This WebView2 sample demonstrates how to deploy a WebView2 app using the Visual Studio installer. + -To help you understand how to deploy the [Evergreen WebView2 Runtime](/microsoft-edge/webview2/concepts/distribution#deploying-the-evergreen-webview2-runtime) with an application, this article describes how to use the [Microsoft Visual Studio Installer Project](https://marketplace.visualstudio.com/items?itemName=visualstudioclient.MicrosoftVisualStudio2017InstallerProjects) to create an installer for [WebView2APISample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WebView2APISample#readme) and chain-install the Evergreen WebView2 Runtime. +This sample, **WV2DeploymentVSInstallerSample**, demonstrates how to deploy a WebView2 app by using the Visual Studio installer. * Sample name: **WV2DeploymentVSInstallerSample** -* Repo directory: **WV2DeploymentVSInstallerSample** +* Repo directory: [WV2DeploymentVSInstallerSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentVSInstallerSample) +* Solution file: not provided in the repo. You create a solution file in the steps below. +To demonstrate how to deploy the Evergreen WebView2 Runtime with your app, this article describes how to use the [Microsoft Visual Studio Installer Project](https://marketplace.visualstudio.com/items?itemName=visualstudioclient.MicrosoftVisualStudio2017InstallerProjects) extension for Visual Studio. You create a project of type **Setup Project**, to create an installer for the [Win32 sample app](./webview2apissample.md) (**WebView2APISample**). That installer that you create chain-installs the Evergreen WebView2 Runtime. - -## Step 1 - Install Visual Studio and Installer Projects + + +You first edit the `project.xml` file from the repo, and then in Visual Studio, you create a new project by using the **Setup Project** project template from the **Microsoft Visual Studio Installer Projects** extension. -Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. +This sample demonstrates several different deployment approaches: +* Downloading the Evergreen WebView2 Runtime Bootstrapper by using a link. +* Packaging the Evergreen WebView2 Runtime Bootstrapper with your app. +* Packaging the Evergreen WebView2 Runtime Standalone Installer with your app. -1. If Visual Studio 2019 or higher is not already installed, in a separate window or tab, open [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +For information about these different approaches, see [Deploying the Evergreen WebView2 Runtime](/microsoft-edge/webview2/concepts/distribution#deploying-the-evergreen-webview2-runtime) in _Distribute your app and the WebView2 Runtime_. -1. Install the [Microsoft Visual Studio Installer Projects](https://marketplace.visualstudio.com/items?itemName=visualstudioclient.MicrosoftVisualStudio2017InstallerProjects). Follow the steps on that page, and then return to this page and continue the steps below. -## Step 2 - Install a preview channel of Microsoft Edge +## Step 1 - Build and run WebView2APISample -1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. + +To become familiar with the app that this sample distributes, and to make sure your environment is set up for general Win32 WebView2 app development, build and run the Win32 sample app (**WebView2APISample**) before using this deployment sample. - -## Step 3 - Download or clone the WebView2Samples repo +1. Do the steps in [Win32 sample app](./webview2apissample.md) (**WebView2APISample**) and then continue below. -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. +Prerequisite: As stated in the above page, Microsoft Visual Studio is required, including C++ support. Microsoft Visual Studio Code is not supported for this **WV2DeploymentVSInstallerSample** sample. + +The above page helps you clone or download the WebView2Samples repo, and install Visual Studio with C++ support, if not done yet. - +## Step 2 - Install Visual Studio Installer Projects - +If a **Waiting on the following processes to shut down** dialog appears, close Visual Studio. - +## Step 3 - Edit product.xml to configure how to distribute the WebView2 Runtime + +1. Open Visual Studio. In the opening screen, you can click the **Continue without code** link in the lower right. + +1. Open the following individual file that's in your local copy of the repo: `\WebView2Samples\SampleApps\WV2DeploymentVSInstallerSample\product.xml` + + Location of the file in the repo at GitHub: [SampleApps/WV2DeploymentVSInstallerSample/product.xml](https://github.com/MicrosoftEdge/WebView2Samples/blob/main/SampleApps/WV2DeploymentVSInstallerSample/product.xml) + + ![product.xml file opened for editing, unchanged, in Visual Studio 2019](./wv2deploymentvsinstallersample-images/product-xml-open-for-editing-unchanged.png) + +1. Inspect `product.xml`. There are three `` lines. Study the comment above each of the 3 lines. Here is a simplified view of the lines, with clarifications. + + The first `` line uses file `MicrosoftEdgeWebview2Setup.exe`, which is the Evergreen WebView2 Runtime Bootstrapper, and it specifies a `HomeSite` website. Use this line for _Approach 1: Downloading the Evergreen WebView2 Runtime Bootstrapper through a link_: + + ```xml + + + ``` + + The second `` line uses file `MicrosoftEdgeWebview2Setup.exe`, which is the Evergreen WebView2 Runtime Bootstrapper. Use this line for _Approach 2: Packaging the Evergreen WebView2 Runtime Bootstrapper with the app_: + + ```xml + + + ``` + + The third `` line uses file `MicrosoftEdgeWebView2RuntimeInstallerX64.exe`, which is a platform-specific Evergreen WebView2 Runtime Standalone Installer. Use this line for _Approach 3: Packaging the Evergreen WebView2 Runtime Standalone Installer with your app_: + + ```xml + + + ``` + +1. Identify which approach you are using. Approach 2 is the default; that is, the line to use Approach 2 is un-commented in the repo's `product.xml` file. + +1. Edit `product.xml`, as follows; do the steps in one of the three sections below. + + + +#### Approach 1: Downloading the Evergreen WebView2 Runtime Bootstrapper through a link + + +If you want the app to download the Evergreen WebView2 Runtime Bootstrapper (`MicrosoftEdgeWebview2Setup.exe`) through a link: + +1. Within the `` section, un-comment the following line (keep the long public key value), and comment out the other lines: + + ```xml + + ``` + +1. The `PublicKey` value for the WebView2 Runtime Bootstrapper may change without notice. We're working on addressing this issue. For now, you may need to replace it in `product.xml` with an updated `PublicKey` value. - +1. Within the `` and `` section, make sure `PackageFile` points to `"MicrosoftEdgeWebview2Setup.exe"` so that the Visual Studio installer is using the Bootstrapper. - +1. Save the file. - - + +#### Approach 2: Packaging the Evergreen WebView2 Runtime Bootstrapper with the app + +If you want to package the Evergreen WebView2 Runtime Bootstrapper (`MicrosoftEdgeWebview2Setup.exe`) with the app: + +1. Within the `` section, un-comment the following line and comment out the other lines: + + ```xml + + ``` + +1. Within the `` section, make sure `PackageFile` points to `"MicrosoftEdgeWebview2Setup.exe"` so that the Visual Studio installer is using the Bootstrapper. + +1. Save the file. + + +#### Approach 3: Packaging the Evergreen WebView2 Runtime Standalone Installer with your app + +If you want to package the Evergreen WebView2 Runtime Standalone Installer with the app: + +1. Within the `` section, un-comment the following line and comment out the other lines: + + ```xml + + ``` + +1. Within the `` and `` section, make sure `PackageFile` points to `"MicrosoftEdgeWebView2RuntimeInstallerX64.exe"` so that the Visual Studio installer is using the Standalone Installer. + +1. If you're targeting non-X64 devices, edit the `MicrosoftEdgeWebView2RuntimeInstallerX64` filename to reflect the correct architecture. + +1. Save the file. -## Step 4 - Install or update the WebView2 SDK +## Step 4 - Download the WebView2 Bootstrapper or Standalone Installer + +If you want to package either the Bootstrapper (Approach 2) or the Standalone Installer (Approach 3) with the app, do the steps in this section. Otherwise skip to the next major Step section. -1. If needed, install (or update) the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. You can follow these steps to determine whether the WebView2 SDK is installed for the project. Follow the steps in that section, and then return to this page and continue below. +1. Download [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2/) Bootstrapper or the Standalone Installer. + +1. Save the downloaded Bootstrapper or the Standalone Installer under the `\WebView2Samples\SampleApps\WV2DeploymentVSInstallerSample\` folder. - +## Step 5 - Copy the WV2DeploymentVSInstallerSample folder into a Packages folder + +This step applies to all of the approaches (1, 2, or 3). + +1. Copy the `\WebView2Samples\SampleApps\WV2DeploymentVSInstallerSample\` folder, and paste it into either one of the following folders: - + * `:\Program Files (x86)\Microsoft SDKs\ClickOnce Bootstrapper\Packages\` + * `\MSBuild\Microsoft\VisualStudio\BootstrapperPackages\` (requires at least Visual Studio 2019 Update 7) - + Typical path for ``: - + * `C:\Program Files (x86)\Microsoft Visual Studio\2019\Professional\Common7\IDE\` -## Step 5 - Create a Visual Studio installer for the Evergreen WebView2 Runtime +## Step 6 - Create a Setup Project in Visual Studio -This section highlights deployment workflows included in [Deploying the Evergreen WebView2 Runtime](/microsoft-edge/webview2/concepts/distribution#deploying-the-evergreen-webview2-runtime) in _Distribute your app and the WebView2 Runtime_ to complete the following tasks: +1. In Visual Studio, select **File** > **New** > **Project**. The **Create a new project** window appears. -* Download the Evergreen WebView2 Runtime Bootstrapper using a link. -* Package the Evergreen WebView2 Runtime Bootstrapper. -* Package the Evergreen WebView2 Runtime Standalone Installer. +1. In the **Search for templates** text box, enter **setup project**, and then select the **Setup Project** template. Make sure you select the template that's named exactly that, as shown below: -### Build Steps + ![WebView2 Deployment Visual Studio Installer: Create Setup Project](wv2deploymentvsinstallersample-images/create-setup-project.png) -Complete these steps to edit and run the project. +1. Click the **Next** button. -1. Start Visual Studio. + The **Configure your new project: Setup Project** dialog opens, as shown below. -1. Open the local copy of the `WebView2Samples` repo. +1. In the **Project name** text box, enter a name, such as **MyWin32WV2DeploySample**. -1. Edit the `product.xml` file depending on the workflow you wish to use. +1. In the **Location** text box, navigate to a location that's not inside another project directory, such as `\WebView2Samples\` or a location that's not in the repo directory. - * For "Package the Evergreen WebView2 Runtime Bootstrapper", - * Within the `` and `` section, un-comment the line `` and comment out other lines. - * Within the `` and `` section, make sure `PackageFile` points to `"MicrosoftEdgeWebview2Setup.exe"` so that the Visual Studio installer is using the Bootstrapper. + ![Configure new project](./wv2deploymentvsinstallersample-images/config-new-project.png) - * For "Download the Evergreen WebView2 Runtime Bootstrapper through link", - * Within the `` and `` section, un-comment the line `` and comment out other lines. Note that the `PublicKey` for the WebView2 Runtime Bootstrapper may change without notice and we are working on addressing this issue. For now, you may need to replace it with an updated `PublicKey`. - * Within the `` and `` section, make sure `PackageFile` points to `"MicrosoftEdgeWebview2Setup.exe"` so that the Visual Studio installer is using the Bootstrapper. +1. Click the **Create** button. - * For "Package the Evergreen WebView2 Runtime Standalone Installer", - * Within the `` and `` section, un-comment the line `` and comment out other lines. - * Within the `` and `` section, make sure `PackageFile` points to `"MicrosoftEdgeWebView2RuntimeInstallerX64.exe"` so that the Visual Studio installer is using the Standalone Installer. - * If you're targeting non-X64 devices, edit the `MicrosoftEdgeWebView2RuntimeInstallerX64` filename to reflect the correct architecture. + ![New empty deployment project (2019)](./wv2deploymentvsinstallersample-images/new-empty-deployment-project-2019.png) -1. If you plan to package either the Bootstrapper or the Standalone Installer, download [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2/) Bootstrapper or the Standalone Installer and save it in the `WV2DeploymentVSInstallerSample` folder. -1. Copy the `WV2DeploymentVSInstallerSample` folder, and paste it in either folder: - 1. `Program Files (x86)\Microsoft SDKs\ClickOnce Bootstrapper\Packages\`, or, - 1. `\MSBuild\Microsoft\VisualStudio\BootstrapperPackages\` (requires at least Visual Studio 2019 Update 7). + +## Step 7 - Add WebView2 Runtime as a prerequisite + +1. In Visual Studio, in Solution Explorer, right-click your project, and then select **Properties**. The **Property Pages** dialog opens. + +1. Click the **Prerequisites** button: -1. Create a Setup Project in Visual Studio. - 1. In Visual Studio, select **File** > **New** > **Project**. - 1. Search for `Setup Project`. + ![WebView2 Deployment Visual Studio Installer: Set Up Prerequisites](wv2deploymentvsinstallersample-images/setup-prerequisites.png) - ![WebView2 Deployment Visual Studio Installer: Create Setup Project](wv2deploymentvsinstallersample-images/create-setup-project.png) +1. Select the **Edge WebView2 runtime** checkbox. - 1. Create a Setup project. + If that checkbox isn't listed, that might indicate that a needed file hasn't been placed in a Packages folder. Check which approach you are using. You might need to do the steps above, in sections [Step 4 - Download the WebView2 Bootstrapper or Standalone Installer](#step-4---download-the-webview2-bootstrapper-or-standalone-installer) and [Step 5 - Copy the WV2DeploymentVSInstallerSample folder into a Packages folder](#step-5---copy-the-wv2deploymentvsinstallersample-folder-into-a-packages-folder). -1. Add WebView2 Runtime as a prerequisite. - 1. In Visual Studio, select **Project** > **Properties**. - 1. In the Property page, select **Prerequisites**. +1. Clear the other prerequisites checkboxes. Then click the **OK** button: - ![WebView2 Deployment Visual Studio Installer: Set Up Prerequisites](wv2deploymentvsinstallersample-images/setup-prerequisites.png) + ![WebView2 Deployment Visual Studio Installer: Select Prerequisite](wv2deploymentvsinstallersample-images/select-prerequisites.png) - 1. Check **Edge WebView2 runtime**, and un-check other prerequisites. Select **OK**. - - ![WebView2 Deployment Visual Studio Installer: Select Prerequisite](wv2deploymentvsinstallersample-images/select-prerequisites.png) + + +## Step 8 - Build the Setup project 1. Press **F5** to save and build the Setup project. + + ## See also diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/turn-windows-features-on.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/turn-windows-features-on.png new file mode 100644 index 0000000000..9ff50561e2 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/turn-windows-features-on.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vs2019-manage-extensions-wix.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vs2019-manage-extensions-wix.png new file mode 100644 index 0000000000..e80d40498d Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vs2019-manage-extensions-wix.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext-complete.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext-complete.png new file mode 100644 index 0000000000..fa251c4f66 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext-complete.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext.png new file mode 100644 index 0000000000..dfd01a81bd Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2022-ext-complete.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2022-ext-complete.png new file mode 100644 index 0000000000..c32afc14e9 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2022-ext-complete.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2022-ext.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2022-ext.png new file mode 100644 index 0000000000..4807cb5f35 Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2022-ext.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/wix-requires-dotnet-fwk-351.png b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/wix-requires-dotnet-fwk-351.png new file mode 100644 index 0000000000..54d64f440c Binary files /dev/null and b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample-images/wix-requires-dotnet-fwk-351.png differ diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample.md b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample.md index 7112cf927b..08cbfa37a1 100644 --- a/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample.md +++ b/microsoft-edge/webview2/samples/wv2deploymentwixburnbundlesample.md @@ -7,96 +7,161 @@ ms.topic: conceptual ms.prod: microsoft-edge ms.technology: webview ms.date: 04/27/2022 + --- # WiX Burn Bundle to deploy the WebView2 Runtime -This is a WebView2 sample demonstrating how to use a WiX Burn Bundle to deploy the WebView2 Runtime. - +This sample, **WV2DeploymentWiXBurnBundleSample**, demonstrates how to use a WiX Burn Bundle to deploy the WebView2 Runtime. Do the steps in this article to create a WiX installer that chain-installs the Evergreen WebView2 Runtime through Burn Bundle. * Sample name: **WV2DeploymentWiXBurnBundleSample** -* Repo directory: **WV2DeploymentWiXBurnBundleSample** +* Repo directory: [WV2DeploymentWiXBurnBundleSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample) * Project file: **WV2DeploymentWiXBurnBundleSample.wixproj** +This sample creates a [WiX](https://wixtoolset.org/) installer for the [Win32 sample app](webview2apissample.md). This sample uses [WiX Burn Bundle](https://wixtoolset.org/documentation/manual/v3/bundle/) to chain-install the Evergreen WebView2 Runtime. - -## Step 1 - View the Readme + -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. +This sample demonstrates these two different distribution approaches to distribute the WebView2 Runtime for your app: +* Downloading the Evergreen WebView2 Runtime Bootstrapper through a link stored in your app. +* Packaging the Evergreen WebView2 Runtime Bootstrapper with your app. -1. **README** - In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WV2DeploymentWiXBurnBundleSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample#readme). Then return to this page and continue the steps below. +The other approach, not demonstrated in this sample, is packaging the Evergreen WebView2 Runtime Standalone Installer with your app. That approach is very similar to packaging the Evergreen WebView2 Runtime Bootstrapper with your app. - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample#prerequisites) +For an overview of the approaches, see [Deploying the Evergreen WebView2 Runtime](../concepts/distribution.md#deploying-the-evergreen-webview2-runtime) in _Distribute your app and the WebView2 Runtime_. - * [README > Build steps](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample#build-steps) - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: + +## Step 1 - Install Visual Studio + +Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. - `/WebView2Samples/SampleApps/WV2DeploymentWiXBurnBundleSample/README.md` +If Visual Studio (minimum required version) is not already installed, with C++ support: - or: +1. In a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section to install Visual Studio, including C++ support. - `/WebView2Samples-main/SampleApps/WV2DeploymentWiXBurnBundleSample/README.md` +Then return to this page and continue the steps below. -## Step 2 - Install Visual Studio +## Step 2 - Install WiX Toolset build tools -Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. +If not done yet, install WiX Toolset: -1. If Visual Studio (minimum required version) is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. + - -## Step 3 - Install a preview channel of Microsoft Edge + -1. If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. In a new window or tab, go to [WiX Toolset](https://wixtoolset.org/releases/) and then download the **WiX Toolset build tools**. + - -## Step 4 - Download or clone the WebView2Samples repo +1. Click the `wixnnn.exe` file, and then click **Open file**. -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + A dialog might open, **Requires .NET Framework 3.5.1 to be enabled**: + ![Requires .NET Framework dialog](./wv2deploymentwixburnbundlesample-images/wix-requires-dotnet-fwk-351.png) - - + If .NET Framework 3.5.1 is already enabled on your machine, skip ahead to continue installing this WiX component. - + ![Turn Windows features on or off > .NET Framework 3.5](./wv2deploymentwixburnbundlesample-images/turn-windows-features-on.png) + + You don't need to select the child items. + +1. Click **OK**. You might be prompted whether to let Windows Update download files. + + For more information, see [Install the .NET Framework 3.5 on Windows 11, Windows 10, Windows 8.1, and Windows 8](/dotnet/framework/install/dotnet-35-windows). + +1. After .NET Framework 3.5.1 is enabled, again run the `wixnnn.exe` file. For example, in Microsoft Edge, click **Settings and more**, click **Downloads**, and then click **Open file** below `wix311.exe`. + +1. Click the **Install** panel of the WiX installer. + +1. In **User Account Control**, click the **Yes** button. The top of the WiX installer reads "Successfully installed". + +Also install the WiX Visual Studio component, per the next section. - +## Step 3 - Install WiX Toolset Visual Studio Extension + +If not done yet, install WiX Toolset Visual Studio 2019 Extension: + +1. In a new window or tab, go to [WiX Toolset](https://wixtoolset.org/releases/) and then download and install the extension: + * WiX Toolset Visual Studio 2019 Extension - downloaded installer file: `Votive2019.vsix` + + +1. In **User Account Control**, click the **Yes** button. VSIX Installer for WiX Visual Studio extension opens: + + ![VSIX Installer for WiX Visual Studio 2019 extension](./wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext.png) + + + +1. Click the **Install** button. + +1. If a **VSIX waiting for processes to shut down** dialog opens, close Visual Studio. The VSIX Installer proceeds. + + The VSIX Installer reads **Install complete**: + + ![VSIX Installer - Install Complete - WiX Toolset Visual Studio 2019 Extension](./wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext-complete.png) + + + + +1. In VSIX Installer, click the **Close** button. + +1. In the WiX installer, click the **Exit** panel. + +1. Close Visual Studio, if it's open. - +## Step 4 - Clone or download the WebView2Samples repo + +1. If not done already, clone or download the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. - - +Follow the steps in that section, and then return to this page and continue below. -## Step 5 - Install or update the WebView2 SDK +## Step 5 - Build the deployment project + +1. In your local copy of the WebView2Samples repo, open `\WebView2Samples\SampleApps\WebView2Samples.sln` with Visual Studio (not Visual Studio Code). + + If the **Unsupported ... .wixproj** dialog box appears, install the WiX Toolset and the WiX Toolset Extension, above: + + ![Unsupported wix projects message](./media/unsupported-review-project-dialog.png) + +1. This sample is an extension to the [WV2DeploymentWiXCustomActionSample](./wv2deploymentwixcustomactionsample.md) sample. In Solution Explorer, expand **WV2DeploymentWiXCustomActionSample** and then double-click `Product.wxs`. + +1. In `Product.wxs`, comment out all the ``, ``, and `` elements under `` and `` so that Custom Action is not used. + +1. Open `Bundle.wxs` under the `WV2DeploymentWiXBurnBundleSample` project. Edit `Bundle.wxs` depending on which workflow you want to use: -1. If needed, install (or update) the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. You can follow these steps to determine whether the WebView2 SDK is installed for the project. Follow the steps in that section, and then return to this page and continue below. + **To package the Evergreen WebView2 Runtime Bootstrapper with your app:** + * Uncomment the `` element below ``, and comment out other `` elements. + **To download the Evergreen WebView2 Runtime Bootstrapper through a link in your app:** + * Uncomment the `` element below ``, and comment out other `` elements. - +1. If you are packaging the Evergreen WebView2 Runtime Bootstrapper with your app, [download](https://developer.microsoft.com/microsoft-edge/webview2/) the Bootstrapper and place it under the enclosing `SampleApps` folder. - +1. Build the `WV2DeploymentWiXBurnBundleSample` project. - + +## Next steps +--> ## See also -[README file for WV2DeploymentWiXBurnBundleSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXBurnBundleSample#readme) +* [Deploying the Evergreen WebView2 Runtime](../concepts/distribution.md#deploying-the-evergreen-webview2-runtime) in _Distribute your app and the WebView2 Runtime_. diff --git a/microsoft-edge/webview2/samples/wv2deploymentwixcustomactionsample.md b/microsoft-edge/webview2/samples/wv2deploymentwixcustomactionsample.md index f8308b9301..19f01b45f4 100644 --- a/microsoft-edge/webview2/samples/wv2deploymentwixcustomactionsample.md +++ b/microsoft-edge/webview2/samples/wv2deploymentwixcustomactionsample.md @@ -10,94 +10,190 @@ ms.date: 04/27/2022 --- # WiX Custom Action to deploy the WebView2 Runtime -This is a WebView2 sample demonstrating how to use a WiX Custom Action to deploy the WebView2 Runtime. - +This sample, **WV2DeploymentWiXCustomActionSample**, demonstrates how to use a WiX Custom Action to deploy the WebView2 Runtime. * Sample name: **WV2DeploymentWiXCustomActionSample** -* Repo directory: **WV2DeploymentWiXCustomActionSample** +* Repo directory: [WV2DeploymentWiXCustomActionSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample) * Project file: **WV2DeploymentWiXCustomActionSample.wixproj** + - -## Step 1 - View the Readme +To help you understand how to deploy the Evergreen WebView2 Runtime with your app, this sample creates a [WiX](https://wixtoolset.org/) installer for the **WebView2APISample** and uses a [WiX Custom Action](https://wixtoolset.org/documentation/manual/v3/wixdev/extensions/authoring_custom_actions.html) to chain-install the Evergreen WebView2 Runtime. -The steps on the present page are general-purpose. See the sample-specific steps in the README sections, which may override the present page. +This sample demonstrates several different deployment approaches: +* Downloading the Evergreen WebView2 Runtime Bootstrapper by using a link. +* Packaging the Evergreen WebView2 Runtime Bootstrapper with your app. +* Packaging the Evergreen WebView2 Runtime Standalone Installer with your app. -1. In a separate window or tab, read the rendered README.md file for this project at GitHub: [README file for WV2DeploymentWiXCustomActionSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample#readme). Then return to this page and continue the steps below. - * [README > Prerequisites](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample#prerequisites) + +## Step 1 - Install Visual Studio 2019 with C++ support - * [README > Build steps](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample#build-steps) + - You can also view the README.md source file (non-rendered) in Visual Studio. In **File Manager** or Visual Studio > Solution Explorer, open the file: +Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. - `/WebView2Samples/SampleApps/WV2DeploymentWiXCustomActionSample/README.md` +1. **Visual Studio** - If Install Visual Studio 2019 (minimum required version) with C++ support is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section to install Visual Studio 2019 with C++ support, and then return to this page and continue the steps below. - or: - `/WebView2Samples-main/SampleApps/WV2DeploymentWiXCustomActionSample/README.md` + +## Step 2 - Install a preview channel of Microsoft Edge + +1. **Preview channel of Microsoft Edge** - If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. -## Step 2 - Install Visual Studio +## Step 3 - Install WiX Toolset build tools -Microsoft Visual Studio is required. Microsoft Visual Studio Code is not supported for this sample. +If not done yet, install WiX Toolset: -1. **Visual Studio** - If Visual Studio (minimum required version) is not already installed, in a separate window or tab, see [Install Visual Studio](../how-to/machine-setup.md#install-visual-studio) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. +1. In a new window or tab, go to [WiX Toolset](https://wixtoolset.org/releases/) and then download the **WiX Toolset build tools**. +1. Click the `wixnnn.exe` file, and then click **Open file**. - -## Step 3 - Install a preview channel of Microsoft Edge + A dialog might open, **Requires .NET Framework 3.5.1 to be enabled**: -1. **Preview channel of Microsoft Edge** - If a preview channel of Microsoft Edge (Beta, Dev, or Canary) is not already installed, in a separate window or tab, see [Install a preview channel of Microsoft Edge](../how-to/machine-setup.md#install-a-preview-channel-of-microsoft-edge) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue the steps below. + ![Requires .NET Framework dialog](./wv2deploymentwixburnbundlesample-images/wix-requires-dotnet-fwk-351.png) + If .NET Framework 3.5.1 is already enabled on your machine, skip ahead to continue installing this WiX component. - -## Step 4 - Download or clone the WebView2Samples repo +1. Click the **OK** button. The WiX installer window closes. + +1. Press the **Windows** key ![Windows key logo](../../media/windows-keyboard-logo.png) on your keyboard, type **Windows Features**, and then press **Enter**. The **Turn Windows features on or off** dialog box appears. + +1. Select the **.NET Framework 3.5 (includes .NET 2.0 and 3.0)** check box: + + ![Turn Windows features on or off > .NET Framework 3.5](./wv2deploymentwixburnbundlesample-images/turn-windows-features-on.png) -1. If not done already, download or clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Download the WebView2Samples repo](../how-to/machine-setup.md#download-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. + You don't need to select the child items. + +1. Click **OK**. You might be prompted whether to let Windows Update download files. + + For more information, see [Install the .NET Framework 3.5 on Windows 11, Windows 10, Windows 8.1, and Windows 8](/dotnet/framework/install/dotnet-35-windows). + +1. After .NET Framework 3.5.1 is enabled, again run the `wixnnn.exe` file. For example, in Microsoft Edge, click **Settings and more**, click **Downloads**, and then click **Open file** below `wix311.exe`. + +1. Click the **Install** panel of the WiX installer. + +1. In **User Account Control**, click the **Yes** button. The top of the WiX installer reads "Successfully installed". + +Also install the WiX Visual Studio component, per the next section. - +## Step 4 - Install WiX Toolset Visual Studio Extension + +If not done yet, install WiX Toolset Visual Studio 2019 Extension: + +1. In a new window or tab, go to [WiX Toolset](https://wixtoolset.org/releases/) and then download and install the extension: + * WiX Toolset Visual Studio 2019 Extension - downloaded installer file: `Votive2019.vsix` + +1. In **User Account Control**, click the **Yes** button. VSIX Installer for WiX Visual Studio extension opens: + + ![VSIX Installer for WiX Visual Studio 2019 extension](./wv2deploymentwixburnbundlesample-images/vsix-installer-wix-vs-2019-ext.png) + + + +1. Click the **Install** button. + +1. If a **VSIX waiting for processes to shut down** dialog opens, close Visual Studio. The VSIX Installer proceeds. + + The VSIX Installer reads **Install complete**: - + - or: +1. In VSIX Installer, click the **Close** button. - * `/WebView2Samples-main/SampleApps/WV2DeploymentWiXCustomActionSample/WV2DeploymentWiXCustomActionSample.sln` --> +1. In the WiX installer, click the **Exit** panel. - +## Step 5 - Clone the WebView2Samples repo + +1. If not done already, clone the `WebView2Sample` repo to your local drive. In a separate window or tab, see [Clone the WebView2Samples repo](../how-to/machine-setup.md#clone-the-webview2samples-repo) in _Set up your Dev environment for WebView2_. Follow the steps in that section, and then return to this page and continue below. - +## Step 6 - Open the solution in Visual Studio - - +1. In your local copy of the WebView2Samples repo, open `\WebView2Samples\SampleApps\WebView2Samples.sln` with Visual Studio (not Visual Studio Code). -## Step 5 - Install or update the WebView2 SDK +## Step 7 - Edit Product.wxs to configure how to distribute the WebView2 Runtime + +1. Open `Product.wxs` under the `WV2DeploymentWiXCustomActionSample` project. + +1. Edit `Product.wxs` depending on which approach you want to use: + + +#### Approach 1: Downloading the Evergreen WebView2 Runtime Bootstrapper through a link + +If you want the app to download the Evergreen WebView2 Runtime Bootstrapper (`MicrosoftEdgeWebview2Setup.exe`) through a link: + +1. Under ``, uncomment the `` element below ``. + +1. Comment out other `` and `` elements under `Step 4`. + +1. Under ``, uncomment the `` element below ``. + +1. Comment out other `` elements under `Step 5`. + + +#### Approach 2: Packaging the Evergreen WebView2 Runtime Bootstrapper with the app + +If you want to package the Evergreen WebView2 Runtime Bootstrapper (`MicrosoftEdgeWebview2Setup.exe`) with the app: + +1. Under ``, uncomment the `` and `` elements below ``. -1. **WebView2 SDK** - If needed, install (or update) the WebView2 SDK on the project node (not the solution node) in Solution Explorer. In a separate window or tab, see [Install the WebView2 SDK](../how-to/machine-setup.md#install-the-webview2-sdk) in _Set up your Dev environment for WebView2_. You can follow these steps to determine whether the WebView2 SDK is installed for the project. Follow the steps in that section, and then return to this page and continue below. +1. Comment out other `` and `` elements under `Step 4`. + +1. Under ``, uncomment the `` element below ``. + +1. Comment out other `` elements under `Step 5`. + + +#### Approach 3: Packaging the Evergreen WebView2 Runtime Standalone Installer with your app + +If you want to package the Evergreen WebView2 Runtime Standalone Installer with the app: + +1. Under ``, uncomment the `` and `` elements below ``. + +1. Comment out other `` and `` elements under `Step 4`. + +1. If you're targeting non-X64 devices, you may also want to edit the `MicrosoftEdgeWebView2RuntimeInstallerX64` filename to reflect the correct architecture. + +1. Under ``, uncomment the `` element below ``. + +1. Comment out other `` elements under `Step 5`. - +## Step 8 - Put bootstrapper or installer in the folder + +If you plan to package either the Bootstrapper (Approach 2) or the Standalone Installer (Approach 3) with the app: + +1. Download the Bootstrapper or the Standalone Installer. At [Microsoft Edge WebView2](https://developer.microsoft.com/microsoft-edge/webview2/), click **Download Now**, to scroll down to the **Download the WebView2 Runtime** section. - +1. Place the downloaded Bootstrapper or Standalone Installer under the enclosing `SampleApps` folder. + + + +## Step 9 - Build the installer project - +1. Build the `WV2DeploymentVSInstallerSample` project. - + ## See also -* [README file for WV2DeploymentWiXCustomActionSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample#readme) +* [Win32 sample app](./webview2apissample.md) +* [Deploying the Evergreen WebView2 Runtime](/microsoft-edge/webview2/concepts/distribution.md#deploying-the-evergreen-webview2-runtime) in _Distribute your app and the WebView2 Runtime_. +* [Readme for WV2DeploymentWiXCustomActionSample](https://github.com/MicrosoftEdge/WebView2Samples/tree/main/SampleApps/WV2DeploymentWiXCustomActionSample#readme). +* [WiX Toolset](https://wixtoolset.org/) +* [WiX > Adding a Custom Action](https://wixtoolset.org/documentation/manual/v3/wixdev/extensions/authoring_custom_actions.html)