-
Notifications
You must be signed in to change notification settings - Fork 518
Expand file tree
/
Copy pathMainWindow.xaml.cs
More file actions
1390 lines (1284 loc) · 60.6 KB
/
MainWindow.xaml.cs
File metadata and controls
1390 lines (1284 loc) · 60.6 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.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
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 Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
namespace WebView2WpfBrowser
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public static RoutedCommand InjectScriptCommand = new RoutedCommand();
public static RoutedCommand InjectScriptIFrameCommand = new RoutedCommand();
public static RoutedCommand PrintToPdfCommand = new RoutedCommand();
public static RoutedCommand NavigateWithWebResourceRequestCommand = new RoutedCommand();
public static RoutedCommand DOMContentLoadedCommand = 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 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 ToggleMuteStateCommand = new RoutedCommand();
bool _isNavigating = false;
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)
{
_webViewProfile = webView.CoreWebView2.Profile;
}
return _webViewProfile;
}
}
List<CoreWebView2Frame> _webViewFrames = new List<CoreWebView2Frame>();
public MainWindow()
{
InitializeComponent();
AttachControlEventHandlers(webView);
}
void AttachControlEventHandlers(WebView2 control)
{
control.NavigationStarting += WebView_NavigationStarting;
control.NavigationCompleted += WebView_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 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;
}
}
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();
}
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;
shouldAttachEnvironmentEventHandlers = true;
}
else
{
replacementControl.CreationProperties = webView.CreationProperties;
}
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(CoreWebView2ProcessFailedKind kind)
{
string caption;
string message;
if (kind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
{
caption = "Browser process exited";
message = "WebView2 Runtime's browser process exited unexpectedly. Recreate WebView?";
}
else
{
caption = "Web page unresponsive";
message = "WebView2 Runtime's render process stopped responding. Recreate WebView?";
}
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);
}
}
void ReloadIfSelectedByUser(CoreWebView2ProcessFailedKind kind)
{
string caption;
string message;
if (kind == CoreWebView2ProcessFailedKind.RenderProcessExited)
{
caption = "Web page unresponsive";
message = "WebView2 Runtime's render process exited unexpectedly. Reload page?";
}
else
{
caption = "App content frame unresponsive";
message = "WebView2 Runtime's render process for app frame exited unexpectedly. Reload page?";
}
var selection = MessageBox.Show(message, caption, MessageBoxButton.YesNo);
if (selection == MessageBoxResult.Yes)
{
webView.Reload();
}
}
bool IsAppContentUri(Uri source)
{
// Sample virtual host name for the app's content.
// See CoreWebView2.SetVirtualHostNameToFolderMapping: https://docs.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2.setvirtualhostnametofoldermapping
return source.Host == "appassets.example";
}
switch (e.ProcessFailedKind)
{
case CoreWebView2ProcessFailedKind.BrowserProcessExited:
// Once the WebView2 Runtime's browser process has crashed,
// the control becomes virtually unusable as the process exit
// moves the CoreWebView2 to its Closed state. Most calls will
// become invalid as they require a backing browser process.
// Remove the control from the visual tree so the framework does
// not attempt to redraw it, which would call the invalid methods.
RemoveControlFromVisualTree(webView);
goto case CoreWebView2ProcessFailedKind.RenderProcessUnresponsive;
case CoreWebView2ProcessFailedKind.RenderProcessUnresponsive:
System.Threading.SynchronizationContext.Current.Post((_) =>
{
ReinitIfSelectedByUser(e.ProcessFailedKind);
}, null);
break;
case CoreWebView2ProcessFailedKind.RenderProcessExited:
System.Threading.SynchronizationContext.Current.Post((_) =>
{
ReloadIfSelectedByUser(e.ProcessFailedKind);
}, null);
break;
case 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)))
{
goto case CoreWebView2ProcessFailedKind.RenderProcessExited;
}
}
break;
default:
// Show the process failure details. Apps can collect info for their logging purposes.
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}");
System.Threading.SynchronizationContext.Current.Post((_) =>
{
MessageBox.Show(messageBuilder.ToString(), "Child process failed", MessageBoxButton.OK);
}, null);
break;
}
}
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)
{
System.Drawing.Color backgroundColor = System.Drawing.Color.FromName(e.Parameter.ToString());
webView.DefaultBackgroundColor = backgroundColor;
}
async void InjectScriptCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
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");
}
}
async void InjectScriptIFrameCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
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");
}
}
}
}
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
{
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");
}
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Print to PDF Failed: " + exception.Message,
"Print to PDF");
}
}
async void GetCookiesCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
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");
}
void AddOrUpdateCookieCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
CoreWebView2Cookie cookie = webView.CoreWebView2.CookieManager.CreateCookie("CookieName", "CookieValue", ".bing.com", "/");
webView.CoreWebView2.CookieManager.AddOrUpdateCookie(cookie);
}
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)
{
WebViewSettings.UserAgent = dialog.Input.Text;
}
}
void DOMContentLoadedCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.CoreWebView2.DOMContentLoaded += (object sender, CoreWebView2DOMContentLoadedEventArgs arg) =>
{
_ = webView.ExecuteScriptAsync("let " +
"content=document.createElement(\"h2\");content.style.color=" +
"'blue';content.textContent= \"This text was added by the " +
"host app\";document.body.appendChild(content);");
};
webView.CoreWebView2.FrameCreated += (sender, args) =>
{
args.Frame.DOMContentLoaded += (frameSender, DOMContentLoadedArgs) =>
{
args.Frame.ExecuteScriptAsync(
"let content = document.createElement(\"h2\");" +
"content.style.color = 'blue';" +
"content.textContent = \"This text was added to the iframe by the host app\";" +
"document.body.appendChild(content);");
};
};
webView.NavigateToString(@"<!DOCTYPE html>" +
"<h1>DOMContentLoaded sample page</h1>" +
"<h2>The content to the iframe and below will be added after DOM content is loaded </h2>" +
"<iframe style='height: 200px; width: 100%;'/>");
}
void PasswordAutosaveCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
WebViewSettings.IsPasswordAutosaveEnabled = !WebViewSettings.IsPasswordAutosaveEnabled;
}
void GeneralAutofillCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
WebViewSettings.IsGeneralAutofillEnabled = !WebViewSettings.IsGeneralAutofillEnabled;
}
void NavigateWithWebResourceRequestCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// Prepare post data as UTF-8 byte array and convert it to stream
// as required by the application/x-www-form-urlencoded Content-Type
var dialog = new TextInputDialog(
title: "NavigateWithWebResourceRequest",
description: "Specify post data to submit to https://www.w3schools.com/action_page.php.");
if (dialog.ShowDialog() == true)
{
string postDataString = "input=" + dialog.Input.Text;
UTF8Encoding utfEncoding = new UTF8Encoding();
byte[] postData = utfEncoding.GetBytes(
postDataString);
MemoryStream postDataStream = new MemoryStream(postDataString.Length);
postDataStream.Write(postData, 0, postData.Length);
postDataStream.Seek(0, SeekOrigin.Begin);
CoreWebView2WebResourceRequest webResourceRequest =
WebViewEnvironment.CreateWebResourceRequest(
"https://www.w3schools.com/action_page.php",
"POST",
postDataStream,
"Content-Type: application/x-www-form-urlencoded\r\n");
webView.CoreWebView2.NavigateWithWebResourceRequest(webResourceRequest);
}
}
private bool _isCustomContextMenu = false;
void CustomContextMenuCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
try
{
if (!_isCustomContextMenu)
{
webView.CoreWebView2.ContextMenuRequested +=
WebView_ContextMenuRequested;
}
else
{
webView.CoreWebView2.ContextMenuRequested -=
WebView_ContextMenuRequested;
}
_isCustomContextMenu = !_isCustomContextMenu;
MessageBox.Show(this,
_isCustomContextMenu
? "Custom context menus have been enabled"
: "Custom context menus have been disabled",
"Custom context menus");
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Custom context menu Failed: " + exception.Message,
"Custom context menus");
}
}
private CoreWebView2ContextMenuItem displayUriParentContextMenuItem = null;
void WebView_ContextMenuRequested(
object sender,
CoreWebView2ContextMenuRequestedEventArgs args)
{
IList<CoreWebView2ContextMenuItem> menuList = args.MenuItems;
CoreWebView2ContextMenuTargetKind context = args.ContextMenuTarget.Kind;
// Using custom context menu UI
if (context == CoreWebView2ContextMenuTargetKind.SelectedText)
{
CoreWebView2Deferral deferral = args.GetDeferral();
args.Handled = true;
ContextMenu cm = new ContextMenu();
cm.Closed += (s, ex) => deferral.Complete();
PopulateContextMenu(args, menuList, cm);
cm.IsOpen = true;
}
// Remove item from WebView context menu
else if (context == CoreWebView2ContextMenuTargetKind.Image)
{
/// removes the last item in the collection
menuList.RemoveAt(menuList.Count - 1);
}
// Add item to WebView context menu
else if (context == CoreWebView2ContextMenuTargetKind.Page)
{
// Created context menu items should be reused.
if (displayUriParentContextMenuItem == null)
{
CoreWebView2ContextMenuItem subItem =
webView.CoreWebView2.Environment.CreateContextMenuItem(
"Display Page Uri", null,
CoreWebView2ContextMenuItemKind.Command);
subItem.CustomItemSelected += delegate (object send, Object ex) {
string pageUrl = args.ContextMenuTarget.PageUri;
System.Threading.SynchronizationContext.Current.Post((_) => {
MessageBox.Show(pageUrl, "Display Page Uri", MessageBoxButton.YesNo);
}, null);
};
displayUriParentContextMenuItem =
webView.CoreWebView2.Environment.CreateContextMenuItem(
"New Submenu", null,
CoreWebView2ContextMenuItemKind.Submenu);
IList<CoreWebView2ContextMenuItem> submenuList = displayUriParentContextMenuItem.Children;
submenuList.Insert(0, subItem);
}
menuList.Insert(menuList.Count, displayUriParentContextMenuItem);
}
}
void PopulateContextMenu(CoreWebView2ContextMenuRequestedEventArgs args,
IList<CoreWebView2ContextMenuItem> menuList,
ItemsControl cm)
{
for (int i = 0; i < menuList.Count; i++)
{
CoreWebView2ContextMenuItem current = menuList[i];
if (current.Kind == CoreWebView2ContextMenuItemKind.Separator)
{
Separator sep = new Separator();
cm.Items.Add(sep);
continue;
}
MenuItem newItem = new MenuItem();
// The accessibility key is the key after the & in the label
newItem.Header = current.Label.Replace('&', '_');
newItem.InputGestureText = current.ShortcutKeyDescription;
newItem.IsEnabled = current.IsEnabled;
if (current.Kind == CoreWebView2ContextMenuItemKind.Submenu)
{
PopulateContextMenu(args, current.Children, newItem);
}
else
{
if (current.Kind == CoreWebView2ContextMenuItemKind.CheckBox ||
current.Kind == CoreWebView2ContextMenuItemKind.Radio)
{
newItem.IsCheckable = true;
newItem.IsChecked = current.IsChecked;
}
newItem.Click +=
(s, ex) => { args.SelectedCommandId = current.CommandId; };
}
cm.Items.Add(newItem);
}
}
void PinchZoomCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
WebViewSettings.IsPinchZoomEnabled = !WebViewSettings.IsPinchZoomEnabled;
MessageBox.Show("Pinch Zoom is" + (WebViewSettings.IsPinchZoomEnabled ? " enabled " : " disabled ") + "after the next navigation.");
}
void SwipeNavigationCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// Safeguarding the handler when unsupported runtime is used.
try
{
WebViewSettings.IsSwipeNavigationEnabled = !WebViewSettings.IsSwipeNavigationEnabled;
MessageBox.Show("Swipe to navigate is" + (WebViewSettings.IsSwipeNavigationEnabled ? " enabled " : " disabled ") + "after the next navigation.");
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Toggle Swipe Navigation Failed: " + exception.Message, "Swipe Navigation");
}
}
void PdfToolbarSaveCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
if(WebViewSettings.HiddenPdfToolbarItems.HasFlag(CoreWebView2PdfToolbarItems.Save))
{
WebViewSettings.HiddenPdfToolbarItems = CoreWebView2PdfToolbarItems.None;
MessageBox.Show("Save button on PDF toolbar is enabled after the next navigation.");
}
else
{
WebViewSettings.HiddenPdfToolbarItems = CoreWebView2PdfToolbarItems.Save;
MessageBox.Show("Save button on PDF toolbar is disabled after the next navigation.");
}
}
void NewBrowserVersionCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
foreach (Window window in Application.Current.Windows)
{
if (window is MainWindow mainWindow)
{
// Simulate NewBrowserVersionAvailable being raised.
mainWindow.Environment_NewBrowserVersionAvailable(null, null);
}
}
}
void DownloadStartingCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
try
{
webView.CoreWebView2.DownloadStarting += delegate (
object sender, CoreWebView2DownloadStartingEventArgs args)
{
// Developer can obtain a deferral for the event so that the CoreWebView2
// doesn't examine the properties we set on the event args until
// after the deferral completes asynchronously.
CoreWebView2Deferral deferral = args.GetDeferral();
// We avoid potential reentrancy from running a message loop in the download
// starting event handler by showing our download dialog later when we
// complete the deferral asynchronously.
System.Threading.SynchronizationContext.Current.Post((_) =>
{
using (deferral)
{
// Hide the default download dialog.
args.Handled = true;
var dialog = new TextInputDialog(
title: "Download Starting",
description: "Enter new result file path or select OK to keep default path. Select cancel to cancel the download.",
defaultInput: args.ResultFilePath);
if (dialog.ShowDialog() == true)
{
args.ResultFilePath = dialog.Input.Text;
UpdateProgress(args.DownloadOperation);
}
else
{
args.Cancel = true;
}
}
}, null);
};
webView.CoreWebView2.Navigate("https://demo.smartscreen.msft.net/");
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "DownloadStarting Failed: " + exception.Message, "Download Starting");
}
}
// Update download progress
void UpdateProgress(CoreWebView2DownloadOperation download)
{
download.BytesReceivedChanged += delegate (object sender, Object e)
{
// Here developer can update download dialog to show progress of a
// download using `download.BytesReceived` and `download.TotalBytesToReceive`
};
download.StateChanged += delegate (object sender, Object e)
{
switch (download.State)
{
case CoreWebView2DownloadState.InProgress:
break;
case CoreWebView2DownloadState.Interrupted:
// Here developer can take different actions based on `download.InterruptReason`.
// For example, show an error message to the end user.
break;
case CoreWebView2DownloadState.Completed:
break;
}
};
}
// Turn off client certificate selection dialog using ClientCertificateRequested event handler
// that disables the dialog. This example hides the default client certificate dialog and
// always chooses the last certificate without prompting the user.
private bool _isCustomClientCertificateSelection = false;
void EnableCustomClientCertificateSelection()
{
// Safeguarding the handler when unsupported runtime is used.
try
{
if (!_isCustomClientCertificateSelection)
{
webView.CoreWebView2.ClientCertificateRequested += WebView_ClientCertificateRequested;
}
else
{
webView.CoreWebView2.ClientCertificateRequested -= WebView_ClientCertificateRequested;
}
_isCustomClientCertificateSelection = !_isCustomClientCertificateSelection;
MessageBox.Show(this,
_isCustomClientCertificateSelection ? "Custom client certificate selection has been enabled" : "Custom client certificate selection has been disabled",
"Custom client certificate selection");
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Custom client certificate selection Failed: " + exception.Message, "Custom client certificate selection");
}
}
void WebView_ClientCertificateRequested(object sender, CoreWebView2ClientCertificateRequestedEventArgs e)
{
IReadOnlyList<CoreWebView2ClientCertificate> certificateList = e.MutuallyTrustedCertificates;
if (certificateList.Count() > 0)
{
// There is no significance to the order, picking a certificate arbitrarily.
e.SelectedCertificate = certificateList.LastOrDefault();
// Continue with the selected certificate to respond to the server.
e.Handled = true;
}
else
{
// Continue without a certificate to respond to the server if certificate list is empty.
e.Handled = true;
}
}
// This example hides the default client certificate dialog and shows a custom dialog instead.
// The dialog box displays mutually trusted certificates list and allows the user to select a certificate.
// Selecting `OK` will continue the request with a certificate.
// Selecting `CANCEL` will continue the request without a certificate
private bool _isCustomClientCertificateSelectionDialog = false;
void DeferredCustomClientCertificateSelectionDialog()
{
// Safeguarding the handler when unsupported runtime is used.
try
{
if (!_isCustomClientCertificateSelectionDialog)
{
webView.CoreWebView2.ClientCertificateRequested += delegate (
object sender, CoreWebView2ClientCertificateRequestedEventArgs args)
{
// Developer can obtain a deferral for the event so that the WebView2
// doesn't examine the properties we set on the event args until
// after the deferral completes asynchronously.
CoreWebView2Deferral deferral = args.GetDeferral();
System.Threading.SynchronizationContext.Current.Post((_) =>
{
using (deferral)
{
IReadOnlyList<CoreWebView2ClientCertificate> certificateList = args.MutuallyTrustedCertificates;
if (certificateList.Count() > 0)
{
// Display custom dialog box for the client certificate selection.
var dialog = new ClientCertificateSelectionDialog(
title: "Select a Certificate for authentication",
host: args.Host,
port: args.Port,
client_cert_list: certificateList);
if (dialog.ShowDialog() == true)
{
// Continue with the selected certificate to respond to the server if `OK` is selected.
args.SelectedCertificate = (CoreWebView2ClientCertificate)dialog.CertificateDataBinding.SelectedItem;
}
// Continue without a certificate to respond to the server if `CANCEL` is selected.
args.Handled = true;
}
else
{
// Continue without a certificate to respond to the server if certificate list is empty.
args.Handled = true;
}
}
}, null);
};
_isCustomClientCertificateSelectionDialog = true;
MessageBox.Show("Custom Client Certificate selection dialog will be used next when WebView2 is making a " +
"request to an HTTP server that needs a client certificate.", "Client certificate selection");
}
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Custom client certificate selection dialog Failed: " + exception.Message, "Client certificate selection");
}
}
void GoToPageCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = webView != null && !_isNavigating;
}
async void GoToPageCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
await webView.EnsureCoreWebView2Async();
var rawUrl = (string)e.Parameter;
Uri uri = null;
if (Uri.IsWellFormedUriString(rawUrl, UriKind.Absolute))
{
uri = new Uri(rawUrl);
}
else if (!rawUrl.Contains(" ") && rawUrl.Contains("."))
{
// An invalid URI contains a dot and no spaces, try tacking http:// on the front.
uri = new Uri("http://" + rawUrl);
}
else
{
// Otherwise treat it as a web search.
uri = new Uri("https://bing.com/search?q=" +
String.Join("+", Uri.EscapeDataString(rawUrl).Split(new string[] { "%20" }, StringSplitOptions.RemoveEmptyEntries)));
}
// Setting webView.Source will not trigger a navigation if the Source is the same
// as the previous Source. CoreWebView.Navigate() will always trigger a navigation.
webView.CoreWebView2.Navigate(uri.ToString());
}
async void SuspendCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
try
{
bool isSuccessful = await webView.CoreWebView2.TrySuspendAsync();
MessageBox.Show(this,
(isSuccessful) ? "TrySuspendAsync succeeded" : "TrySuspendAsync failed",
"TrySuspendAsync");
}
catch (System.Runtime.InteropServices.COMException exception)
{
MessageBox.Show(this, "TrySuspendAsync failed:" + exception.Message, "TrySuspendAsync");
}
}
void ResumeCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
try
{
webView.CoreWebView2.Resume();
MessageBox.Show(this, "Resume Succeeded", "Resume");
}
catch (System.Runtime.InteropServices.COMException exception)
{
MessageBox.Show(this, "Resume failed:" + exception.Message, "Resume");
}
}
async void CheckUpdateCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
try
{
CoreWebView2UpdateRuntimeResult result = await webView.CoreWebView2.Environment.UpdateRuntimeAsync();
string update_result = "status: " + result.Status + ", extended error:" + result.ExtendedError;
MessageBox.Show(this, update_result, "UpdateRuntimeAsync result");
}
catch (System.Runtime.InteropServices.COMException exception)
{
MessageBox.Show(this, "UpdateRuntimeAsync failed:" + exception.Message, "UpdateRuntimeAsync");
}