-
Notifications
You must be signed in to change notification settings - Fork 462
/
MainWindow.xaml.cs
3752 lines (3444 loc) · 163 KB
/
MainWindow.xaml.cs
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 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 EnhancedSecurityModeGetBypassListCommand = new RoutedCommand();
public static RoutedCommand EnhancedSecurityModeSetBypassListCommand = new RoutedCommand();
public static RoutedCommand EnhancedSecurityModeGetEnforceListCommand = new RoutedCommand();
public static RoutedCommand EnhancedSecurityModeSetEnforceListCommand = 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 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 DedicatedWorkerCreatedCommand = new RoutedCommand();
public static RoutedCommand SharedWorkerManagerCommand = new RoutedCommand();
public static RoutedCommand GetSharedWorkersCommand = new RoutedCommand();
#endregion commands
bool _isNavigating = false;
// for add/remove initialize script
string m_lastInitializeScriptId;
CoreWebView2Settings _webViewSettings;
CoreWebView2Settings WebViewSettings
{
get
{
if (_webViewSettings == null && webView?.CoreWebView2 != null)
{
_webViewSettings = webView.CoreWebView2.Settings;
}
return _webViewSettings;
}
}
CoreWebView2Environment _webViewEnvironment;
CoreWebView2Environment WebViewEnvironment
{
get
{
if (_webViewEnvironment == null && webView?.CoreWebView2 != null)
{
_webViewEnvironment = webView.CoreWebView2.Environment;
}
return _webViewEnvironment;
}
}
CoreWebView2Profile _webViewProfile;
CoreWebView2Profile WebViewProfile
{
get
{
if (_webViewProfile == null && webView?.CoreWebView2 != null)
{
// <Profile>
_webViewProfile = webView.CoreWebView2.Profile;
// </Profile>
}
return _webViewProfile;
}
}
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()
{
DataContext = this;
Loaded += MainWindow_Loaded;
InitializeComponent();
}
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)
{
await InitializeWebView();
}
async System.Threading.Tasks.Task InitializeWebView()
{
AttachControlEventHandlers(webView);
// Set background transparent
webView.DefaultBackgroundColor = System.Drawing.Color.Transparent;
await webView.EnsureCoreWebView2Async();
}
void AttachControlEventHandlers(WebView2 control)
{
// <NavigationStarting>
control.NavigationStarting += WebView_NavigationStarting;
// </NavigationStarting>
// <NavigationCompleted>
control.NavigationCompleted += WebView_NavigationCompleted;
// </NavigationCompleted>
control.CoreWebView2InitializationCompleted += WebView_CoreWebView2InitializationCompleted;
control.KeyDown += WebView_KeyDown;
}
bool IsWebViewValid()
{
try
{
return webView != null && webView.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;
}
}
webView.Dispose();
this.Close();
}
void BackCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = webView != null && webView.CanGoBack;
}
void BackCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.GoBack();
}
void ForwardCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = webView != null && webView.CanGoForward;
}
void ForwardCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.GoForward();
}
void RefreshCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsWebViewValid() && !_isNavigating;
}
void RefreshCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.Reload();
}
void BrowseStopCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsWebViewValid() && _isNavigating;
}
void BrowseStopCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.Stop();
}
void WebViewRequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = webView != null;
}
void CoreWebView2RequiringCmdsCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = IsWebViewValid();
}
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(WebView2 control)
{
Layout.Children.Remove(control);
_isControlInVisualTree = false;
}
void AttachControlToVisualTree(WebView2 control)
{
Layout.Children.Add(control);
_isControlInVisualTree = true;
}
WebView2 GetReplacementControl(bool useNewEnvironment)
{
WebView2 replacementControl = new WebView2();
((System.ComponentModel.ISupportInitialize)(replacementControl)).BeginInit();
// Setup properties and bindings.
if (useNewEnvironment)
{
// 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;
}
else
{
replacementControl.CreationProperties = webView.CreationProperties;
}
replacementControl.CreationProperties.AreBrowserExtensionsEnabled = true;
Binding urlBinding = new Binding()
{
Source = replacementControl,
Path = new PropertyPath("Source"),
Mode = BindingMode.OneWay
};
url.SetBinding(TextBox.TextProperty, urlBinding);
AttachControlEventHandlers(replacementControl);
replacementControl.Source = webView.Source ?? new Uri("https://www.bing.com");
((System.ComponentModel.ISupportInitialize)(replacementControl)).EndInit();
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.
if (_isControlInVisualTree)
{
RemoveControlFromVisualTree(webView);
}
webView.Dispose();
webView = GetReplacementControl(false);
AttachControlToVisualTree(webView);
// Set background transparent
webView.DefaultBackgroundColor = System.Drawing.Color.Transparent;
}
});
}
void ReloadIfSelectedByUser(string caption, string message)
{
this.Dispatcher.InvokeAsync(() =>
{
var selection = MessageBox.Show(message, caption, MessageBoxButton.YesNo);
if (selection == MessageBoxResult.Yes)
{
webView.Reload();
// Set background transparent
webView.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 (webView.ZoomFactor < 1)
{
return 0.25;
}
else if (webView.ZoomFactor < 2)
{
return 0.5;
}
else
{
return 1;
}
}
void IncreaseZoomCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.ZoomFactor += ZoomStep();
}
void DecreaseZoomCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = (webView != null) && (webView.ZoomFactor - ZoomStep() > 0.0);
}
void DecreaseZoomCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.ZoomFactor -= ZoomStep();
}
void BackgroundColorCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// <DefaultBackgroundColor>
System.Drawing.Color backgroundColor = System.Drawing.Color.FromName(e.Parameter.ToString());
webView.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 webView.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 webView.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.
webView.CoreWebView2.ShowPrintUI();
}
else
{
// Opens the system print dialog.
webView.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;
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);
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 = webView.CoreWebView2.DocumentTitle;
try
{
CoreWebView2PrintStatus printStatus = await webView.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 = webView.CoreWebView2.DocumentTitle;
// Passing null for `PrintSettings` results in default print settings used.
System.IO.Stream stream = await webView.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")
{
SetTrackingPreventionLevel(CoreWebView2TrackingPreventionLevel.Basic);
}
else if (level == "Balanced")
{
SetTrackingPreventionLevel(CoreWebView2TrackingPreventionLevel.Balanced);
}
else
{
SetTrackingPreventionLevel(CoreWebView2TrackingPreventionLevel.Strict);
}
}
// <SetTrackingPreventionLevel>
void SetTrackingPreventionLevel(CoreWebView2TrackingPreventionLevel value)
{
WebViewProfile.PreferredTrackingPreventionLevel = value;
MessageBox.Show(this, "Tracking prevention level is set successfully", "Tracking Prevention Level");
}
// <SetTrackingPreventionLevel>
void EnhancedSecurityModeLevelCommandExecuted(object target, ExecutedRoutedEventArgs e)
{
}
void EnhancedSecurityModeGetBypassListCommandExecuted(object target, ExecutedRoutedEventArgs e)
{
}
void EnhancedSecurityModeSetBypassListCommandExecuted(object target, ExecutedRoutedEventArgs e)
{
}
void EnhancedSecurityModeGetEnforceListCommandExecuted(object target, ExecutedRoutedEventArgs e)
{
}
void EnhancedSecurityModeSetEnforceListCommandExecuted(object target, ExecutedRoutedEventArgs e)
{
}
async void GetCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// <GetCookies>
List<CoreWebView2Cookie> cookieList = await webView.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());
cookieResult.Append($"\n{cookie.Name} {cookie.Value} {(cookie.IsSession ? "[session cookie]" : cookie.Expires.ToString("G"))}");
}
MessageBox.Show(this, cookieResult.ToString(), "GetCookiesAsync");
// </GetCookies>
}
void AddOrUpdateCookieCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// <AddOrUpdateCookie>
CoreWebView2Cookie cookie = webView.CoreWebView2.CookieManager.CreateCookie("CookieName", "CookieValue", ".bing.com", "/");
webView.CoreWebView2.CookieManager.AddOrUpdateCookie(cookie);
// </AddOrUpdateCookie>
}
void DeleteAllCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.CoreWebView2.CookieManager.DeleteAllCookies();
}
void DeleteCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.CoreWebView2.CookieManager.DeleteCookiesWithDomainAndPath("CookieName", ".bing.com", "/");
}
void SetUserAgentCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
var dialog = new TextInputDialog(
title: "SetUserAgent",
description: "Enter UserAgent");
if (dialog.ShowDialog() == true)
{
// <SetUserAgent>
WebViewSettings.UserAgent = dialog.Input.Text;
// </SetUserAgent>
}
}
void SetCustomDataPartitionCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
#if USE_WEBVIEW2_EXPERIMENTAL
// <CustomDataPartitionId>
var dialog = new TextInputDialog(
title: "Custom Data Partition",
description: "Enter Custom Data Partition Id",
defaultInput: webView.CoreWebView2.CustomDataPartitionId);
if (dialog.ShowDialog() == true)
{
webView.CoreWebView2.CustomDataPartitionId = dialog.Input.Text;
}
// </CustomDataPartitionId>
#endif
}
async void ClearCustomDataPartitionCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
#if USE_WEBVIEW2_EXPERIMENTAL
// <ClearCustomDataPartition>
var dialog = new TextInputDialog(
title: "Clear Custom Data Partition",
description: "Enter Custom Data Partition Id to clear",
defaultInput: webView.CoreWebView2.CustomDataPartitionId);
if (dialog.ShowDialog() == true)
{
try
{
await WebViewProfile.ClearCustomDataPartitionAsync(dialog.Input.Text);
MessageBox.Show(this,
"Completed",
"Clear Custom Data Partition");
}
catch (Exception exception)
{
MessageBox.Show(this, "ClearCustomDataPartitionAsync Failed: " + exception.Message, "Clear Custom Data Partition");
}
}
// </ClearCustomDataPartition>
#else
await Task.CompletedTask;
#endif
}
void WebMessagesCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived;
webView.CoreWebView2.FrameCreated += WebView_FrameCreatedWebMessages;
webView.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
webView.Source = new Uri("https://appassets.example/webMessages.html");
}
void HandleWebMessage(CoreWebView2WebMessageReceivedEventArgs args)
{
try
{
if (args.Source != "https://appassets.example/webMessages.html")
{
// Throw exception from untrusted sources.
throw new Exception();
}
string message = args.TryGetWebMessageAsString();
if (message.Contains("SetTitleText"))
{
int msgLength = "SetTitleText".Length;
this.Title = message.Substring(msgLength);
}