WPF 中的 WebView2 入门Get started with WebView2 in WPF

本文将开始创建你的第一个 WebView2 应用,并了解 WebView2 的主要功能In this article, get started creating your first WebView2 app and learn about the main features of WebView2. 有关各个 API 的信息,请导航到 API 参考For more information on individual APIs, navigate to API reference.

必备条件Prerequisites

请确保先安装以下先决条件列表,然后再继续。Ensure you install the following list of pre-requisites before proceeding.

步骤 1 - 创建单窗口应用Step 1 - Create a single-window app

从包含单个主窗口的基本桌面项目开始。Start with a basic desktop project that contains a single main window.

  1. In Visual Studio, choose WPF .NET Core App \ (or WPF .NET Framework App) > Next.In Visual Studio, choose WPF .NET Core App (or WPF .NET Framework App) > Next.

    WPF 核心

    WPF 核心WPF core :::image-end:::

    WPF 框架

    WPF 框架WPF Framework :::image-end:::

  2. 输入 name 和location Project****的值Enter values for Project name and Location. 选择 .NET Framework 4.6.2或更高版本 \ (或 .NET Core 3.0或更高版本) 。Choose .NET Framework 4.6.2 or later (or .NET Core 3.0 or later).

    创建核心

    创建核心Create core :::image-end:::

    创建框架

    创建框架Create Framework :::image-end:::

  3. 若要创建项目,请选择"创建 "。To create your project, choose Create.

步骤 2 - 安装 WebView2 SDKStep 2 - Install WebView2 SDK

使用 NuGet 将 WebView2 SDK 添加到项目中。Use NuGet to add the WebView2 SDK to the project.

  1. 将鼠标悬停在项目上,打开上下文菜单 \ (右键单击) ,然后选择"管理NuGet包..."。Hover on the projecty, open the contextual menu (right-click), and choose Manage NuGet Packages....

    管理 NuGet 程序包

  2. 在搜索栏中,键入"> Microsoft.Web.WebView2 选择"Microsoft.Web.WebView2"。In the search bar, type Microsoft.Web.WebView2 > choose Microsoft.Web.WebView2.

    NuGet

    准备好开始使用 WebView2 API 开发应用。Ready to start developing apps using the WebView2 API. 若要生成并运行项目,请选择 F5To build and run the project, select F5. 正在运行的项目显示一个空窗口。The running project displays an empty window.

    空应用

步骤 3 - 创建单个 WebViewStep 3 - Create a single WebView

