WebView2 入门Get started with WebView2

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


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

  • WebView2运行时Microsoft Edge (Chromium) 安装在受支持的操作系统 \ (上的任意非稳定通道Windows 10、Windows 8.1和 Windows 7) 。WebView2 Runtime or any Microsoft Edge (Chromium) non-stable channel installed on supported OS (currently Windows 10, Windows 8.1, and Windows 7).


    WebView 团队建议使用 Canary 通道,最低要求版本为 82.0.488.0。The WebView team recommends using the Canary channel and the minimum required version is 82.0.488.0.

  • Visual Studio安装有 C++ 支持的 2015 或更高版本。Visual Studio 2015 or later with C++ support installed.

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

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


为了更好地关注演练,请使用演练:为示例应用创建传统的 Windows 桌面应用程序 (C++) 中修改的示例代码。To better focus the walkthrough, use modified sample code from Walkthrough: Create a traditional Windows Desktop application (C++) for your sample app. 若要下载修改后的示例并开始,请导航到"WebView2 示例"。To download the modified sample and get started, navigate to WebView2 Samples.

  1. 在Visual Studio中,打开 WebView2GettingStarted.slnIn Visual Studio, open WebView2GettingStarted.sln.
    如果使用早期版本的 Visual Studio,请将鼠标悬停在WebView2GettingStarted项目上,打开上下文菜单 \ (右键单击) ,然后选择 "属性"。If you use an older version of Visual Studio, hover on the WebView2GettingStarted project, open the contextual menu (right-click), and choose Properties. 配置属性 > 常规,Windows SDK版本和**** 平台工具集,以使用 Win10 SDK 和Visual Studio可用的工具集。Under Configuration Properties > General, modify Windows SDK Version and Platform Toolset to use the Win10 SDK and Visual Studio toolset available to you.


Visual Studio显示错误,因为项目缺少 WebView2 头文件。Visual Studio may display errors, because your project is missing the WebView2 header file. 应在步骤 2 之后修复错误The errors should be fixed after Step 2.

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

将 WebView2 SDK 添加到项目中。Add the WebView2 SDK into the project. 使用 NuGet 安装 Win32 SDK。Use NuGet to install the Win32 SDK.

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

    管理 NuGet 程序包

  2. 安装Windows库。Install the Windows Implementation Library.

    1. 在搜索栏中,键入 > Microsoft.Windows.ImplementationLibrary Microsoft.Windows。ImplementationLibraryIn the search bar, type Microsoft.Windows.ImplementationLibrary > choose Microsoft.Windows.ImplementationLibrary.

    2. 在右侧窗口中,选择"安装 "。In the right-hand side window, choose Install. NuGet将库下载到计算机。NuGet downloads the library to your machine.


      实现Windows库和 Windows运行时 C++ 模板库是可选的,因此对于此示例而言,使用 COM 更为简单。The Windows Implementation Library and Windows Runtime C++ Template Library are optional and make working with COM easier for the example.


  3. 安装 WebView2 SDK。Install the WebView2 SDK.

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

    2. 在右侧窗口中,选择"安装 "。In the right-hand side window, choose Install. NuGet将 SDK 下载到计算机。NuGet downloads the SDK to your machine.

      NuGet 程序包管理器

  4. 将 WebView2 标头添加到项目中。Add WebView2 header to your project.

    HelloWebView.cpp 文件中,复制以下代码段并将其粘贴到最后一 #include 行之后。In the HelloWebView.cpp file, copy the following code snippet and paste it after the last #include line.

    // include WebView2 header
    #include "WebView2.h"

    include 部分应类似于以下代码段。The include section should look similar to the following code snippet.

    #include <wrl.h>
    #include <wil/com.h>
    // include WebView2 header
    #include "WebView2.h"

准备好使用 WebView2 API 并生成。Ready to use and build against the WebView2 API.

生成空示例应用Build your empty sample app

若要生成并运行示例应用,请选择 F5To build and run the sample app, select F5. 你的应用显示一个空窗口。Your app displays an empty window.


步骤 3 - 在父窗口中创建单个 WebViewStep 3 - Create a single WebView within the parent window

将 WebView 添加到主窗口。Add a WebView to the main window.

