Начало работы с WebView2 в приложениях WPF
В этой статье присвойте начало созданию первого приложения WebView2 в приложениях Windows Presentation Foundation (WPF) и узнайте об основных особенностях WebView2. Дополнительные сведения об отдельных API см. в справке aPI.
Шаг 0 — необходимые условия
Установите следующий список необходимых условий перед началом работы.
Visual Studio 2017 или более поздней.
WebView2 Runtimeили любой Microsoft Edge (предварительный просмотр) Канала (Бета-версия, Dev или Canary), установленного на поддерживаемой операционной системе (ОС). Поддерживаемый в настоящее время список ОС Windows 11, Windows 10, Windows 8.1 и Windows 7.
Команда WebView2 рекомендует использовать канал Canary, а минимальная требуемая версия — 82.0.488.0.
Начните с базового настольного проекта с одним основным окном.
Откройте Microsoft Visual Studio.
На открываемой панели нажмите кнопку Создать новый проектили в приложении нажмите кнопку FileNew > **** > Project.
Поиск приложения WPF.
В новой панели проекта отображаются результаты поиска приложений WPF. Выделенная кнопка — это основное Windows Presentation Foundation приложения WPF для C#, XAML, Windows и настольного компьютера. Диалоговое окно отображает следующую кнопку.
Для WPF App (.NET Core) введите значения для Project имени и расположения, а затем нажмите кнопку Далее.
В диалоговом окне приложения WPF проекта настраивается имя проекта, расположение и имя решения. Диалоговое окно отображает назад и далее кнопки.
Выберите .NET Core 3.1 или более поздней.
Щелкните Создать, чтобы продолжить.
Visual Studio создает проект.
Используйте NuGet для добавления SDK WebView2 в проект.
В Обозревателерешений щелкните правой кнопкой мыши имя проекта, а затем выберите Управление NuGet пакетами.
Нажмите кнопку Browse. В панели поиска Microsoft.Web.WebView2 введите, а затем выберите Microsoft.Web.WebView2.
Диалоговое окно NuGet диспетчера пакетов отображает результаты поиска, включая карточку Microsoft.Web.WebView2. В диалоговом окне отображается версия и кнопка установки.
Примите версию по умолчанию и нажмите кнопку Установить.
В диалоговом окне Предварительные изменения нажмите кнопку ОК.
Чтобы сохранитьпроект, нажмите кнопку Сохранить все файлы > (Ctrl+Shift+S).
Нажмите кнопку F5 для создания и запуска проекта.
Запущенный проект отображает пустое окно.
Пустое окно приложения. Проверяет, установлено и работает WebView2, но отображаться нечем.
Добавьте в приложение управление WebView2.
Чтобы добавить пространство имен MainWindow.xaml WebView2 XAML, вставьте в тег следующую строку.
Убедитесь, что код MainWindow.xaml выглядит как следующий фрагмент кода.
Чтобы добавить управление WebView2, замените теги следующим фрагментом кода. Свойство Source задает начальный URI, отображаемый в области управления WebView2.
Чтобы сохранитьпроект, нажмите кнопку Сохранить все файлы > (Ctrl+Shift+S).
Нажмите кнопку F5 для создания и запуска проекта.
Убедитесь, что отображает управление https://www.microsoft.com WebView2.
Шаг 4 — навигация
Включение пользователями URL-адреса, отображаемого в области управления WebView2, путем добавления панели адресов в приложение.
В файл добавьте адресную планку путем копирования и вклейки следующего фрагмента кода внутри MainWindow.xaml веб-сайта. Держите существующий код ниже нового фрагмента.
Убедитесь, что раздел файла соответствует MainWindow.xaml следующему коду.
Чтобы добавить пространство имен, вставьте в файл следующий фрагмент MainWindow.xaml.cs CoreWebView2 кода.
В MainWindow.xaml.cs файле скопируйте следующий фрагмент кода для создания ButtonGo_Click метода. Этот код перемещает управление WebView2 в URL-адрес, вступив в адресную планку.
Вклеить фрагмент кода сразу после Public MainWIndow объявления, как показано в следующем коде.
Чтобы сохранитьпроект, нажмите кнопку Сохранить все файлы > (Ctrl+Shift+S).
Нажмите кнопку F5 для создания и запуска проекта.
Убедитесь, что управление WebView2 открывает вступимый URL-адрес.
В примере приложения отображается веб Bing веб-сайт с URL-адресом https://www.bing.com в панели адресов.
Шаг 5 — события навигации
Во время навигации на веб-странице управление WebView2 вызывает события. Приложение, в котором размещены элементы управления WebView2, прослушивает следующие события.
События навигации, начиная с нового документа. Путь отказа начинается непосредственно от навигации до завершения навигации. Успешный путь включает запуск навигации, изменение источника с возможным вводом из того же документа — загрузку контента до изменений в истории с помощью завершения навигации.
При ошибке возникают следующие события, которые могут зависеть от навигации на веб-страницу ошибки.
Если происходит перенаправление HTTP, в строке несколько NavigationStarting событий.
Чтобы продемонстрировать, как использовать события, зарегистрируйте обработок, который отменяет любые запросы, не NavigationStarting относясь к HTTPS.
В файле измените конструктор, чтобы соответствовать следующему фрагменту кода, MainWindow.xaml.cs и добавьте EnsureHttps функцию.
В конструкторе регистрируется как обработчик событий в EnsureHttps NavigationStarting событии на контроле WebView2.
Чтобы сохранитьпроект, нажмите кнопку Сохранить все файлы > (Ctrl+Shift+S).
Нажмите кнопку F5 для создания и запуска проекта.
Попытка открыть сайт HTTP. Убедитесь, что управление WebView2 остается неизменным. Однако управление WebView2 позволяет открывать сайты HTTPS.
Шаг 6 — сценарий
Вы можете использовать хост-приложения, чтобы ввести код JavaScript в элементы управления WebView2 во время работы. Вы можете поручено WebView2 выполнить произвольный JavaScript или добавить сценарии инициализации. Введенный JavaScript применяется ко всем новым документам верхнего уровня и к любым детским кадрам до удаления JavaScript. Вводный JavaScript запускается с определенными сроками.
Например, добавьте скрипты, которые отправляют оповещение при переходе пользователя на сайты, не относящаться к HTTPS.
Измените EnsureHttps функцию, чтобы ввести скрипт в веб-контент, использующий метод ExecuteScriptAsync.
Чтобы сохранитьпроект, нажмите кнопку Сохранить все файлы > (Ctrl+Shift+S).
Нажмите кнопку F5 для создания и запуска проекта.
Убедитесь, что приложение отображает оповещение при переходе на веб-сайт, который не использует HTTPS.
Хост и веб-контент могут общаться следующим postMessage образом.
Механизм связи передает сообщения из веб-контента в хост с помощью родных возможностей.
В проекте, когда управление WebView2 переходит на URL-адрес, он отображает URL-адрес в панели адресов и оповещает пользователя об URL-адресе, отображаемом в области управления WebView2.
В файле обновите конструктор и создайте функцию, которая будет соответствовать MainWindow.xaml.cs InitializeAsync следующему фрагменту кода. Функция InitializeAsync ожидает EnsureCoreWebView2Async, так как инициализация CoreWebView2 асинхронна.
Для управления WebView2 для отправки и ответа на веб-сообщение после инициализации CoreWebView2 хост:
В MainWindow.xaml.cs файле обновим, чтобы соответствовать InitializeAsync следующему фрагменту кода.
Чтобы сохранитьпроект, нажмите кнопку Сохранить все файлы > (Ctrl+Shift+S).
Нажмите кнопку F5 для создания и запуска проекта.
При открываемом новом URI управление WebView2 отображает его в панели адресов.
Пример приложения отображает URI в панели адресов и веб-сайте https://www.microsoft.com Майкрософт.
Поздравляем, вы создали свое первое приложение WebView2!
Microsoft Edge WebView2
Embed web content (HTML, CSS, and JavaScript) in your native applications with Microsoft Edge WebView2.
Best of the Web
Use the modern Microsoft Edge (Chromium) platform to bring web experiences into your native app.
Power of native
Build powerful and secure applications by allowing WebView2 controlled access to native capabilities.
Evergreen or fixed version
By default, WebView2 is evergreen and receives automatic updates to stay on the latest and most secure platform.
A fixed version variant is available for applications with strict compatibility requirements.
Download the WebView2 Runtime
When distributing your application, there are a few ways you can ensure the WebView2 Runtime is on client machines. Learn more about those options.
Evergreen Bootstrapper
The Bootstrapper is a tiny installer that downloads the Evergreen Runtime matching device architecture and installs it locally. There is also a Link that allows you to programmatically download the Bootstrapper.
Evergreen Standalone Installer
A full-blown installer that can install the Evergreen Runtime in offline environment. Available for x86/x64/ARM64.
Fixed Version
Select and package a specific version of the WebView2 Runtime with your application.
Download the Fixed Version WebView2 Runtime
MICROSOFT SOFTWARE LICENSE TERMS
MICROSOFT EDGE WEBVIEW2 RUNTIME (FIXED VERSION)
These license terms are an agreement between you and Microsoft Corporation (or one of its affiliates). They apply to the software named above and any Microsoft services or software updates (except to the extent such services or updates are accompanied by new or additional terms, in which case those different terms apply prospectively and do not alter your or Microsoft’s rights relating to pre-updated software or services). IF YOU COMPLY WITH THESE LICENSE TERMS, YOU HAVE THE RIGHTS BELOW. BY USING THE SOFTWARE, YOU ACCEPT THESE TERMS.
1. INSTALLATION AND USE RIGHTS.
a) General. You may install and use any number of copies of the software on your devices.
b) Included Microsoft Applications. The software may include other Microsoft applications. These license terms apply to those included applications, if any, unless other license terms are provided with the other Microsoft applications.
c) Third Party Components. The software may include third party components with separate legal notices or governed by other agreements, as may be described in the ThirdPartyNotices file(s) accompanying the software.
d) Other Services. The software may include features that provide an access point to, or rely on, other services, websites, links, content, material, integrations or applications, including as provided by independent third parties (“Other Services”). Your use of Other Services or of software features that rely on Other Services may be governed by separate terms and subject to separate privacy policies. You can view these separate terms and policies through the Other Services’ websites or settings, as applicable. The Other Services may not be available in all regions. You may not use tokens the software uses to call into a Microsoft Azure service separate from the software.
2. DISTRIBUTABLE CODE. The software may contain code you are permitted to distribute (i.e. make available for third parties) in applications you develop, as described in this Section.
a) Distribution Rights.
i. You may copy and distribute the object code of the software; and
ii. You may permit distributors of your applications to copy and distribute any of this distributable code you elect to distribute with your applications.
b) Distribution Requirements. For any code you distribute, you must:
i. add significant primary functionality to it in your applications;
ii. require distributors and external end users to agree to terms that protect it and Microsoft at least as much as this agreement, including providing notice to end users as required in Section 8 below;
iii. You must acquire all code, including any code obtained from a Microsoft URL, directly from Microsoft, including a Microsoft download site; and
iv. indemnify, defend, and hold harmless Microsoft from any claims, including attorneys’ fees, related to the distribution or use of your applications, except to the extent that any claim is based solely on the unmodified distributable code.
c) Distribution Restrictions. You may not:
i. use Microsoft’s trademarks or trade dress in your application in any way that suggests your application comes from or is endorsed by Microsoft; or
ii. modify or distribute the source code of any distributable code so that any part of it becomes subject to any license that requires that the distributable code, any other part of the software, or any of Microsoft’s other intellectual property be disclosed or distributed in source code form, or that others have the right to modify it; or
iii. provide any Microsoft download sites or shortcuts that provides access to this software to a third party.
3. SCOPE OF LICENSE. The software is licensed, not sold. Microsoft reserves all other rights. Unless applicable law gives you more rights despite this limitation, you will not (and have no right to):
a) work around any technical limitations in the software that only allow you to use it in certain ways;
b) reverse engineer, decompile or disassemble the software, or otherwise attempt to derive the source code for the software, except and to the extent required by third party licensing terms governing use of certain open source components that may be included in the software;
c) remove, minimize, block, or modify any notices of Microsoft or its suppliers in the software;
d) use the software in any way that is against the law or to create or propagate malware; or
e) share, publish, distribute, or lease the software, provide the software as a stand-alone offering for others to use, or transfer the software or this agreement to any third party.
4. DATA.
a) Data Collection. The software may collect information about you and your end users’ use of the software, and send that to Microsoft. Microsoft may use this information to provide services and improve our products and services. See Section 8 below for end user notice requirements. There are also some features in the software that may enable you to collect data from users of your applications. If you use these features to enable data collection in your applications, you must comply with applicable law, including providing appropriate notices to users of your applications. You can learn more about data collection and use in the help documentation and the privacy statement at https://aka.ms/privacy. Your use of the software operates as your consent to these practices.
b) Microsoft Defender SmartScreen. Microsoft Defender SmartScreen (“SmartScreen”) is enabled by default. You can learn more about SmartScreen in the Microsoft Edge Privacy Whitepaper at https://docs.microsoft.com/en-us/microsoft-edge/privacy-whitepaper#smartscreen. If you do not disable SmartScreen, you must provide notice to your end users as required by Section 8 below.
c) Processing of Personal Data. To the extent Microsoft is a processor or subprocessor of personal data in connection with the software, Microsoft makes the commitments in the European Union General Data Protection Regulation Terms of the Online Services Terms to all customers effective May 25, 2018, at https://docs.microsoft.com/en-us/legal/gdpr.
5. EXPORT RESTRICTIONS. You must comply with all domestic and international export laws and regulations that apply to the software, which include restrictions on destinations, end users, and end use. For further information on export restrictions, visit https://aka.ms/exporting.
6. SUPPORT SERVICES. Microsoft is not obligated under this agreement to provide any support services for the software. Any support provided is “as is”, “with all faults”, and without warranty of any kind.
7. H.264/AVC and MPEG-4 Visual Standards and VC-1 Video Standards. The software may include H.264/AVC, MPEG-4 Visual, and/or VC-1 codec technology. MPEG LA, L.L.C. requires this notice: THIS PRODUCT IS LICENSED UNDER THE H.264/AVC, THE VC-1, AND THE MPEG-4 PART 2 VISUAL PATENT PORTFOLIO LICENSES FOR THE PERSONAL AND NON-COMMERCIAL USE OF A CONSUMER TO (i) ENCODE VIDEO IN COMPLIANCE WITH THE ABOVE STANDARDS (“VIDEO STANDARDS”) OR (ii) DECODE AVC, VC-1, AND MPEG-4 PART 2 VIDEO THAT WAS ENCODED BY A CONSUMER ENGAGED IN A PERSONAL AND NON-COMMERCIAL ACTIVITY OR WAS OBTAINED FROM A VIDEO PROVIDER LICENSED TO PROVIDE SUCH VIDEO. NO LICENSE IS GRANTED OR SHALL BE IMPLIED FOR ANY OTHER USE. ADDITIONAL INFORMATION MAY BE OBTAINED FROM MPEG LA, L.L.C. SEE http://aka.ms/mpegla
8. REQUIRED NOTICES TO END USERS.
a) Required notice to all end users. Per Section 3 (a) above, you must provide notice to all users that your software includes software provided by Microsoft and that it may collect information about the end user’s use of the software, and send that information to Microsoft to provide services as disclosed in Microsoft’s Privacy Statement at https://aka.ms/privacy.
b) Required SmartScreen notice. If you do not disable SmartScreen as described in Section 3(b) above, you must provide notice to all users that your software includes Microsoft Defender SmartScreen and collects and sends the end user’s information to Microsoft as disclosed in Microsoft’s Privacy Statement at https://aka.ms/privacy and the Microsoft Edge Privacy Whitepaper at https://docs.microsoft.com/en-us/microsoft-edge/privacy-whitepaper#smartscreen.
9. BINDING ARBITRATION AND CLASS ACTION WAIVER. This Section applies if you live in (or, if a business, your principal place of business is in) the United States. If you and Microsoft have a dispute, you and Microsoft agree to try for 60 days to resolve it informally. If you and Microsoft can’t, you and Microsoft agree to binding individual arbitration before the American Arbitration Association under the Federal Arbitration Act (“FAA”), and not to sue in court in front of a judge or jury. Instead, a neutral arbitrator will decide. Class action lawsuits, class-wide arbitrations, private attorney-general actions, and any other proceeding where someone acts in a representative capacity are not allowed; nor is combining individual proceedings without the consent of all parties. The complete Arbitration Agreement contains more terms and is at aka.ms/arb-agreement-1. You and Microsoft agree to these terms.
10. ENTIRE AGREEMENT. This agreement, and any other terms Microsoft may provide for supplements, updates, or third-party applications, is the entire agreement for the software.
11. APPLICABLE LAW AND PLACE TO RESOLVE DISPUTES. If you acquired the software in the United States or Canada, the laws of the state or province where you live (or, if a business, where your principal place of business is located) govern the interpretation of this agreement, claims for its breach, and all other claims (including consumer protection, unfair competition, and tort claims), regardless of conflict of laws principles. If you acquired the software in any other country, its laws apply. If U.S. federal jurisdiction exists, you and Microsoft consent to exclusive jurisdiction and venue in the federal court in King County, Washington for all disputes heard in court. If not, you and Microsoft consent to exclusive jurisdiction and venue in the Superior Court of King County, Washington for all disputes heard in court.
12. CONSUMER RIGHTS; REGIONAL VARIATIONS. This agreement describes certain legal rights. You may have other rights, including consumer rights, under the laws of your state, province, or country. Separate and apart from your relationship with Microsoft, you may also have rights with respect to the party from which you acquired the software. This agreement does not change those other rights if the laws of your state, province, or country do not permit it to do so. For example, if you acquired the software in one of the below regions, or mandatory country law applies, then the following provisions apply to you:
a) Australia. You have statutory guarantees under the Australian Consumer Law and nothing in this agreement is intended to affect those rights.
b) Canada. If you acquired this software in Canada, you may stop receiving updates by turning off the automatic update feature, disconnecting your device from the Internet (if and when you re-connect to the Internet, however, the software will resume checking for and installing updates), or uninstalling the software. The product documentation, if any, may also specify how to turn off updates for your specific device or software.
c) Germany and Austria.
i. Warranty. The properly licensed software will perform substantially as described in any Microsoft materials that accompany the software. However, Microsoft gives no contractual guarantee in relation to the licensed software.
ii. Limitation of Liability. In case of intentional conduct, gross negligence, claims based on the Product Liability Act, as well as, in case of death or personal or physical injury, Microsoft is liable according to the statutory law.
Subject to the foregoing clause ii., Microsoft will only be liable for slight negligence if Microsoft is in breach of such material contractual obligations, the fulfillment of which facilitate the due performance of this agreement, the breach of which would endanger the purpose of this agreement and the compliance with which a party may constantly trust in (so-called «cardinal obligations»). In other cases of slight negligence, Microsoft will not be liable for slight negligence.
13. DISCLAIMER OF WARRANTY. THE SOFTWARE IS LICENSED “AS IS.” YOU BEAR THE RISK OF USING IT. MICROSOFT GIVES NO EXPRESS WARRANTIES, GUARANTEES, OR CONDITIONS. TO THE EXTENT PERMITTED UNDER APPLICABLE LAWS, MICROSOFT EXCLUDES ALL IMPLIED WARRANTIES, INCLUDING MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT.
This limitation applies to (a) anything related to the software, services, content (including code) on third party Internet sites, or third party applications; and (b) claims for breach of contract, warranty, guarantee, or condition; strict liability, negligence, or other tort; or any other claim; in each case to the extent permitted by applicable law.
It also applies even if Microsoft knew or should have known about the possibility of the damages. The above limitation or exclusion may not apply to you because your state, province, or country may not allow the exclusion or limitation of incidental, consequential, or other damages.
Source Code Compliance Team
Microsoft Corporation
One Microsoft Way
Redmond, WA 98052
USA
Notwithstanding any other terms, you may reverse engineer this software to the extent required to debug changes to any libraries licensed under the GNU Lesser General Public License.
Please note: As this software is distributed in Canada, some of the clauses in this agreement are provided below in French.
Remarque: Ce logiciel étant distribué au Canada, certaines des clauses dans ce contrat sont fournies ci-dessous en français.
EXONÉRATION DE GARANTIE. Le logiciel visé par une licence est offert « tel quel ». Toute utilisation de ce logiciel est à votre seule risque et péril. Microsoft n’accorde aucune autre garantie expresse. Vous pouvez bénéficier de droits additionnels en vertu du droit local sur la protection des consommateurs, que ce contrat ne peut modifier. La ou elles sont permises par le droit locale, les garanties implicites de qualité marchande, d’adéquation à un usage particulier et d’absence de contrefaçon sont exclues.
Cette limitation concerne:
tout ce qui est relié au logiciel, aux services ou au contenu (y compris le code) figurant sur des sites Internet tiers ou dans des programmes tiers; et
les réclamations au titre de violation de contrat ou de garantie, ou au titre de responsabilité stricte, de négligence ou d’une autre faute dans la limite autorisée par la loi en vigueur.
Elle s’applique également, même si Microsoft connaissait ou devrait connaître l’éventualité d’un tel dommage. Si votre pays n’autorise pas l’exclusion ou la limitation de responsabilité pour les dommages indirects, accessoires ou de quelque nature que ce soit, il se peut que la limitation ou l’exclusion ci-dessus ne s’appliquera pas à votre égard.
EFFET JURIDIQUE. Le présent contrat décrit certains droits juridiques. Vous pourriez avoir d’autres droits prévus par les lois de votre pays. Le présent contrat ne modifie pas les droits que vous confèrent les lois de votre pays si celles-ci ne le permettent pas.