接下来,将 WebView 添加到你的应用。Next add a WebView to your app.

  1. MainWindow.xaml 文件中,若要添加 WebView2 XAML 命名空间,在 标记内插入以下 <Window/> 行。In the MainWindow.xaml file, to add the WebView2 XAML namespace, insert the following line inside the <Window/> tag.

    xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
    

    确保 中的代码 MainWindow.xaml 类似于以下代码段。Ensure the code in MainWindow.xaml looks like the following code snippet.

    <Window x:Class="WPF_Getting_Started.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
            xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
            xmlns:local="clr-namespace:{YOUR PROJECT NAME}"
            xmlns:wv2="clr-namespace:Microsoft.Web.WebView2.Wpf;assembly=Microsoft.Web.WebView2.Wpf"
            mc:Ignorable="d"
            Title="MainWindow"
            Height="450"
            Width="800"
    >
        <Grid>
    
        </Grid>
    </Window>
    
  2. 若要添加 WebView2 控件,请将 <Grid> 标记替换为以下代码段。To add the WebView2 control, replace the <Grid> tags with the following code snippet. 属性 Source 设置 WebView2 控件中显示的初始 URI。The Source property sets the initial URI displayed in the WebView2 control.

    <DockPanel>
        <wv2:WebView2 Name="webView"
                      Source="https://www.microsoft.com"
        />
    </DockPanel>
    
  3. 若要生成并运行项目,请选择 F5 "确保 WebView2 控件显示 [https://www.microsoft.com][|::ref1::|Main] "。To build and run the project, select F5 Ensure your WebView2 control displays [https://www.microsoft.com][|::ref1::|Main].

    Microsoft.com

    Microsoft.comMicrosoft.com

步骤 4 - 导航Step 4 - Navigation

添加允许用户通过向应用添加地址栏来更改 WebView2 控件显示的 URL 的能力。Add the ability to allow users to change the URL that the WebView2 control displays by adding an address bar to the app.

  1. 在 文件中,通过复制并粘贴包含 WebView 的 中的以下代码段 MainWindow.xaml <DockPanel> 来添加地址栏。In the MainWindow.xaml file, add an address bar by copying and pasting the following code snippet inside the <DockPanel> that contains the WebView.

    <DockPanel DockPanel.Dock="Top">
        <Button x:Name="ButtonGo"
                DockPanel.Dock="Right"
                Click="ButtonGo_Click"
                Content="Go"
        />
        <TextBox Name="addressBar"/>
    </DockPanel>
    

    确保 <DockPanel> 文件的 MainWindow.xaml 部分与以下代码段匹配。Ensure the <DockPanel> section of the MainWindow.xaml file matches the following code snippet.

    <DockPanel>
        <DockPanel DockPanel.Dock="Top">
            <Button x:Name="ButtonGo" DockPanel.Dock="Right" Click="ButtonGo_Click" Content="Go"/>
            <TextBox Name = "addressBar"/>
        </DockPanel>
        <wv2:WebView2 Name = "webView"
                      Source = "https://www.microsoft.com"
        />
    </DockPanel>
    
  2. 在Visual Studio中,若要添加命名空间,请将 MainWindow.xaml.cs CoreWebView2 以下代码段插入顶部。In Visual Studio, in the MainWindow.xaml.cs file, to add the CoreWebView2 namespace, insert the following code snippet at the top.

    using Microsoft.Web.WebView2.Core;
    
  3. 在文件中,复制以下代码段以创建 方法,该方法将 WebView 导航到地址栏中 MainWindow.xaml.cs ButtonGo_Click 输入的 URL。In the MainWindow.xaml.csfile, copy the following code snippet to create the ButtonGo_Click method, which navigates the WebView to the URL entered in the address bar.

    private void ButtonGo_Click(object sender, RoutedEventArgs e)
    {
        if (webView != null && webView.CoreWebView2 != null)
        {
            webView.CoreWebView2.Navigate(addressBar.Text);
        }
    }
    

    若要生成并运行项目,请选择 F5To build and run the project, select F5. 在地址栏中键入新 URL,然后选择"转到"。Type a new URL in the address bar and choose Go. 例如,键入 https://www.bing.comFor example, type https://www.bing.com. 确保 WebView2 控件导航到 URL。Ensure the WebView2 control navigates to the URL.

    备注

    确保在地址栏中输入完整 URL。Make sure a complete URL is entered in the address bar. 如果 ArgumentException URL 不以 或 为起始,则 http:// 会引发 https://An ArgumentException is thrown if the URL does not start with http:// or https://.

    必应

    bing.combing.com

步骤 5 - 导航事件Step 5 - Navigation events

在网页导航期间,WebView2 控件将引发事件。During webpage navigation, the WebView2 control raises events. 承载 WebView2 控件的应用侦听以下事件。The app that hosts WebView2 controls listens for the following events.

  • NavigationStarting
  • SourceChanged
  • ContentLoading
  • HistoryChanged
  • NavigationCompleted

有关详细信息,请导航到"导航事件"。For more information, navigate to Navigation Events.

导航事件

导航事件Navigation events

发生错误时,将引发以下事件,并可能依赖于导航到错误网页。When an error occurs, the following events are raised and may depend on navigation to an error webpage.

  • SourceChanged
  • ContentLoading
  • HistoryChanged

备注

如果发生 HTTP 重定向,则一行 NavigationStarting 中有多个事件。If an HTTP redirect occurs, there are multiple NavigationStarting events in a row.

若要演示如何使用事件,请注册用于取消任何非 NavigationStarting HTTPS 请求的处理程序。To demonstrate how to use the events, register a handler for NavigationStarting that cancels any non-HTTPS requests.

MainWindow.xaml.cs 文件中,修改构造函数以匹配以下代码段并添加 EnsureHttps 函数。In the MainWindow.xaml.cs file, modify the constructor to match the following code snippet and add the EnsureHttps function.

public MainWindow()
{
    InitializeComponent();
    webView.NavigationStarting += EnsureHttps;
}

void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        args.Cancel = true;
    }
}

