-
Notifications
You must be signed in to change notification settings - Fork 517
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
4517 lines (4082 loc) · 193 KB
/
MainWindow.xaml.cs
File metadata and controls
4517 lines (4082 loc) · 193 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (C) Microsoft Corporation. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Common;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
namespace WebView2WpfBrowser
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
#region commands
public static RoutedCommand InjectScriptCommand = new RoutedCommand();
public static RoutedCommand InjectScriptIFrameCommand = new RoutedCommand();
public static RoutedCommand InjectScriptWithResultCommand = new RoutedCommand();
public static RoutedCommand PrintToPdfCommand = new RoutedCommand();
public static RoutedCommand NavigateWithWebResourceRequestCommand = new RoutedCommand();
public static RoutedCommand DOMContentLoadedCommand = new RoutedCommand();
public static RoutedCommand WebMessagesCommand = new RoutedCommand();
public static RoutedCommand GetCookiesCommand = new RoutedCommand();
public static RoutedCommand SuspendCommand = new RoutedCommand();
public static RoutedCommand ResumeCommand = new RoutedCommand();
public static RoutedCommand CheckUpdateCommand = new RoutedCommand();
public static RoutedCommand NewBrowserVersionCommand = new RoutedCommand();
public static RoutedCommand PdfToolbarSaveCommand = new RoutedCommand();
public static RoutedCommand SmartScreenEnabledCommand = new RoutedCommand();
public static RoutedCommand AuthenticationCommand = new RoutedCommand();
public static RoutedCommand FaviconChangedCommand = new RoutedCommand();
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();
public static RoutedCommand BackgroundColorCommand = new RoutedCommand();
public static RoutedCommand DownloadStartingCommand = new RoutedCommand();
public static RoutedCommand AddOrUpdateCookieCommand = new RoutedCommand();
public static RoutedCommand DeleteCookiesCommand = new RoutedCommand();
public static RoutedCommand DeleteAllCookiesCommand = new RoutedCommand();
public static RoutedCommand SetUserAgentCommand = new RoutedCommand();
public static RoutedCommand PasswordAutosaveCommand = new RoutedCommand();
public static RoutedCommand GeneralAutofillCommand = new RoutedCommand();
public static RoutedCommand PinchZoomCommand = new RoutedCommand();
public static RoutedCommand SwipeNavigationCommand = new RoutedCommand();
public static RoutedCommand DeleteProfileCommand = new RoutedCommand();
public static RoutedCommand NonClientRegionSupportCommand = new RoutedCommand();
public static RoutedCommand NonClientRegionSupportEnabledCommand = new RoutedCommand();
public static RoutedCommand ToggleMuteStateCommand = new RoutedCommand();
public static RoutedCommand AllowExternalDropCommand = new RoutedCommand();
public static RoutedCommand LaunchingExternalUriSchemeCommand = new RoutedCommand();
public static RoutedCommand PerfInfoCommand = new RoutedCommand();
public static RoutedCommand CustomServerCertificateSupportCommand = new RoutedCommand();
public static RoutedCommand ClearServerCertificateErrorActionsCommand = new RoutedCommand();
public static RoutedCommand NewWindowWithOptionsCommand = new RoutedCommand();
public static RoutedCommand CreateNewThreadCommand = new RoutedCommand();
public static RoutedCommand ExtensionsCommand = new RoutedCommand();
public static RoutedCommand TrackingPreventionLevelCommand = new RoutedCommand();
public static RoutedCommand EnhancedSecurityModeLevelCommand = new RoutedCommand();
public static RoutedCommand WebRtcUdpPortConfigCommand = new RoutedCommand();
public static RoutedCommand PrintDialogCommand = new RoutedCommand();
public static RoutedCommand PrintToDefaultPrinterCommand = new RoutedCommand();
public static RoutedCommand PrintToPrinterCommand = new RoutedCommand();
public static RoutedCommand PrintToPdfStreamCommand = new RoutedCommand();
// Commands(V2)
public static RoutedCommand AboutCommand = new RoutedCommand();
public static RoutedCommand CrashBrowserProcessCommand = new RoutedCommand();
public static RoutedCommand CrashRenderProcessCommand = new RoutedCommand();
public static RoutedCommand GetDocumentTitleCommand = new RoutedCommand();
public static RoutedCommand GetUserDataFolderCommand = new RoutedCommand();
public static RoutedCommand SharedBufferRequestedCommand = new RoutedCommand();
public static RoutedCommand PostMessageStringCommand = new RoutedCommand();
public static RoutedCommand PostMessageJSONCommand = new RoutedCommand();
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();
public static RoutedCommand AddInitializeScriptCommand = new RoutedCommand();
public static RoutedCommand RemoveInitializeScriptCommand = new RoutedCommand();
public static RoutedCommand CallCdpMethodCommand = new RoutedCommand();
public static RoutedCommand OpenDevToolsCommand = new RoutedCommand();
public static RoutedCommand OpenTaskManagerCommand = new RoutedCommand();
public static RoutedCommand PermissionManagementCommand = new RoutedCommand();
public static RoutedCommand NotificationReceivedCommand = new RoutedCommand();
public static RoutedCommand SetCustomDataPartitionCommand = new RoutedCommand();
public static RoutedCommand ClearCustomDataPartitionCommand = new RoutedCommand();
public static RoutedCommand ProcessExtendedInfoCommand = new RoutedCommand();
public static RoutedCommand ProgrammaticSaveAsCommand = new RoutedCommand();
public static RoutedCommand ToggleSilentCommand = new RoutedCommand();
public static RoutedCommand ThrottlingControlCommand = new RoutedCommand();
public static RoutedCommand FileExplorerCommand = new RoutedCommand();
public static RoutedCommand ToggleScreenCaptureEnableCommand = new RoutedCommand();
public static RoutedCommand FileTypePolicyCommand = new RoutedCommand();
public static RoutedCommand ServiceWorkerRegisteredCommand = new RoutedCommand();
public static RoutedCommand GetServiceWorkerRegistrationsCommand = new RoutedCommand();
public static RoutedCommand GetServiceWorkerRegisteredForScopeCommand = new RoutedCommand();
public static RoutedCommand ServiceWorkerPostMessageCommand = new RoutedCommand();
public static RoutedCommand DedicatedWorkerCreatedCommand = new RoutedCommand();
public static RoutedCommand DedicatedWorkerPostMessageCommand = new RoutedCommand();
public static RoutedCommand SharedWorkerManagerCommand = new RoutedCommand();
public static RoutedCommand GetSharedWorkersCommand = new RoutedCommand();
public static RoutedCommand ServiceWorkerSyncManagerCommand = new RoutedCommand();
public static RoutedCommand ChildFrameEventsCommand = new RoutedCommand();
public static RoutedCommand RemoveChildFrameEventsCommand = new RoutedCommand();
public static RoutedCommand StartCommand = new RoutedCommand();
public static RoutedCommand FindNextCommand = new RoutedCommand();
public static RoutedCommand FindPreviousCommand = new RoutedCommand();
public static RoutedCommand StopFindCommand = new RoutedCommand();
public static RoutedCommand FindTermCommand = new RoutedCommand();
public static RoutedCommand GetMatchCountCommand = new RoutedCommand();
public static RoutedCommand GetActiveMatchIndexCommand = new RoutedCommand();
public static RoutedCommand ToggleCaseSensitiveCommand = new RoutedCommand();
public static RoutedCommand ToggleShouldHighlightAllMatchesCommand = new RoutedCommand();
public static RoutedCommand ToggleShouldMatchWordCommand = new RoutedCommand();
public static RoutedCommand ToggleSuppressDefaultFindDialogCommand = new RoutedCommand();
#endregion commands
bool _isNavigating = false;
// for add/remove initialize script
string m_lastInitializeScriptId;
CoreWebView2Settings _webViewSettings;
CoreWebView2Settings WebViewSettings
{
get
{
if (_webViewSettings == null && _iWebView2?.CoreWebView2 != null)
{
_webViewSettings = _iWebView2.CoreWebView2.Settings;
}
return _webViewSettings;
}
}
CoreWebView2Environment _webViewEnvironment;
CoreWebView2Environment WebViewEnvironment
{
get
{
if (_webViewEnvironment == null && _iWebView2?.CoreWebView2 != null)
{
_webViewEnvironment = _iWebView2.CoreWebView2.Environment;
}
return _webViewEnvironment;
}
}
CoreWebView2Profile _webViewProfile;
CoreWebView2Profile WebViewProfile
{
get
{
if (_webViewProfile == null && _iWebView2?.CoreWebView2 != null)
{
// <Profile>
_webViewProfile = _iWebView2.CoreWebView2.Profile;
// </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;
WebView2CompositionControl webView2CompositionControlXamlElement = null;
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<CoreWebView2Frame> _webViewFrames = new List<CoreWebView2Frame>();
IReadOnlyList<CoreWebView2ProcessInfo> _processList = new List<CoreWebView2ProcessInfo>();
IDictionary<(string, CoreWebView2PermissionKind, bool), bool> _cachedPermissions =
new Dictionary<(string, CoreWebView2PermissionKind, bool), bool>();
List<CoreWebView2PermissionKind> _permissionKinds = new List<CoreWebView2PermissionKind>
{
CoreWebView2PermissionKind.Microphone,
CoreWebView2PermissionKind.Camera,
CoreWebView2PermissionKind.Geolocation,
CoreWebView2PermissionKind.Notifications,
CoreWebView2PermissionKind.OtherSensors,
CoreWebView2PermissionKind.ClipboardRead,
CoreWebView2PermissionKind.MultipleAutomaticDownloads,
CoreWebView2PermissionKind.FileReadWrite,
CoreWebView2PermissionKind.Autoplay,
CoreWebView2PermissionKind.LocalFonts,
CoreWebView2PermissionKind.MidiSystemExclusiveMessages,
CoreWebView2PermissionKind.WindowManagement,
};
List<CoreWebView2PermissionState> _permissionStates = new List<CoreWebView2PermissionState>
{
CoreWebView2PermissionState.Allow,
CoreWebView2PermissionState.Deny,
CoreWebView2PermissionState.Default
};
List<CoreWebView2SaveAsKind> _saveAsKindList = new List<CoreWebView2SaveAsKind>
{
CoreWebView2SaveAsKind.Default,
CoreWebView2SaveAsKind.HtmlOnly,
CoreWebView2SaveAsKind.SingleFile,
CoreWebView2SaveAsKind.Complete,
};
public CoreWebView2CreationProperties CreationProperties { get; set; } = null;
public MainWindow() : this(null, false)
{
}
public MainWindow(
CoreWebView2CreationProperties creationProperties = null,
bool isNewWindowRequest = false)
{
this.CreationProperties = creationProperties;
DataContext = this;
Loaded += MainWindow_Loaded;
_isNewWindowRequest = isNewWindowRequest;
InitializeComponent();
}
private async void MainWindow_Loaded(object sender, RoutedEventArgs e)
{
// 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 (useCompositionControl)
{
webView2CompositionControlXamlElement = newWebView2 as WebView2CompositionControl;
}
else
{
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 Task InitializeWebView(IWebView2 webView2)
{
if (this.CreationProperties != null)
{
webView2.CreationProperties = this.CreationProperties;
}
AttachControlEventHandlers(webView2);
// Set background transparent
webView2.DefaultBackgroundColor = System.Drawing.Color.Transparent;
// Create environment with options and configure WebRTC UDP port range
#if USE_WEBVIEW2_EXPERIMENTAL
// <SetAllowedPortRange>
CoreWebView2EnvironmentOptions options = new CoreWebView2EnvironmentOptions();
try
{
// Set allowed port range for WebRTC UDP traffic (example: ports 10000-20000)
options.SetAllowedPortRange(
CoreWebView2AllowedPortRangeScope.WebRtc,
CoreWebView2TransportProtocolKind.Udp,
10000,
20000);
}
catch (Exception ex)
{
// Handle any errors setting the port range
System.Diagnostics.Debug.WriteLine($"Failed to set WebRTC UDP port range: {ex.Message}");
}
string browserExecutableFolder = null;
if (webView2.CreationProperties?.BrowserExecutableFolder != null)
{
browserExecutableFolder = webView2.CreationProperties.BrowserExecutableFolder;
}
CoreWebView2Environment environment = await CoreWebView2Environment.CreateAsync(browserExecutableFolder, null, options);
// Configure WebRTC UDP port range if experimental API is available
await webView2.EnsureCoreWebView2Async(environment);
// </SetAllowedPortRange>
#else
await webView2.EnsureCoreWebView2Async();
#endif
}
// 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 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 _iWebView2 != null && _iWebView2.CoreWebView2 != null;
}
catch (Exception ex) when (ex is ObjectDisposedException || ex is InvalidOperationException)
{
return false;
}
}
void AssertCondition(bool condition, string message)
{
if (condition)
return;
MessageBox.Show(message, "Assertion Failed");
}
void NewCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
new MainWindow().Show();
}
void CloseCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
if (_isPrintToPdfInProgress)
{
var selection = MessageBox.Show(
"Print to PDF in progress. Continue closing?",
"Print to PDF", MessageBoxButton.YesNo);
if (selection == MessageBoxResult.No)
{
return;
}
}
CloseWebView();
this.Close(); // Close the window
}
void BackCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _iWebView2 != null && _iWebView2.CanGoBack;
}
void BackCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
_iWebView2.GoBack();
}
void ForwardCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _iWebView2 != null && _iWebView2.CanGoForward;
}
void ForwardCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
_iWebView2.GoForward();
}
void RefreshCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsWebViewValid() && !_isNavigating;
}
void RefreshCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
_iWebView2.Reload();
}
void BrowseStopCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsWebViewValid() && _isNavigating;
}
void BrowseStopCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
_iWebView2.Stop();
}
void WebViewRequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = _iWebView2 != null;
}
void CoreWebView2RequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
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();
}
void DeferredCustomCertificateDialogCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
DeferredCustomClientCertificateSelectionDialog();
}
void LaunchingExternalUriSchemeCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
EnableLaunchingExternalUriSchemeSupport();
}
void CustomServerCertificateSupportCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
ToggleCustomServerCertificateSupport();
}
void ClearServerCertificateErrorActionsCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
ClearServerCertificateErrorActions();
}
void PrintDialogCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
ShowPrintUI(target, e);
}
void PrintToDefaultPrinterCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
PrintToDefaultPrinter();
}
void PrintToPrinterCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
PrintToPrinter();
}
void PrintToPdfStreamCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
PrintToPdfStream();
}
private bool _isControlInVisualTree = true;
void RemoveControlFromVisualTree(UIElement control)
{
if (_isControlInVisualTree)
{
Layout.Children.Remove(control);
}
_isControlInVisualTree = false;
}
void AttachControlToVisualTree(UIElement control)
{
Layout.Children.Add(control);
_isControlInVisualTree = true;
}
IWebView2 CreateReplacementControl(bool useNewEnvironment, bool useCompositionControl)
{
IWebView2 replacementControl;
if (useCompositionControl)
{
replacementControl = new WebView2CompositionControl();
}
else
{
replacementControl = new WebView2();
}
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,
Path = new PropertyPath("Source"),
Mode = BindingMode.OneWay
};
url.SetBinding(TextBox.TextProperty, urlBinding);
AttachControlEventHandlers(replacementControl);
return replacementControl;
}
void WebView_ProcessFailed(object sender, CoreWebView2ProcessFailedEventArgs e)
{
void ReinitIfSelectedByUser(string caption, string message)
{
this.Dispatcher.InvokeAsync(() =>
{
var selection = MessageBox.Show(message, caption, MessageBoxButton.YesNo);
if (selection == MessageBoxResult.Yes)
{
// 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.
_ = ReinitializeWebView(_useCompositionControl);
}
});
}
void ReloadIfSelectedByUser(string caption, string message)
{
this.Dispatcher.InvokeAsync(() =>
{
var selection = MessageBox.Show(message, caption, MessageBoxButton.YesNo);
if (selection == MessageBoxResult.Yes)
{
_iWebView2.Reload();
// Set background transparent
_iWebView2.DefaultBackgroundColor = System.Drawing.Color.Transparent;
}
});
}
bool IsAppContentUri(Uri source)
{
// Sample virtual host name for the app's content.
// See CoreWebView2.SetVirtualHostNameToFolderMapping: https://learn.microsoft.com/dotnet/api/microsoft.web.webview2.core.corewebview2.setvirtualhostnametofoldermapping
return source.Host == "appassets.example";
}
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.FrameRenderProcessExited)
{
// A frame-only renderer has exited unexpectedly. Check if reload is needed.
// In this sample we only reload if the app's content has been impacted.
foreach (CoreWebView2FrameInfo frameInfo in e.FrameInfosForFailedProcess)
{
if (IsAppContentUri(new System.Uri(frameInfo.Source)))
{
System.Threading.SynchronizationContext.Current.Post((_) =>
{
ReloadIfSelectedByUser("App content frame unresponsive",
"Browser render process for app frame exited unexpectedly. Reload page?");
}, null);
}
}
return;
}
// Show the process failure details. Apps can collect info for their logging purposes.
this.Dispatcher.InvokeAsync(() =>
{
StringBuilder messageBuilder = new StringBuilder();
messageBuilder.AppendLine($"Process kind: {e.ProcessFailedKind}");
messageBuilder.AppendLine($"Reason: {e.Reason}");
messageBuilder.AppendLine($"Exit code: {e.ExitCode}");
messageBuilder.AppendLine($"Process description: {e.ProcessDescription}");
MessageBox.Show(messageBuilder.ToString(), "Child process failed", MessageBoxButton.OK);
});
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
{
ReinitIfSelectedByUser("Browser process exited",
"Browser process exited unexpectedly. Recreate webview?");
}
else if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.RenderProcessUnresponsive)
{
ReinitIfSelectedByUser("Web page unresponsive",
"Browser render process has stopped responding. Recreate webview?");
}
else if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.RenderProcessExited)
{
ReloadIfSelectedByUser("Web page unresponsive",
"Browser render process exited unexpectedly. Reload page?");
}
}
double ZoomStep()
{
if (_iWebView2.ZoomFactor < 1)
{
return 0.25;
}
else if (_iWebView2.ZoomFactor < 2)
{
return 0.5;
}
else
{
return 1;
}
}
void IncreaseZoomCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
_iWebView2.ZoomFactor += ZoomStep();
}
void DecreaseZoomCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (_iWebView2 != null) && (_iWebView2.ZoomFactor - ZoomStep() > 0.0);
}
void DecreaseZoomCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
_iWebView2.ZoomFactor -= ZoomStep();
}
void BackgroundColorCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// <DefaultBackgroundColor>
System.Drawing.Color backgroundColor = System.Drawing.Color.FromName(e.Parameter.ToString());
_iWebView2.DefaultBackgroundColor = backgroundColor;
// </DefaultBackgroundColor>
}
async void InjectScriptCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// <ExecuteScript>
var dialog = new TextInputDialog(
title: "Inject Script",
description: "Enter some JavaScript to be executed in the context of this page.",
defaultInput: "window.getComputedStyle(document.body).backgroundColor");
if (dialog.ShowDialog() == true)
{
string scriptResult = await _iWebView2.ExecuteScriptAsync(dialog.Input.Text);
MessageBox.Show(this, scriptResult, "Script Result");
}
// </ExecuteScript>
}
async void InjectScriptIFrameCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// <ExecuteScriptFrame>
string iframesData = WebViewFrames_ToString();
string iframesInfo = "Enter iframe to run the JavaScript code in.\r\nAvailable iframes: " + iframesData;
var dialogIFrames = new TextInputDialog(
title: "Inject Script Into IFrame",
description: iframesInfo,
defaultInput: "0");
if (dialogIFrames.ShowDialog() == true)
{
int iframeNumber = -1;
try
{
iframeNumber = Int32.Parse(dialogIFrames.Input.Text);
}
catch (FormatException)
{
Console.WriteLine("Can not convert " + dialogIFrames.Input.Text + " to int");
}
if (iframeNumber >= 0 && iframeNumber < _webViewFrames.Count)
{
var dialog = new TextInputDialog(
title: "Inject Script",
description: "Enter some JavaScript to be executed in the context of iframe " + dialogIFrames.Input.Text,
defaultInput: "window.getComputedStyle(document.body).backgroundColor");
if (dialog.ShowDialog() == true)
{
string scriptResult = await _webViewFrames[iframeNumber].ExecuteScriptAsync(dialog.Input.Text);
MessageBox.Show(this, scriptResult, "Script Result");
}
}
}
// </ExecuteScriptFrame>
}
private bool _isPrintToPdfInProgress = false;
async void PrintToPdfCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
if (_isPrintToPdfInProgress)
{
MessageBox.Show(this, "Print to PDF in progress", "Print To PDF");
return;
}
try
{
// <PrintToPdf>
CoreWebView2PrintSettings printSettings = null;
string orientationString = e.Parameter.ToString();
if (orientationString == "Landscape")
{
printSettings = WebViewEnvironment.CreatePrintSettings();
printSettings.Orientation =
CoreWebView2PrintOrientation.Landscape;
}
Microsoft.Win32.SaveFileDialog saveFileDialog =
new Microsoft.Win32.SaveFileDialog();
saveFileDialog.InitialDirectory = "C:\\";
saveFileDialog.Filter = "Pdf Files|*.pdf";
Nullable<bool> result = saveFileDialog.ShowDialog();
if (result == true)
{
_isPrintToPdfInProgress = true;
bool isSuccessful = await _iWebView2.CoreWebView2.PrintToPdfAsync(
saveFileDialog.FileName, printSettings);
_isPrintToPdfInProgress = false;
string message = (isSuccessful) ?
"Print to PDF succeeded" : "Print to PDF failed";
MessageBox.Show(this, message, "Print To PDF Completed");
}
// </PrintToPdf>
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Print to PDF Failed: " + exception.Message,
"Print to PDF");
}
}
// Shows the user a print dialog. If `printDialogKind` is browser print preview,
// opens a browser print preview dialog, CoreWebView2PrintDialogKind.System opens a system print dialog.
void ShowPrintUI(object target, ExecutedRoutedEventArgs e)
{
string printDialog = e.Parameter.ToString();
if (printDialog == "Browser")
{
// Opens the browser print preview dialog.
_iWebView2.CoreWebView2.ShowPrintUI();
}
else
{
// Opens the system print dialog.
_iWebView2.CoreWebView2.ShowPrintUI(CoreWebView2PrintDialogKind.System);
}
}
// This example prints the current web page without a print dialog to default printer.
async void PrintToDefaultPrinter()
{
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 _iWebView2.CoreWebView2.PrintAsync(null);
if (printStatus == CoreWebView2PrintStatus.Succeeded)
{
MessageBox.Show(this, "Printing " + title + " document to printer is succeeded", "Print");
}
else if (printStatus == CoreWebView2PrintStatus.PrinterUnavailable)
{
MessageBox.Show(this, "Printer is not available, offline or error state", "Print");
}
else
{
MessageBox.Show(this, "Printing " + title + " document to printer is failed",
"Print");
}
}
catch (Exception)
{
MessageBox.Show(this, "Printing " + title + " document already in progress",
"Print");
}
}
// <PrintToPrinter>
// Function to get printer name by displaying printer text input dialog to the user.
// User has to specify the desired printer name by querying the installed printers list on the
// OS to print the web page.
// You may also choose to display printers list to the user and return user selected printer.
string GetPrinterName()
{
string printerName = "";
var dialog = new TextInputDialog(
title: "Printer Name",
description: "Specify a printer name from the installed printers list on the OS.",
defaultInput: "");
if (dialog.ShowDialog() == true)
{
printerName = dialog.Input.Text;
}
return printerName;
// or
//
// Use GetPrintQueues() of LocalPrintServer from System.Printing to get list of locally installed printers.
// Display the printer list to the user and get the desired printer to print.
// Return the user selected printer name.
}
// Function to get print settings for the selected printer.
// You may also choose get the capabilities from the native printer API, display to the user to get
// the print settings for the current web page and for the selected printer.
CoreWebView2PrintSettings GetSelectedPrinterPrintSettings(string printerName)
{
CoreWebView2PrintSettings printSettings = null;
printSettings = WebViewEnvironment.CreatePrintSettings();
printSettings.ShouldPrintBackgrounds = true;
printSettings.ShouldPrintHeaderAndFooter = true;
return printSettings;
// or
//
// Get PrintQueue for the selected printer and use GetPrintCapabilities() of PrintQueue from System.Printing
// to get the capabilities of the selected printer.
// Display the printer capabilities to the user along with the page settings.
// Return the user selected settings.
}
// This example prints the current web page to the specified printer with the settings.
async void PrintToPrinter()
{
string printerName = GetPrinterName();
CoreWebView2PrintSettings printSettings = GetSelectedPrinterPrintSettings(printerName);
string title = _iWebView2.CoreWebView2.DocumentTitle;
try
{
CoreWebView2PrintStatus printStatus = await _iWebView2.CoreWebView2.PrintAsync(printSettings);
if (printStatus == CoreWebView2PrintStatus.Succeeded)
{
MessageBox.Show(this, "Printing " + title + " document to printer is succeeded", "Print to printer");
}
else if (printStatus == CoreWebView2PrintStatus.PrinterUnavailable)
{
MessageBox.Show(this, "Selected printer is not found, not available, offline or error state", "Print to printer");
}
else
{
MessageBox.Show(this, "Printing " + title + " document to printer is failed",
"Print");
}
}
catch (ArgumentException)
{
MessageBox.Show(this, "Invalid settings provided for the specified printer",
"Print");
}
catch (Exception)
{
MessageBox.Show(this, "Printing " + title + " document already in progress",
"Print");
}
}
// </PrintToPrinter>
// <PrintToPdfStream>
// This example prints the Pdf data of the current web page to a stream.
async void PrintToPdfStream()
{
try
{
string title = _iWebView2.CoreWebView2.DocumentTitle;
// Passing null for `PrintSettings` results in default print settings used.
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");
}
catch (Exception exception)
{
MessageBox.Show(this, "Printing to PDF Stream failed: " + exception.Message,
"Print to PDF Stream");
}
}
// Function to display current page pdf data in a custom print preview dialog.
void DisplayPdfDataInPrintDialog(Stream pdfData)
{
// You can display the printable pdf data in a custom print preview dialog to the end user.
}
// </PrintToPdfStream>
void TrackingPreventionLevelCommandExecuted(object target, ExecutedRoutedEventArgs e)
{
string level = e.Parameter.ToString();
if (level == "None")
{
SetTrackingPreventionLevel(CoreWebView2TrackingPreventionLevel.None);
}
else if (level == "Basic")
{