使用 CreateCoreWebView2Environment 方法设置环境并找到支持Microsoft Edge \ (Chromium) 的浏览器。Use the CreateCoreWebView2Environment method to set up the environment and locate the Microsoft Edge (Chromium) browser powering the control. 如果要指定浏览器位置、用户文件夹、浏览器标志等,也可以使用此方法,而不是 CreateCoreWebView2EnvironmentWithOptions 使用默认设置。You may also use the CreateCoreWebView2EnvironmentWithOptions method if you want to specify browser location, user folder, browser flags, and so on, instead of using the default setting. 完成该方法后,在回调中运行 方法并运行 CreateCoreWebView2Environment ICoreWebView2Environment::CreateCoreWebView2Controller ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler ICoreWebView2Controller::get_CoreWebView2 方法,获取关联的 WebView。Upon the completion of the CreateCoreWebView2Environment method, run the ICoreWebView2Environment::CreateCoreWebView2Controller method inside the ICoreWebView2CreateCoreWebView2EnvironmentCompletedHandler callback and run the ICoreWebView2Controller::get_CoreWebView2 method to get the associated WebView.

在回调中,设置一些设置,调整 WebView 的大小以使用 100% 的父窗口,然后导航到必应。In the callback, set a few more settings, resize the WebView to take 100% of the parent window, and navigate to Bing.

复制以下代码段,并粘贴 HelloWebView.cpp 到注释之后 // <-- WebView2 sample code starts here --> 和注释 // <-- WebView2 sample code ends here --> 之前。Copy the following code snippet and paste into HelloWebView.cpp after the // <-- WebView2 sample code starts here --> comment and before the // <-- WebView2 sample code ends here --> comment.