在构造函数中 EnsureHttps ,注册为 WebView2 控件上事件 NavigationStarting 的事件处理程序。In the constructor, EnsureHttps is registered as the event handler on the NavigationStarting event on the WebView2 control.

若要生成并运行项目,请选择 F5To build and run the project, select F5. 确保导航到 HTTP 网站时,WebView 保持不变。Ensure when navigating to an HTTP site, the WebView remains unchanged. 但是,WebView 导航到 HTTPS 网站。However, the WebView navigates to HTTPS sites.

步骤 6 - 脚本Step 6 - Scripting

你可以在运行时使用主机应用将 JavaScript 代码注入 WebView2 控件。You may use host apps to inject JavaScript code into WebView2 controls at runtime. 你可以任务 WebView 运行任意 JavaScript 或添加初始化脚本。You may task WebView to run arbitrary JavaScript or add initialization scripts. 在删除 JavaScript 之前,注入的 JavaScript 适用于所有新的顶级文档和任何子框架。The injected JavaScript applies to all new top-level documents and any child frames until the JavaScript is removed. 注入的 JavaScript 以特定计时运行。The injected JavaScript is run with specific timing.

  • 创建全局对象后运行它。Run it after the creation of the global object.
  • 在运行 HTML 文档中包含的任何其他脚本之前运行它。Run it before any other script included in the HTML document is run.

例如,添加在用户导航到非 HTTPS 网站时发送警报的脚本。As an example, add scripts that send an alert when a user navigates to non-HTTPS sites. 修改 EnsureHttps 函数以将脚本注入到使用 ExecuteScriptAsync 方法的 Web 内容中。Modify the EnsureHttps function to inject a script into the web content that uses ExecuteScriptAsync method.

void EnsureHttps(object sender, CoreWebView2NavigationStartingEventArgs args)
{
    String uri = args.Uri;
    if (!uri.StartsWith("https://"))
    {
        webView.CoreWebView2.ExecuteScriptAsync($"alert('{uri} is not safe, try an https link')");
        args.Cancel = true;
    }
}

若要生成并运行项目,请选择 F5To build and run the project, select F5. 当你导航到不使用 HTTPS 的网站时,请确保应用显示一个警报。Ensure the app displays an alert when you navigate to a website that doesn't use HTTPS.

HTTPS

HTTPSHTTPS

步骤 7 - 主机和 Web 内容之间的通信Step 7 - Communication between host and web content

主机和 Web 内容可能通过以下方式使用 进行通信 postMessageThe host and web content may communicate in the following ways using postMessage.

  • WebView2 控件中的 Web 内容可能会使用 向主机发布消息 window.chrome.webview.postMessageWeb content in a WebView2 control may post a message to the host using window.chrome.webview.postMessage. 主机使用主机上注册的任何消息 WebMessageReceived 处理邮件。The host handles the message using any registered WebMessageReceived on the host.
  • 使用 或 将消息张贴到 WebView2 控件中的 CoreWebView2.PostWebMessageAsString Web 内容 CoreWebView2.PostWebMessageAsJSONHosts post messages to web content in a WebView2 control using CoreWebView2.PostWebMessageAsString or CoreWebView2.PostWebMessageAsJSON. 消息被添加到 的处理程序捕获 window.chrome.webview.addEventListenerThe messages are caught by handlers added to window.chrome.webview.addEventListener.

通信机制使用本机功能将来自 Web 内容的消息传递给主机。The communication mechanism passes messages from web content to the host using native capabilities.

