From 799322c16379a2e8e1b3487fc0d8c2a8dbed8684 Mon Sep 17 00:00:00 2001 From: WebView2 Github Bot Date: Mon, 16 Sep 2024 18:44:52 +0000 Subject: [PATCH 1/3] Updates for Win32, WPF, WinForms, UWP and WinUI3 sample apps from 130.0.2839.0 --- SampleApps/WebView2APISample/AppWindow.cpp | 5 +- .../WebView2APISample.vcxproj | 10 +- ...oServiceWorkerSyncRegistrationManager.html | 151 ++++ ...kerSyncRegistrationManagerServiceWorker.js | 12 + SampleApps/WebView2WpfBrowser/App.xaml | 12 - SampleApps/WebView2WpfBrowser/MainWindow.xaml | 35 +- .../WebView2WpfBrowser/MainWindow.xaml.cs | 673 ++++++++++-------- 7 files changed, 578 insertions(+), 320 deletions(-) create mode 100644 SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html create mode 100644 SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManagerServiceWorker.js diff --git a/SampleApps/WebView2APISample/AppWindow.cpp b/SampleApps/WebView2APISample/AppWindow.cpp index be1b8e05..c2c35735 100644 --- a/SampleApps/WebView2APISample/AppWindow.cpp +++ b/SampleApps/WebView2APISample/AppWindow.cpp @@ -1429,11 +1429,11 @@ HRESULT AppWindow::OnCreateEnvironmentCompleted( m_webViewEnvironment = environment; if (m_webviewOption.entry == WebViewCreateEntry::EVER_FROM_CREATE_WITH_OPTION_MENU || - m_creationModeId == IDM_CREATION_MODE_HOST_INPUT_PROCESSING - ) + m_creationModeId == IDM_CREATION_MODE_HOST_INPUT_PROCESSING) { return CreateControllerWithOptions(); } + auto webViewEnvironment3 = m_webViewEnvironment.try_query(); if (webViewEnvironment3 && (m_dcompDevice || m_wincompCompositor)) @@ -1522,6 +1522,7 @@ HRESULT AppWindow::CreateControllerWithOptions() } } //! [AllowHostInputProcessing] + if (m_dcompDevice || m_wincompCompositor) { //! [OnCreateCoreWebView2ControllerCompleted] diff --git a/SampleApps/WebView2APISample/WebView2APISample.vcxproj b/SampleApps/WebView2APISample/WebView2APISample.vcxproj index 87af0f7a..177a97c1 100644 --- a/SampleApps/WebView2APISample/WebView2APISample.vcxproj +++ b/SampleApps/WebView2APISample/WebView2APISample.vcxproj @@ -1,4 +1,4 @@ - + @@ -391,6 +391,12 @@ $(OutDir)\assets + + $(OutDir)\assets + + + $(OutDir)\assets + $(OutDir)\assets @@ -489,4 +495,4 @@ - + \ No newline at end of file diff --git a/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html b/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html new file mode 100644 index 00000000..00aa0959 --- /dev/null +++ b/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManager.html @@ -0,0 +1,151 @@ + + + + ScenarioServiceWorkerSyncRegistrationManager + + + +

Periodic Background Sync Example

+

Registrations

+

+
+ + + +
+ +
+ + +
+ +
+ + +
+ +
+ +
+
+ +

Background Sync Example

+

Registrations

+