// Step 3 - Create a single WebView within the parent window
// Locate the browser and set up the environment for WebView
CreateCoreWebView2EnvironmentWithOptions(nullptr, nullptr, nullptr,
        [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<ICoreWebView2CreateCoreWebView2ControllerCompletedHandler>(
                [hWnd](HRESULT result, ICoreWebView2Controller* controller) -> HRESULT {
                if (controller != nullptr) {
                    webviewController = controller;
                // Add a few settings for the webview
                // The demo step is redundant since the values are the default settings
                ICoreWebView2Settings* Settings;
                // Resize WebView to fit the bounds of the parent window
                RECT bounds;
                GetClientRect(hWnd, &bounds);
                // Schedule an async task to navigate to Bing
                // Step 4 - Navigation events
                // Step 5 - Scripting
                // Step 6 - Communication between host and web content
                return S_OK;
        return S_OK;

生成必应示例应用Build your Bing sample app

若要生成并运行应用,请选择 F5To build and run the app, select F5. 现在,你有一个 WebView 窗口,必应页面。Now you have a WebView window displaying the Bing page.


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

WebView 团队已在上一步中介绍了使用 ICoreWebView2::Navigate 方法导航到 URL 的内容。The WebView team already covered navigating to URL using the ICoreWebView2::Navigate method in the last step. 在导航过程中,WebView 会触发主机可以侦听的一系列事件。During navigation, WebView fires a sequence of events to which the host may listen.

  1. NavigationStarting
  2. SourceChanged
  3. ContentLoading
  4. HistoryChanged
  5. NavigationCompleted

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


在错误情况下,可能会发生以下一个或多个事件,具体取决于导航是否继续导航到错误网页。In error cases, one or more of the following events may occur depending on whether the navigation is continued to an error webpage.

  • SourceChanged
  • ContentLoading
  • HistoryChanged


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

作为使用事件的示例,请为事件注册处理程序以取消 NavigationStarting 任何非 https 请求。As an example of using the events, register a handler for the NavigationStarting event to cancel any non-https requests. 复制以下代码段并粘贴到 HelloWebView.cpp 中。Copy the following code snippet and paste into HelloWebView.cpp.

// register an ICoreWebView2NavigationStartingEventHandler to cancel any non-https navigation
EventRegistrationToken token;
    [](ICoreWebView2* webview, ICoreWebView2NavigationStartingEventArgs * args) -> HRESULT {
        PWSTR uri;
        std::wstring source(uri);
        if (source.substr(0, 5) != L"https") {
        return S_OK;
    }).Get(), &token);

现在,应用不会导航到任何非 https 网站。Now the app does not navigate to any non-https sites. 您可以使用类似的机制完成其他任务,例如将导航限制到您自己的域中。You may use similar mechanism to accomplish other tasks, such as restricting navigation to within your own domain.

步骤 5 - 脚本Step 5 - 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.

复制以下代码段并粘贴到 HelloWebView.cpp 中。Copy the following code snippet and paste into HelloWebView.cpp.

// 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<ICoreWebView2ExecuteScriptCompletedHandler>(
    [](HRESULT errorCode, LPCWSTR resultObjectAsJson) -> HRESULT {
        LPCWSTR URL = resultObjectAsJson;
        return S_OK;

现在,WebView 应始终冻结 Object 对象并返回页面文档一次。Now, WebView should always freeze the Object object and returns the page document once.


脚本注入 API \ (和其他一些 WebView2 API) 是异步的,如果代码必须按特定顺序运行,则应该使用回调。The script injection APIs (and some other WebView2 APIs) are asynchronous, you should use callbacks if code is must be run in a specific order.

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

主机和 Web 内容还可通过 方法相互 postMessage 通信。The host and the web content may also communicate with each other through the postMessage method. WebView 中运行的 Web 内容可以通过 方法发布给主机,消息由主机上注册的任何 window.chrome.webview.postMessage ICoreWebView2WebMessageReceivedEventHandler 事件处理程序处理。The web content running within a WebView may post to the host through the window.chrome.webview.postMessage method, and the message is handled by any registered the ICoreWebView2WebMessageReceivedEventHandler event handler on the host. 同样,主机可能通过 或 方法发送 Web 内容消息,由从侦听器添加的 ICoreWebView2::PostWebMessageAsString ICoreWebView2::PostWebMessageAsJSON 处理程序捕获 window.chrome.webview.addEventListenerLikewise, the host may message the web content through ICoreWebView2::PostWebMessageAsString or ICoreWebView2::PostWebMessageAsJSON method, which is caught by handlers added from window.chrome.webview.addEventListener listener. 通信机制允许 Web 内容通过传递消息要求主机运行本机 API 来使用本机功能。The communication mechanism allows the web content to use native capabilities by passing messages to ask the host to run native APIs.

作为了解机制的示例,当您尝试在 WebView 中输出文档 URL 时,将执行以下步骤。As an example to understand the mechanism, the following steps occur when you try to output the document URL in WebView.

  1. 主机注册处理程序以将收到的消息返回给 Web 内容The host registers a handler to return received message back to the web content
  2. 主机将脚本注入 Web 内容,Web 内容注册处理程序以从主机打印消息The host injects a script to the web content that registers a handler to print message from the host
  3. 主机向将 URL 张贴到主机的 Web 内容注入脚本The host injects a script to the web content that posts the URL to the host
  4. 将触发主机处理程序,并返回消息 \ (URL) Web 内容The handler of the host is triggered and returns the message (the URL) to the web content
  5. 将触发 Web 内容的处理程序,并输出来自主机 \ (URL) The handler of the web content is triggered and prints message from the host (the URL)

复制以下代码段并粘贴到 HelloWebView.cpp 中。Copy the following code snippet and paste into HelloWebView.cpp.

// Set an event handler for the host to return received message back to the web content
    [](ICoreWebView2* webview, ICoreWebView2WebMessageReceivedEventArgs * args) -> HRESULT {
        PWSTR message;
        // processMessage(&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
    L"window.chrome.webview.addEventListener(\'message\', event => alert(event.data));" \

生成显示 URL 示例应用程序Build your display URL sample app

若要生成并运行应用,请选择 F5To build and run the app, select F5. 在导航到网页之前,URL 将显示在弹出窗口中。The URL appears in a pop-up window before navigating to a webpage.

显示 URL

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

后续步骤Next steps

有关本文未涵盖的其他 WebView2 功能,请查看以下资源。For additional WebView2 functionality that isn't covered in this article, review the following resources.

与 Microsoft Edge WebView 团队联系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.