在项目中,当 WebView2 控件导航到 URL 时,它会在地址栏中显示 URL,并通知用户 WebView2 控件中显示的 URL。In your project, when the WebView2 control navigates to a URL, it displays the URL in the address bar and alerts the user of the URL displayed in the WebView2 control.

  1. MainWindow.xaml.cs 文件中,更新构造函数并创建 InitializeAsync 一个函数以匹配以下代码段。In the MainWindow.xaml.cs file, update your constructor and create an InitializeAsync function to match the following code snippet. 函数 InitializeAsync awaits EnsureCoreWebView2Async, 因为 的初始化 CoreWebView2 是异步的。The InitializeAsync function awaits EnsureCoreWebView2Async because the initialization of CoreWebView2 is asynchronous.

    public MainWindow()
    {
        InitializeComponent();
        webView.NavigationStarting += EnsureHttps;
        InitializeAsync();
    }
    
    async void InitializeAsync()
    {
        await webView.EnsureCoreWebView2Async(null);
    }
    
  2. 初始化 CoreWebView2 后,注册事件处理程序以响应 WebMessageReceivedAfter CoreWebView2 is initialized, register an event handler to respond to WebMessageReceived. MainWindow.xaml.csInitializeAsync ,使用下面的 UpdateAddressBar 代码段更新和添加。In MainWindow.xaml.cs, update InitializeAsync and add UpdateAddressBar using the following code snippet.

    async void InitializeAsync()
    {
        await webView.EnsureCoreWebView2Async(null);
        webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;
    }
    
    void UpdateAddressBar(object sender, CoreWebView2WebMessageReceivedEventArgs args)
    {
        String uri = args.TryGetWebMessageAsString();
        addressBar.Text = uri;
        webView.CoreWebView2.PostWebMessageAsString(uri);
    }
    
  3. 为了使 WebView 能够发送和响应 Web 消息,在初始化后,主机 CoreWebView2In order for the WebView to send and respond to the web message, after CoreWebView2 is initialized, the host:

    1. 将脚本注入 Web 内容,用于注册处理程序以从主机打印消息。Injects a script to the web content that registers a handler to print message from the host.
    2. 将脚本注入到将 URL 张贴到主机的 Web 内容。Injects a script to the web content that posts the URL to the host.

    MainWindow.xaml.cs 文件中,进行更新 InitializeAsync 以匹配以下代码段。In the MainWindow.xaml.cs file, update InitializeAsync to match the following code snippet.

    async void InitializeAsync()
    {
        await webView.EnsureCoreWebView2Async(null);
        webView.CoreWebView2.WebMessageReceived += UpdateAddressBar;
    
        await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.postMessage(window.document.URL);");
        await webView.CoreWebView2.AddScriptToExecuteOnDocumentCreatedAsync("window.chrome.webview.addEventListener(\'message\', event => alert(event.data));");
    }
    

    若要生成并运行应用,请选择 F5To build and run the app, select F5. 现在,地址栏在 WebView2 控件中显示 URI。Now, the address bar displays the URI in the WebView2 control. 当您成功导航到新的 URI 时,WebView2 控件会向 WebView2 控件中显示的 URI 的用户发出警报。When you successfully navigate to a new URI, the WebView2 control alerts the user of the URI that's displayed in the WebView2 control.

    addressBar

    addressBaraddressBar

恭喜!你生成了第一个 WebView2 应用。Congratulations, you built your first WebView2 app.

后续步骤Next steps

若要继续了解有关 WebView2 的更多内容,请导航到以下资源。To continue learning more about WebView2, navigate to the following resources.

与 WebView 团队Microsoft Edge联系Getting in touch with the Microsoft Edge WebView team

分享反馈以帮助构建更丰富的 WebView2 体验。Share your feedback to help build richer WebView2 experiences. 若要提交功能请求或 Bug,或搜索已知问题,请导航到 Microsoft Edge WebView 反馈 存储库。To submit feature requests or bugs, or search for known issues, navigate to the Microsoft Edge WebView feedback repo.