+
+ + +
+ +
+ + +
+
+ +
+ + + + diff --git a/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManagerServiceWorker.js b/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManagerServiceWorker.js new file mode 100644 index 00000000..4e5fbb2c --- /dev/null +++ b/SampleApps/WebView2APISample/assets/ScenarioServiceWorkerSyncRegistrationManagerServiceWorker.js @@ -0,0 +1,12 @@ +function fetchAndCacheLatestNews() { + console.log("Fetched news from a server"); + } + + self.addEventListener("periodicsync", (event) => { + console.log("Periodic Sync Task Tag: " + event.tag + " executed"); + event.waitUntil(fetchAndCacheLatestNews()); + }); + + self.addEventListener("sync", (event) => { + console.log("Background Sync Task Tag: " + event.tag + " executed"); + }); \ No newline at end of file diff --git a/SampleApps/WebView2WpfBrowser/App.xaml b/SampleApps/WebView2WpfBrowser/App.xaml index 11dcce52..97ff7c9d 100644 --- a/SampleApps/WebView2WpfBrowser/App.xaml +++ b/SampleApps/WebView2WpfBrowser/App.xaml @@ -12,17 +12,5 @@ found in the LICENSE file. xmlns:local="clr-namespace:WebView2WpfBrowser" StartupUri="MainWindow.xaml"> - - - - diff --git a/SampleApps/WebView2WpfBrowser/MainWindow.xaml b/SampleApps/WebView2WpfBrowser/MainWindow.xaml index 763b498b..98a38ffc 100644 --- a/SampleApps/WebView2WpfBrowser/MainWindow.xaml +++ b/SampleApps/WebView2WpfBrowser/MainWindow.xaml @@ -16,6 +16,7 @@ found in the LICENSE file. Width="800" > + @@ -60,6 +61,7 @@ found in the LICENSE file. + @@ -94,7 +96,8 @@ found in the LICENSE file. - + + @@ -136,8 +139,9 @@ found in the LICENSE file. - - + + + @@ -176,7 +180,7 @@ found in the LICENSE file. - + @@ -188,6 +192,7 @@ found in the LICENSE file. + @@ -259,7 +264,7 @@ found in the LICENSE file. - + @@ -270,14 +275,18 @@ found in the LICENSE file. - - + + + + + + diff --git a/SampleApps/WebView2WpfBrowser/MainWindow.xaml.cs b/SampleApps/WebView2WpfBrowser/MainWindow.xaml.cs index 30b02d1f..386b49cb 100644 --- a/SampleApps/WebView2WpfBrowser/MainWindow.xaml.cs +++ b/SampleApps/WebView2WpfBrowser/MainWindow.xaml.cs @@ -55,6 +55,7 @@ public partial class MainWindow : Window public static RoutedCommand ClearBrowsingDataCommand = new RoutedCommand(); public static RoutedCommand SetDefaultDownloadPathCommand = new RoutedCommand(); public static RoutedCommand CreateDownloadsButtonCommand = new RoutedCommand(); + public static RoutedCommand ShowExtensionsWindowCommand = new RoutedCommand(); public static RoutedCommand CustomClientCertificateSelectionCommand = new RoutedCommand(); public static RoutedCommand CustomContextMenuCommand = new RoutedCommand(); public static RoutedCommand DeferredCustomCertificateDialogCommand = new RoutedCommand(); @@ -103,6 +104,7 @@ public partial class MainWindow : Window public static RoutedCommand CloseWebViewCommand = new RoutedCommand(); public static RoutedCommand NewWebViewCommand = new RoutedCommand(); + public static RoutedCommand NewWebViewCompositionControlCommand = new RoutedCommand(); public static RoutedCommand HostObjectsAllowedCommand = new RoutedCommand(); public static RoutedCommand BrowserAcceleratorKeyEnabledCommand = new RoutedCommand(); @@ -134,6 +136,7 @@ public partial class MainWindow : Window public static RoutedCommand DedicatedWorkerCreatedCommand = new RoutedCommand(); public static RoutedCommand SharedWorkerManagerCommand = new RoutedCommand(); public static RoutedCommand GetSharedWorkersCommand = new RoutedCommand(); + public static RoutedCommand ServiceWorkerSyncManagerCommand = new RoutedCommand(); #endregion commands @@ -147,9 +150,9 @@ CoreWebView2Settings WebViewSettings { get { - if (_webViewSettings == null && webView?.CoreWebView2 != null) + if (_webViewSettings == null && _iWebView2?.CoreWebView2 != null) { - _webViewSettings = webView.CoreWebView2.Settings; + _webViewSettings = _iWebView2.CoreWebView2.Settings; } return _webViewSettings; } @@ -159,9 +162,9 @@ CoreWebView2Environment WebViewEnvironment { get { - if (_webViewEnvironment == null && webView?.CoreWebView2 != null) + if (_webViewEnvironment == null && _iWebView2?.CoreWebView2 != null) { - _webViewEnvironment = webView.CoreWebView2.Environment; + _webViewEnvironment = _iWebView2.CoreWebView2.Environment; } return _webViewEnvironment; } @@ -171,16 +174,25 @@ CoreWebView2Profile WebViewProfile { get { - if (_webViewProfile == null && webView?.CoreWebView2 != null) + if (_webViewProfile == null && _iWebView2?.CoreWebView2 != null) { // - _webViewProfile = webView.CoreWebView2.Profile; + _webViewProfile = _iWebView2.CoreWebView2.Profile; // } return _webViewProfile; } } + // Try not to set these directly. Instead these should be updated by calling SetWebView(). + // We can switch between using a WebView2 or WebView2CompositionControl element. + bool _useCompositionControl = false; +#if USE_WEBVIEW2_EXPERIMENTAL + WebView2CompositionControl webView2CompositionControlXamlElement = null; +#endif + private FrameworkElement _webView2FrameworkElement; // Helper reference pointing to the current WV2 control. + private IWebView2 _iWebView2; // Helper reference pointing to the current WV2 control. + bool _isNewWindowRequest = false; List _webViewFrames = new List(); IReadOnlyList _processList = new List(); @@ -221,11 +233,8 @@ CoreWebView2Profile WebViewProfile public CoreWebView2CreationProperties CreationProperties { get; set; } = null; - public MainWindow() + public MainWindow() : this(null, false) { - DataContext = this; - Loaded += MainWindow_Loaded; - InitializeComponent(); } public MainWindow( @@ -241,34 +250,113 @@ public MainWindow( private async void MainWindow_Loaded(object sender, RoutedEventArgs e) { - await InitializeWebView(); + // We default to a regular WebView2 control. + this.CreationProperties = this.CreationProperties ?? webView2XamlElement.CreationProperties; + SetWebView(webView2XamlElement, false /*useCompositionControl*/); + await InitializeWebView(webView2XamlElement); + SetWebViewVisibility(true); + } + + // Calling this function sets the various WebView2 control references and updates + // the _useCompositionControl value. + private void SetWebView(IWebView2 newWebView2, bool useCompositionControl) + { +#if USE_WEBVIEW2_EXPERIMENTAL + if (useCompositionControl) + { + webView2CompositionControlXamlElement = newWebView2 as WebView2CompositionControl; + } + else +#endif + { + webView2XamlElement = newWebView2 as WebView2; + } + _webView2FrameworkElement = newWebView2 as FrameworkElement; + _iWebView2 = newWebView2; + _useCompositionControl = useCompositionControl; + + // We display the type of control in the window title, so update that now. + UpdateTitle(); } - async System.Threading.Tasks.Task InitializeWebView() + async Task InitializeWebView(IWebView2 webView2) { - AttachControlEventHandlers(webView); + if (this.CreationProperties != null) + { + webView2.CreationProperties = this.CreationProperties; + } + AttachControlEventHandlers(webView2); // Set background transparent - webView.DefaultBackgroundColor = System.Drawing.Color.Transparent; - await webView.EnsureCoreWebView2Async(); + webView2.DefaultBackgroundColor = System.Drawing.Color.Transparent; + await webView2.EnsureCoreWebView2Async(); } - void AttachControlEventHandlers(WebView2 control) + // In general, re-initializing a WebView2 involves creating and initializing a new WebView2, and then + // swapping it when ready. + // We do it in this order to avoid any race conditions of closing the existing WebView2 and having the browser + // process exit before the new WebView2 is spun up. + async Task ReinitializeWebView(bool useCompositionControl) + { + // First, create a new control, add it to the visual tree hidden, and initialize it. + IWebView2 newWebView = CreateReplacementControl(false /*useNewEnvironment*/, useCompositionControl); + (newWebView as FrameworkElement).Visibility = Visibility.Hidden; + AttachControlToVisualTree(newWebView as FrameworkElement); + await InitializeWebView(newWebView); + + // Next, remove the existing WebView2 and close it. + CloseWebView(); + + // Add the new control to the visual tree and set it as the current control. + SetWebView(newWebView, useCompositionControl); + SetWebViewVisibility(true); + } + + void CloseWebView(bool recreate = false) + { + shouldAttemptReinitOnBrowserExit = recreate; + RemoveControlFromVisualTree(_webView2FrameworkElement); + _iWebView2?.Dispose(); + _webView2FrameworkElement = null; + _iWebView2 = null; + } + + void AttachControlEventHandlers(IWebView2 control) { - // control.NavigationStarting += WebView_NavigationStarting; - // - // control.NavigationCompleted += WebView_NavigationCompleted; - // control.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted; - control.KeyDown += WebView_KeyDown; + (control as FrameworkElement).KeyDown += WebView_KeyDown; + } + + private void OnWebViewVisibleChecked(object sender, RoutedEventArgs e) + { + SetWebViewVisibility(true); + } + + private void OnWebViewVisibleUnchecked(object sender, RoutedEventArgs e) + { + SetWebViewVisibility(false); + } + + private void SetWebViewVisibility(bool visible) + { + if (_webView2FrameworkElement != null) + { + _webView2FrameworkElement.Visibility = (visible ? Visibility.Visible : Visibility.Hidden); + } + webViewVisible.IsChecked = visible; + } + + private bool IsWebViewVisible() + { + return _webView2FrameworkElement.Visibility == Visibility.Visible; } bool IsWebViewValid() { try { - return webView != null && webView.CoreWebView2 != null; + return _iWebView2 != null && _iWebView2.CoreWebView2 != null; } catch (Exception ex) when (ex is ObjectDisposedException || ex is InvalidOperationException) { @@ -300,28 +388,28 @@ void CloseCmdExecuted(object sender, ExecutedRoutedEventArgs e) return; } } - webView.Dispose(); - this.Close(); + CloseWebView(); + this.Close(); // Close the window } void BackCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) { - e.CanExecute = webView != null && webView.CanGoBack; + e.CanExecute = _iWebView2 != null && _iWebView2.CanGoBack; } void BackCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.GoBack(); + _iWebView2.GoBack(); } void ForwardCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) { - e.CanExecute = webView != null && webView.CanGoForward; + e.CanExecute = _iWebView2 != null && _iWebView2.CanGoForward; } void ForwardCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.GoForward(); + _iWebView2.GoForward(); } void RefreshCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) @@ -331,7 +419,7 @@ void RefreshCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) void RefreshCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.Reload(); + _iWebView2.Reload(); } void BrowseStopCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) @@ -341,12 +429,12 @@ void BrowseStopCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) void BrowseStopCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.Stop(); + _iWebView2.Stop(); } void WebViewRequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e) { - e.CanExecute = webView != null; + e.CanExecute = _iWebView2 != null; } void CoreWebView2RequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e) @@ -354,6 +442,15 @@ void CoreWebView2RequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArg e.CanExecute = IsWebViewValid(); } + void EpxerimentalCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e) + { +#if USE_WEBVIEW2_EXPERIMENTAL + e.CanExecute = true; +#else + e.CanExecute = false; +#endif + } + void CustomClientCertificateSelectionCmdExecuted(object target, ExecutedRoutedEventArgs e) { EnableCustomClientCertificateSelection(); @@ -401,39 +498,55 @@ void PrintToPdfStreamCmdExecuted(object target, ExecutedRoutedEventArgs e) private bool _isControlInVisualTree = true; - void RemoveControlFromVisualTree(WebView2 control) + void RemoveControlFromVisualTree(UIElement control) { - Layout.Children.Remove(control); + if (_isControlInVisualTree) + { + Layout.Children.Remove(control); + } _isControlInVisualTree = false; } - void AttachControlToVisualTree(WebView2 control) + void AttachControlToVisualTree(UIElement control) { Layout.Children.Add(control); _isControlInVisualTree = true; } - WebView2 GetReplacementControl(bool useNewEnvironment) + IWebView2 CreateReplacementControl(bool useNewEnvironment, bool useCompositionControl) { - WebView2 replacementControl = new WebView2(); - ((System.ComponentModel.ISupportInitialize)(replacementControl)).BeginInit(); - // Setup properties and bindings. - if (useNewEnvironment) + IWebView2 replacementControl; +#if USE_WEBVIEW2_EXPERIMENTAL + if (useCompositionControl) { - // Create a new CoreWebView2CreationProperties instance so the environment - // is made anew. - replacementControl.CreationProperties = new CoreWebView2CreationProperties(); - replacementControl.CreationProperties.BrowserExecutableFolder = webView.CreationProperties.BrowserExecutableFolder; - replacementControl.CreationProperties.Language = webView.CreationProperties.Language; - replacementControl.CreationProperties.UserDataFolder = webView.CreationProperties.UserDataFolder; - replacementControl.CreationProperties.AdditionalBrowserArguments = webView.CreationProperties.AdditionalBrowserArguments; - shouldAttachEnvironmentEventHandlers = true; + replacementControl = new WebView2CompositionControl(); } else +#endif { - replacementControl.CreationProperties = webView.CreationProperties; + replacementControl = new WebView2(); } - replacementControl.CreationProperties.AreBrowserExtensionsEnabled = true; + + if (_iWebView2?.CreationProperties != null) + { + // Setup properties and bindings. + if (useNewEnvironment) + { + // Create a new CoreWebView2CreationProperties instance so the environment + // is made anew. + replacementControl.CreationProperties = new CoreWebView2CreationProperties(); + replacementControl.CreationProperties.BrowserExecutableFolder = _iWebView2.CreationProperties.BrowserExecutableFolder; + replacementControl.CreationProperties.Language = _iWebView2.CreationProperties.Language; + replacementControl.CreationProperties.UserDataFolder = _iWebView2.CreationProperties.UserDataFolder; + replacementControl.CreationProperties.AdditionalBrowserArguments = _iWebView2.CreationProperties.AdditionalBrowserArguments; + shouldAttachEnvironmentEventHandlers = true; + } + else + { + replacementControl.CreationProperties = _iWebView2.CreationProperties; + } + } + Binding urlBinding = new Binding() { Source = replacementControl, @@ -443,8 +556,6 @@ WebView2 GetReplacementControl(bool useNewEnvironment) url.SetBinding(TextBox.TextProperty, urlBinding); AttachControlEventHandlers(replacementControl); - replacementControl.Source = webView.Source ?? new Uri("https://www.bing.com"); - ((System.ComponentModel.ISupportInitialize)(replacementControl)).EndInit(); return replacementControl; } @@ -461,15 +572,7 @@ void ReinitIfSelectedByUser(string caption, string message) // The control cannot be re-initialized so we setup a new instance to replace it. // Note the previous instance of the control is disposed of and removed from the // visual tree before attaching the new one. - if (_isControlInVisualTree) - { - RemoveControlFromVisualTree(webView); - } - webView.Dispose(); - webView = GetReplacementControl(false); - AttachControlToVisualTree(webView); - // Set background transparent - webView.DefaultBackgroundColor = System.Drawing.Color.Transparent; + _ = ReinitializeWebView(_useCompositionControl); } }); } @@ -481,9 +584,9 @@ void ReloadIfSelectedByUser(string caption, string message) var selection = MessageBox.Show(message, caption, MessageBoxButton.YesNo); if (selection == MessageBoxResult.Yes) { - webView.Reload(); + _iWebView2.Reload(); // Set background transparent - webView.DefaultBackgroundColor = System.Drawing.Color.Transparent; + _iWebView2.DefaultBackgroundColor = System.Drawing.Color.Transparent; } }); } @@ -544,11 +647,11 @@ bool IsAppContentUri(Uri source) double ZoomStep() { - if (webView.ZoomFactor < 1) + if (_iWebView2.ZoomFactor < 1) { return 0.25; } - else if (webView.ZoomFactor < 2) + else if (_iWebView2.ZoomFactor < 2) { return 0.5; } @@ -560,24 +663,24 @@ double ZoomStep() void IncreaseZoomCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.ZoomFactor += ZoomStep(); + _iWebView2.ZoomFactor += ZoomStep(); } void DecreaseZoomCmdCanExecute(object sender, CanExecuteRoutedEventArgs e) { - e.CanExecute = (webView != null) && (webView.ZoomFactor - ZoomStep() > 0.0); + e.CanExecute = (_iWebView2 != null) && (_iWebView2.ZoomFactor - ZoomStep() > 0.0); } void DecreaseZoomCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.ZoomFactor -= ZoomStep(); + _iWebView2.ZoomFactor -= ZoomStep(); } void BackgroundColorCmdExecuted(object target, ExecutedRoutedEventArgs e) { // System.Drawing.Color backgroundColor = System.Drawing.Color.FromName(e.Parameter.ToString()); - webView.DefaultBackgroundColor = backgroundColor; + _iWebView2.DefaultBackgroundColor = backgroundColor; // } @@ -590,7 +693,7 @@ async void InjectScriptCmdExecuted(object target, ExecutedRoutedEventArgs e) defaultInput: "window.getComputedStyle(document.body).backgroundColor"); if (dialog.ShowDialog() == true) { - string scriptResult = await webView.ExecuteScriptAsync(dialog.Input.Text); + string scriptResult = await _iWebView2.ExecuteScriptAsync(dialog.Input.Text); MessageBox.Show(this, scriptResult, "Script Result"); } // @@ -660,7 +763,7 @@ async void PrintToPdfCmdExecuted(object target, ExecutedRoutedEventArgs e) if (result == true) { _isPrintToPdfInProgress = true; - bool isSuccessful = await webView.CoreWebView2.PrintToPdfAsync( + bool isSuccessful = await _iWebView2.CoreWebView2.PrintToPdfAsync( saveFileDialog.FileName, printSettings); _isPrintToPdfInProgress = false; string message = (isSuccessful) ? @@ -684,25 +787,25 @@ void ShowPrintUI(object target, ExecutedRoutedEventArgs e) if (printDialog == "Browser") { // Opens the browser print preview dialog. - webView.CoreWebView2.ShowPrintUI(); + _iWebView2.CoreWebView2.ShowPrintUI(); } else { // Opens the system print dialog. - webView.CoreWebView2.ShowPrintUI(CoreWebView2PrintDialogKind.System); + _iWebView2.CoreWebView2.ShowPrintUI(CoreWebView2PrintDialogKind.System); } } // This example prints the current web page without a print dialog to default printer. async void PrintToDefaultPrinter() { - string title = webView.CoreWebView2.DocumentTitle; + string title = _iWebView2.CoreWebView2.DocumentTitle; try { // Passing null for `PrintSettings` results in default print settings used. // Prints current web page with the default page and printer settings. - CoreWebView2PrintStatus printStatus = await webView.CoreWebView2.PrintAsync(null); + CoreWebView2PrintStatus printStatus = await _iWebView2.CoreWebView2.PrintAsync(null); if (printStatus == CoreWebView2PrintStatus.Succeeded) { @@ -776,10 +879,10 @@ async void PrintToPrinter() { string printerName = GetPrinterName(); CoreWebView2PrintSettings printSettings = GetSelectedPrinterPrintSettings(printerName); - string title = webView.CoreWebView2.DocumentTitle; + string title = _iWebView2.CoreWebView2.DocumentTitle; try { - CoreWebView2PrintStatus printStatus = await webView.CoreWebView2.PrintAsync(printSettings); + CoreWebView2PrintStatus printStatus = await _iWebView2.CoreWebView2.PrintAsync(printSettings); if (printStatus == CoreWebView2PrintStatus.Succeeded) { @@ -815,10 +918,10 @@ async void PrintToPdfStream() { try { - string title = webView.CoreWebView2.DocumentTitle; + string title = _iWebView2.CoreWebView2.DocumentTitle; // Passing null for `PrintSettings` results in default print settings used. - System.IO.Stream stream = await webView.CoreWebView2.PrintToPdfStreamAsync(null); + System.IO.Stream stream = await _iWebView2.CoreWebView2.PrintToPdfStreamAsync(null); DisplayPdfDataInPrintDialog(stream); MessageBox.Show(this, "Printing" + title + " document to PDF Stream " + ((stream != null) ? "succeeded" : "failed"), "Print To PDF Stream"); } @@ -884,11 +987,11 @@ void EnhancedSecurityModeSetEnforceListCommandExecuted(object target, ExecutedRo async void GetCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e) { // - List cookieList = await webView.CoreWebView2.CookieManager.GetCookiesAsync("https://www.bing.com"); + List cookieList = await _iWebView2.CoreWebView2.CookieManager.GetCookiesAsync("https://www.bing.com"); StringBuilder cookieResult = new StringBuilder(cookieList.Count + " cookie(s) received from https://www.bing.com\n"); for (int i = 0; i < cookieList.Count; ++i) { - CoreWebView2Cookie cookie = webView.CoreWebView2.CookieManager.CreateCookieWithSystemNetCookie(cookieList[i].ToSystemNetCookie()); + CoreWebView2Cookie cookie = _iWebView2.CoreWebView2.CookieManager.CreateCookieWithSystemNetCookie(cookieList[i].ToSystemNetCookie()); cookieResult.Append($"\n{cookie.Name} {cookie.Value} {(cookie.IsSession ? "[session cookie]" : cookie.Expires.ToString("G"))}"); } MessageBox.Show(this, cookieResult.ToString(), "GetCookiesAsync"); @@ -898,19 +1001,19 @@ async void GetCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e) void AddOrUpdateCookieCmdExecuted(object target, ExecutedRoutedEventArgs e) { // - CoreWebView2Cookie cookie = webView.CoreWebView2.CookieManager.CreateCookie("CookieName", "CookieValue", ".bing.com", "/"); - webView.CoreWebView2.CookieManager.AddOrUpdateCookie(cookie); + CoreWebView2Cookie cookie = _iWebView2.CoreWebView2.CookieManager.CreateCookie("CookieName", "CookieValue", ".bing.com", "/"); + _iWebView2.CoreWebView2.CookieManager.AddOrUpdateCookie(cookie); // } void DeleteAllCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.CoreWebView2.CookieManager.DeleteAllCookies(); + _iWebView2.CoreWebView2.CookieManager.DeleteAllCookies(); } void DeleteCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.CoreWebView2.CookieManager.DeleteCookiesWithDomainAndPath("CookieName", ".bing.com", "/"); + _iWebView2.CoreWebView2.CookieManager.DeleteCookiesWithDomainAndPath("CookieName", ".bing.com", "/"); } void SetUserAgentCmdExecuted(object target, ExecutedRoutedEventArgs e) @@ -933,10 +1036,10 @@ void SetCustomDataPartitionCmdExecuted(object target, ExecutedRoutedEventArgs e) var dialog = new TextInputDialog( title: "Custom Data Partition", description: "Enter Custom Data Partition Id", - defaultInput: webView.CoreWebView2.CustomDataPartitionId); + defaultInput: _iWebView2.CoreWebView2.CustomDataPartitionId); if (dialog.ShowDialog() == true) { - webView.CoreWebView2.CustomDataPartitionId = dialog.Input.Text; + _iWebView2.CoreWebView2.CustomDataPartitionId = dialog.Input.Text; } // #endif @@ -949,7 +1052,7 @@ async void ClearCustomDataPartitionCmdExecuted(object target, ExecutedRoutedEven var dialog = new TextInputDialog( title: "Clear Custom Data Partition", description: "Enter Custom Data Partition Id to clear", - defaultInput: webView.CoreWebView2.CustomDataPartitionId); + defaultInput: _iWebView2.CoreWebView2.CustomDataPartitionId); if (dialog.ShowDialog() == true) { try @@ -972,11 +1075,11 @@ async void ClearCustomDataPartitionCmdExecuted(object target, ExecutedRoutedEven void WebMessagesCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived; - webView.CoreWebView2.FrameCreated += WebView_FrameCreatedWebMessages; - webView.CoreWebView2.SetVirtualHostNameToFolderMapping( + _iWebView2.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived; + _iWebView2.CoreWebView2.FrameCreated += WebView_FrameCreatedWebMessages; + _iWebView2.CoreWebView2.SetVirtualHostNameToFolderMapping( "appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors); - webView.Source = new Uri("https://appassets.example/webMessages.html"); + _iWebView2.CoreWebView2.Navigate("https://appassets.example/webMessages.html"); } @@ -1003,11 +1106,11 @@ void HandleWebMessage(CoreWebView2WebMessageReceivedEventArgs args) { string reply = "{\"WindowBounds\":\"Left:" + 0 + "\\nTop:" + 0 + - "\\nRight:" + webView.ActualWidth + - "\\nBottom:" + webView.ActualHeight + + "\\nRight:" + _webView2FrameworkElement.ActualWidth + + "\\nBottom:" + _webView2FrameworkElement.ActualHeight + "\"}"; - webView.CoreWebView2.PostWebMessageAsJson(reply); + _iWebView2.CoreWebView2.PostWebMessageAsJson(reply); } else { @@ -1041,22 +1144,22 @@ void WebView_FrameCreatedWebMessages(object sender, CoreWebView2FrameCreatedEven // void DOMContentLoadedCmdExecuted(object target, ExecutedRoutedEventArgs e) { - webView.CoreWebView2.DOMContentLoaded += WebView_DOMContentLoaded; - webView.CoreWebView2.FrameCreated += WebView_FrameCreatedDOMContentLoaded; - webView.NavigateToString(@"" + + _iWebView2.CoreWebView2.DOMContentLoaded += WebView_DOMContentLoaded; + _iWebView2.CoreWebView2.FrameCreated += WebView_FrameCreatedDOMContentLoaded; + _iWebView2.NavigateToString(@"" + "

DOMContentLoaded sample page

" + "

The content to the iframe and below will be added after DOM content is loaded

" + "