-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBrowserForm.cs
More file actions
1490 lines (1364 loc) · 58.9 KB
/
BrowserForm.cs
File metadata and controls
1490 lines (1364 loc) · 58.9 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.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Threading;
using System.Text;
using System.IO;
using System.Windows.Forms;
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.WinForms;
using System.Linq;
using System.ComponentModel;
namespace WebView2WindowsFormsBrowser
{
public partial class BrowserForm : Form
{
private CoreWebView2CreationProperties _creationProperties = null;
public CoreWebView2CreationProperties CreationProperties
{
get
{
if (_creationProperties == null)
{
_creationProperties = new Microsoft.Web.WebView2.WinForms.CoreWebView2CreationProperties();
}
return _creationProperties;
}
set
{
_creationProperties = value;
}
}
public BrowserForm()
{
InitializeComponent();
AttachControlEventHandlers(this.webView2Control);
HandleResize();
}
public BrowserForm(CoreWebView2CreationProperties creationProperties = null)
{
this.CreationProperties = creationProperties;
InitializeComponent();
AttachControlEventHandlers(this.webView2Control);
HandleResize();
}
private void UpdateTitleWithEvent(string message)
{
string currentDocumentTitle = this.webView2Control?.CoreWebView2?.DocumentTitle ?? "Uninitialized";
this.Text = currentDocumentTitle + " (" + message + ")";
}
CoreWebView2Environment _webViewEnvironment;
CoreWebView2Environment WebViewEnvironment
{
get
{
if (_webViewEnvironment == null && webView2Control?.CoreWebView2 != null)
{
_webViewEnvironment = webView2Control.CoreWebView2.Environment;
}
return _webViewEnvironment;
}
}
CoreWebView2Settings _webViewSettings;
CoreWebView2Settings WebViewSettings
{
get
{
if (_webViewSettings == null && webView2Control?.CoreWebView2 != null)
{
_webViewSettings = webView2Control.CoreWebView2.Settings;
}
return _webViewSettings;
}
}
string _lastInitializeScriptId;
List<CoreWebView2Frame> _webViewFrames = new List<CoreWebView2Frame>();
void WebView_HandleIFrames(object sender, CoreWebView2FrameCreatedEventArgs args)
{
_webViewFrames.Add(args.Frame);
args.Frame.Destroyed += WebViewFrames_DestoryedNestedIFrames;
}
void WebViewFrames_DestoryedNestedIFrames(object sender, object args)
{
try
{
var frameToRemove = _webViewFrames.SingleOrDefault(r => r.IsDestroyed() == 1);
if (frameToRemove != null)
_webViewFrames.Remove(frameToRemove);
}
catch (InvalidOperationException ex)
{
MessageBox.Show(ex.Message);
}
}
string WebViewFrames_ToString()
{
string result = "";
for (var i = 0; i < _webViewFrames.Count; i++)
{
if (i > 0) result += "; ";
result += i.ToString() + " " +
(String.IsNullOrEmpty(_webViewFrames[i].Name) ? "<empty_name>" : _webViewFrames[i].Name);
}
return String.IsNullOrEmpty(result) ? "no iframes available." : result;
}
#region Event Handlers
// Enable (or disable) buttons when webview2 is init (or disposed). Similar to the CanExecute feature of WPF.
private void UpdateButtons(bool isEnabled)
{
this.btnEvents.Enabled = isEnabled;
this.btnBack.Enabled = isEnabled && webView2Control != null && webView2Control.CanGoBack;
this.btnForward.Enabled = isEnabled && webView2Control != null && webView2Control.CanGoForward;
this.btnRefresh.Enabled = isEnabled;
this.btnGo.Enabled = isEnabled;
this.closeWebViewToolStripMenuItem.Enabled = isEnabled;
this.allowExternalDropMenuItem.Enabled = isEnabled;
this.xToolStripMenuItem.Enabled = isEnabled;
this.xToolStripMenuItem1.Enabled = isEnabled;
this.xToolStripMenuItem2.Enabled = isEnabled;
this.xToolStripMenuItem3.Enabled = isEnabled;
this.whiteBackgroundColorMenuItem.Enabled = isEnabled;
this.redBackgroundColorMenuItem.Enabled = isEnabled;
this.blueBackgroundColorMenuItem.Enabled = isEnabled;
this.transparentBackgroundColorMenuItem.Enabled = isEnabled;
}
private void EnableButtons()
{
UpdateButtons(true);
}
private void DisableButtons(object sender, EventArgs e)
{
UpdateButtons(false);
}
private void WebView2Control_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
{
UpdateTitleWithEvent("NavigationStarting");
}
private void WebView2Control_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
UpdateTitleWithEvent("NavigationCompleted");
}
private void WebView2Control_SourceChanged(object sender, CoreWebView2SourceChangedEventArgs e)
{
txtUrl.Text = webView2Control.Source.AbsoluteUri;
}
private void WebView2Control_CoreWebView2InitializationCompleted(object sender, CoreWebView2InitializationCompletedEventArgs e)
{
if (!e.IsSuccess)
{
MessageBox.Show($"WebView2 creation failed with exception = {e.InitializationException}");
UpdateTitleWithEvent("CoreWebView2InitializationCompleted failed");
return;
}
// Setup host resource mapping for local files
this.webView2Control.CoreWebView2.SetVirtualHostNameToFolderMapping("appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
this.webView2Control.Source = new Uri(GetStartPageUri(this.webView2Control.CoreWebView2));
this.webView2Control.CoreWebView2.SourceChanged += CoreWebView2_SourceChanged;
this.webView2Control.CoreWebView2.HistoryChanged += CoreWebView2_HistoryChanged;
this.webView2Control.CoreWebView2.DocumentTitleChanged += CoreWebView2_DocumentTitleChanged;
this.webView2Control.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.Image, CoreWebView2WebResourceRequestSourceKinds.Document);
this.webView2Control.CoreWebView2.ProcessFailed += CoreWebView2_ProcessFailed;
this.webView2Control.CoreWebView2.FrameCreated += WebView_HandleIFrames;
UpdateTitleWithEvent("CoreWebView2InitializationCompleted succeeded");
EnableButtons();
}
void AttachControlEventHandlers(Microsoft.Web.WebView2.WinForms.WebView2 control)
{
control.CoreWebView2InitializationCompleted += WebView2Control_CoreWebView2InitializationCompleted;
control.NavigationStarting += WebView2Control_NavigationStarting;
control.NavigationCompleted += WebView2Control_NavigationCompleted;
control.SourceChanged += WebView2Control_SourceChanged;
control.KeyDown += WebView2Control_KeyDown;
control.KeyUp += WebView2Control_KeyUp;
control.Disposed += DisableButtons;
}
private void WebView2Control_KeyUp(object sender, KeyEventArgs e)
{
UpdateTitleWithEvent($"KeyUp key={e.KeyCode}");
if (!this.acceleratorKeysEnabledToolStripMenuItem.Checked)
e.Handled = true;
}
private void WebView2Control_KeyDown(object sender, KeyEventArgs e)
{
UpdateTitleWithEvent($"KeyDown key={e.KeyCode}");
if (!this.acceleratorKeysEnabledToolStripMenuItem.Checked)
e.Handled = true;
}
private void CoreWebView2_HistoryChanged(object sender, object e)
{
// No explicit check for webView2Control initialization because the events can only start
// firing after the CoreWebView2 and its events exist for us to subscribe.
btnBack.Enabled = webView2Control.CoreWebView2.CanGoBack;
btnForward.Enabled = webView2Control.CoreWebView2.CanGoForward;
UpdateTitleWithEvent("HistoryChanged");
}
private void CoreWebView2_SourceChanged(object sender, CoreWebView2SourceChangedEventArgs e)
{
this.txtUrl.Text = this.webView2Control.Source.AbsoluteUri;
UpdateTitleWithEvent("SourceChanged");
}
private void CoreWebView2_DocumentTitleChanged(object sender, object e)
{
this.Text = this.webView2Control.CoreWebView2.DocumentTitle;
UpdateTitleWithEvent("DocumentTitleChanged");
}
#endregion
#region UI event handlers
private void BtnRefresh_Click(object sender, EventArgs e)
{
webView2Control.Reload();
}
private void BtnGo_Click(object sender, EventArgs e)
{
var rawUrl = txtUrl.Text;
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)));
}
webView2Control.Source = uri;
if (ShouldBlockUri())
{
webView2Control.CoreWebView2.NavigateToString("You've attempted to navigate to a domain in the blocked sites list. Press back to return to the previous page.");
}
}
private void btnBack_Click(object sender, EventArgs e)
{
webView2Control.GoBack();
}
private void btnEvents_Click(object sender, EventArgs e)
{
(new EventMonitor(this.webView2Control)).Show(this);
}
private void btnForward_Click(object sender, EventArgs e)
{
webView2Control.GoForward();
}
private void Form_Resize(object sender, EventArgs e)
{
HandleResize();
}
private void closeWebViewToolStripMenuItem_Click(object sender, EventArgs e)
{
this.Controls.Remove(webView2Control);
webView2Control.Dispose();
}
private void createWebViewToolStripMenuItem_Click(object sender, EventArgs e)
{
void EnsureProcessIsClose(uint pid) {
try
{
var process = Process.GetProcessById((int)pid);
process.Kill();
}
catch (ArgumentException)
{
// Process already exited.
}
}
if (this.webView2Control.CoreWebView2 != null)
{
var processId = this.webView2Control.CoreWebView2.BrowserProcessId;
this.Controls.Remove(this.webView2Control);
this.webView2Control.Dispose();
EnsureProcessIsClose(processId);
}
this.webView2Control = GetReplacementControl(false);
// Set background transparent
this.webView2Control.DefaultBackgroundColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.webView2Control);
HandleResize();
}
private void createNewWindowToolStripMenuItem_Click(object sender, EventArgs e)
{
new BrowserForm().Show();
}
private void createNewWindowWithOptionsToolStripMenuItem_Click(object sender, EventArgs e)
{
var dialog = new NewWindowOptionsDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
new BrowserForm(dialog.CreationProperties).Show();
}
}
private void ThreadProc(CoreWebView2CreationProperties creationProperties)
{
try
{
var creationProps = new CoreWebView2CreationProperties();
// The CoreWebView2CreationProperties object cannot be assigned directly, because its member _task will also be assigned.
creationProps.BrowserExecutableFolder = creationProperties.BrowserExecutableFolder;
creationProps.UserDataFolder = creationProperties.UserDataFolder;
creationProps.Language = creationProperties.Language;
creationProps.AdditionalBrowserArguments = creationProperties.AdditionalBrowserArguments;
creationProps.ProfileName = creationProperties.ProfileName;
creationProps.IsInPrivateModeEnabled = creationProperties.IsInPrivateModeEnabled;
var tempForm = new BrowserForm(creationProps);
tempForm.Show();
// Run the message pump
Application.Run();
}
catch (Exception exception)
{
MessageBox.Show("Create New Thread Failed: " + exception.Message, "Create New Thread");
}
}
private void createNewThreadToolStripMenuItem_Click(object sender, EventArgs e)
{
Thread newFormThread = new Thread(() =>
{
ThreadProc(webView2Control.CreationProperties);
});
newFormThread.SetApartmentState(ApartmentState.STA);
newFormThread.IsBackground = false;
newFormThread.Start();
}
private void xToolStripMenuItem05_Click(object sender, EventArgs e)
{
this.webView2Control.ZoomFactor = 0.5;
}
private void xToolStripMenuItem1_Click(object sender, EventArgs e)
{
this.webView2Control.ZoomFactor = 1.0;
}
private void xToolStripMenuItem2_Click(object sender, EventArgs e)
{
this.webView2Control.ZoomFactor = 2.0;
}
private void xToolStripMenuItem3_Click(object sender, EventArgs e)
{
MessageBox.Show($"Zoom factor: {this.webView2Control.ZoomFactor}", "WebView Zoom factor");
}
private void backgroundColorMenuItem_Click(object sender, EventArgs e)
{
var menuItem = (ToolStripMenuItem)sender;
Color backgroundColor = Color.FromName(menuItem.Text);
this.webView2Control.DefaultBackgroundColor = backgroundColor;
}
private void taskManagerToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
this.webView2Control.CoreWebView2.OpenTaskManagerWindow();
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "Open Task Manager Window failed");
}
}
private async void methodCDPToolStripMenuItem_Click(object sender, EventArgs e)
{
TextInputDialog dialog = new TextInputDialog(
title: "Call CDP Method",
description: "Enter the CDP method name to call, followed by a space,\r\n" +
"followed by the parameters in JSON format.",
defaultInput: "Runtime.evaluate {\"expression\":\"alert(\\\"test\\\")\"}"
);
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] words = dialog.inputBox().Trim().Split(' ');
if (words.Length == 1 && words[0] == "")
{
MessageBox.Show(this, "Invalid argument:" + dialog.inputBox(), "CDP Method call failed");
return;
}
string methodName = words[0];
string methodParams = (words.Length == 2 ? words[1] : "{}");
try
{
string cdpResult = await this.webView2Control.CoreWebView2.CallDevToolsProtocolMethodAsync(methodName, methodParams);
MessageBox.Show(this, cdpResult, "CDP method call successfully");
}
catch (Exception ex)
{
MessageBox.Show(this, ex.ToString(), "CDP method call failed");
}
}
}
private void allowExternalDropMenuItem_Click(object sender, EventArgs e)
{
this.webView2Control.AllowExternalDrop = this.allowExternalDropMenuItem.Checked;
}
private void setUsersAgentMenuItem_Click(object sender, EventArgs e)
{
var dialog = new TextInputDialog(
title: "SetUserAgent",
description: "Enter UserAgent");
if (dialog.ShowDialog() == DialogResult.OK)
{
// <SetUserAgent>
WebViewSettings.UserAgent = dialog.inputBox();
// </SetUserAgent>
}
}
private void getDocumentTitleMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(webView2Control.CoreWebView2.DocumentTitle, "Document Title");
}
private bool _isPrintToPdfInProgress = false;
private async void portraitMenuItem_Click(object sender, EventArgs e)
{
if (_isPrintToPdfInProgress)
{
MessageBox.Show(this, "Print to PDF in progress", "Print To PDF");
return;
}
try
{
// <PrintToPdf as Portrait>
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = "C:\\";
saveFileDialog.Filter = "Pdf Files|*.pdf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
_isPrintToPdfInProgress = true;
bool isSuccessful = await webView2Control.CoreWebView2.PrintToPdfAsync(
saveFileDialog.FileName);
_isPrintToPdfInProgress = false;
string message = (isSuccessful) ?
"Print to PDF succeeded" : "Print to PDF failed";
MessageBox.Show(this, message, "Print To PDF Completed");
}
// </PrintToPdf as Portrait>
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Print to PDF Failed: " + exception.Message,
"Print to PDF");
}
}
private async void landscapeMenuItem_Click(object sender, EventArgs e)
{
{
if (_isPrintToPdfInProgress)
{
MessageBox.Show(this, "Print to PDF in progress", "Print To PDF");
return;
}
try
{
// <PrintToPdf as landscape>
CoreWebView2PrintSettings printSettings = WebViewEnvironment.CreatePrintSettings();
printSettings.Orientation = CoreWebView2PrintOrientation.Landscape;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.InitialDirectory = "C:\\";
saveFileDialog.Filter = "Pdf Files|*.pdf";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
_isPrintToPdfInProgress = true;
bool isSuccessful = await webView2Control.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 as landscape>
}
catch (NotImplementedException exception)
{
MessageBox.Show(this, "Print to PDF Failed: " + exception.Message,
"Print to PDF");
}
}
}
private void exitMenuItem_Click(object sender, EventArgs e)
{
if (_isPrintToPdfInProgress)
{
var selection = MessageBox.Show(
"Print to PDF in progress. Continue closing?",
"Print to PDF", MessageBoxButtons.YesNo);
if (selection == DialogResult.No)
{
return;
}
}
this.Close();
}
private void getUserDataFolderMenuItem_Click(object sender, EventArgs e)
{
try
{
MessageBox.Show(WebViewEnvironment.UserDataFolder, "User Data Folder");
}
catch (Exception exception)
{
MessageBox.Show(this, "Get User Data Folder Failed: " + exception.Message, "User Data Folder");
}
}
private void toggleVisibilityMenuItem_Click(object sender, EventArgs e)
{
this.webView2Control.Visible = this.toggleVisibilityMenuItem.Checked;
}
private void toggleCustomServerCertificateSupportMenuItem_Click(object sender, EventArgs e)
{
ToggleCustomServerCertificateSupport();
}
private void clearServerCertificateErrorActionsMenuItem_Click(object sender, EventArgs e)
{
ClearServerCertificateErrorActions();
}
private void toggleDefaultScriptDialogsMenuItem_Click(object sender, EventArgs e)
{
WebViewSettings.AreDefaultScriptDialogsEnabled = !WebViewSettings.AreDefaultScriptDialogsEnabled;
MessageBox.Show("Default script dialogs will be " + (WebViewSettings.AreDefaultScriptDialogsEnabled ? "enabled" : "disabled"), "after the next navigation.");
}
private void addRemoteObjectMenuItem_Click(object sender, EventArgs e)
{
try
{
this.webView2Control.CoreWebView2.AddHostObjectToScript("bridge", new BridgeAddRemoteObject());
}
catch (NotSupportedException exception)
{
MessageBox.Show("CoreWebView2.AddRemoteObject failed: " + exception.Message);
}
this.webView2Control.CoreWebView2.FrameCreated += (s, args) =>
{
if (args.Frame.Name.Equals("iframe_name"))
{
try
{
string[] origins = new string[] { "https://appassets.example" };
args.Frame.AddHostObjectToScript("bridge", new BridgeAddRemoteObject(), origins);
}
catch (NotSupportedException exception)
{
MessageBox.Show("Frame.AddHostObjectToScript failed: " + exception.Message);
}
}
args.Frame.NameChanged += (nameChangedSender, nameChangedArgs) =>
{
CoreWebView2Frame frame = (CoreWebView2Frame)nameChangedSender;
MessageBox.Show("Frame.NameChanged: " + frame.Name);
};
args.Frame.Destroyed += (frameDestroyedSender, frameDestroyedArgs) =>
{
// Handle frame destroyed
};
};
this.webView2Control.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
this.webView2Control.Source = new Uri("https://appassets.example/hostObject.html");
}
// <DOMContentLoaded>
private void domContentLoadedMenuItem_Click(object sender, EventArgs e)
{
this.webView2Control.CoreWebView2.DOMContentLoaded += WebView_DOMContentLoaded;
this.webView2Control.CoreWebView2.FrameCreated += WebView_FrameCreatedDOMContentLoaded;
this.webView2Control.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%;'/>");
this.webView2Control.CoreWebView2.NavigationCompleted += (s, args) =>
{
this.webView2Control.CoreWebView2.DOMContentLoaded -= WebView_DOMContentLoaded;
this.webView2Control.CoreWebView2.FrameCreated -= WebView_FrameCreatedDOMContentLoaded;
};
}
void WebView_DOMContentLoaded(object sender, CoreWebView2DOMContentLoadedEventArgs arg)
{
_ = this.webView2Control.ExecuteScriptAsync(
"let content = document.createElement(\"h2\");" +
"content.style.color = 'blue';" +
"content.textContent = \"This text was added by the host app\";" +
"document.body.appendChild(content);");
}
void WebView_FrameCreatedDOMContentLoaded(object sender, CoreWebView2FrameCreatedEventArgs 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);");
};
}
// </DOMContentLoaded>
private void navigateWithWebResourceRequestMenuItem_Click(object sender, EventArgs e)
{
// <NavigateWithWebResourceRequest>
// 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() == DialogResult.OK)
{
string postDataString = "input=" + dialog.inputBox();
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");
this.webView2Control.CoreWebView2.NavigateWithWebResourceRequest(webResourceRequest);
}
// </NavigateWithWebResourceRequest>
}
// <WebMessage>
private void webMessageMenuItem_Click(object sender, EventArgs e)
{
this.webView2Control.CoreWebView2.WebMessageReceived += WebView_WebMessageReceived;
this.webView2Control.CoreWebView2.FrameCreated += WebView_FrameCreatedWebMessages;
this.webView2Control.CoreWebView2.SetVirtualHostNameToFolderMapping(
"appassets.example", "assets", CoreWebView2HostResourceAccessKind.DenyCors);
this.webView2Control.Source = new Uri("https://appassets.example/webMessages.html");
}
void HandleWebMessage(CoreWebView2WebMessageReceivedEventArgs args, CoreWebView2Frame frame = null)
{
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.Text = message.Substring(msgLength);
}
else if (message == "GetWindowBounds")
{
string reply = "{\"WindowBounds\":\"Left:" + 0 +
"\\nTop:" + 0 +
"\\nRight:" + this.webView2Control.Width +
"\\nBottom:" + this.webView2Control.Height +
"\"}";
if (frame != null)
{
frame.PostWebMessageAsJson(reply);
}
else
{
this.webView2Control.CoreWebView2.PostWebMessageAsJson(reply);
}
}
else
{
// Ignore unrecognized messages, but log them
// since it suggests a mismatch between the web content and the host.
Debug.WriteLine($"Unexpected message received: {message}");
}
}
catch (Exception e)
{
MessageBox.Show($"Unexpected message received: {e.Message}");
}
}
void WebView_WebMessageReceived(object sender, CoreWebView2WebMessageReceivedEventArgs args)
{
HandleWebMessage(args);
}
// <WebMessageReceivedIFrame>
void WebView_FrameCreatedWebMessages(object sender, CoreWebView2FrameCreatedEventArgs args)
{
args.Frame.WebMessageReceived += (WebMessageReceivedSender, WebMessageReceivedArgs) =>
{
HandleWebMessage(WebMessageReceivedArgs, args.Frame);
};
}
// </WebMessageReceivedIFrame>
// </WebMessage>
private void toggleMuteStateMenuItem_Click(object sender, EventArgs e)
{
this.webView2Control.CoreWebView2.IsMuted = !this.webView2Control.CoreWebView2.IsMuted;
MessageBox.Show("Mute state will be " + (this.webView2Control.CoreWebView2.IsMuted ? "enabled" : "disabled"), "Mute");
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show(this, "WebView2WindowsFormsBrowser, Version 1.0\nCopyright(C) 2023", "About WebView2WindowsFormsBrowser");
}
void AuthenticationMenuItem_Click(object sender, EventArgs e)
{
// <BasicAuthenticationRequested>
this.webView2Control.CoreWebView2.BasicAuthenticationRequested += delegate (object requestSender, CoreWebView2BasicAuthenticationRequestedEventArgs args)
{
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo credentials in https://authenticationtest.com")]
args.Response.UserName = "user";
// [SuppressMessage("Microsoft.Security", "CS002:SecretInNextLine", Justification="Demo credentials in https://authenticationtest.com")]
args.Response.Password = "pass";
};
this.webView2Control.CoreWebView2.Navigate("https://authenticationtest.com/HTTPAuth");
// </BasicAuthenticationRequested>
}
async void ClearBrowsingData(object target, EventArgs e, CoreWebView2BrowsingDataKinds dataKinds)
{
// Clear the browsing data from the last hour.
await this.webView2Control.CoreWebView2.Profile.ClearBrowsingDataAsync(dataKinds);
MessageBox.Show(this,
"Completed",
"Clear Browsing Data");
// </ClearBrowsingData>
}
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();
}
e.Handled = true;
}
private bool _isCustomClientCertificateSelection = false;
void CustomClientCertificateSelectionMenuItem_Click(object sender, EventArgs e)
{
// Safeguarding the handler when unsupported runtime is used.
try
{
if (!_isCustomClientCertificateSelection)
{
this.webView2Control.CoreWebView2.ClientCertificateRequested += WebView_ClientCertificateRequested;
}
else
{
this.webView2Control.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");
}
}
// <ClientCertificateRequested2>
// 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 DeferredCustomCertificateDialogMenuItem_Click(object sender, EventArgs e)
{
// Safeguarding the handler when unsupported runtime is used.
try
{
if (!_isCustomClientCertificateSelectionDialog)
{
this.webView2Control.CoreWebView2.ClientCertificateRequested += delegate (
object requestSender, 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() == DialogResult.OK)
{
// Continue with the selected certificate to respond to the server if `OK` is selected.
args.SelectedCertificate = (CoreWebView2ClientCertificate)dialog.CertificateDataBinding.SelectedItems[0].Tag;
}
}
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");
}
}
async void GetCookiesMenuItem_Click(object sender, EventArgs e, string address)
{
// <GetCookies>
List<CoreWebView2Cookie> cookieList = await this.webView2Control.CoreWebView2.CookieManager.GetCookiesAsync(address);
StringBuilder cookieResult = new StringBuilder(cookieList.Count + " cookie(s) received from " + address);
for (int i = 0; i < cookieList.Count; ++i)
{
CoreWebView2Cookie cookie = this.webView2Control.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 AddOrUpdateCookieMenuItem_Click(object sender, EventArgs e, string domain)
{
// <AddOrUpdateCookie>
CoreWebView2Cookie cookie = this.webView2Control.CoreWebView2.CookieManager.CreateCookie("CookieName", "CookieValue", domain, "/");
this.webView2Control.CoreWebView2.CookieManager.AddOrUpdateCookie(cookie);
// </AddOrUpdateCookie>
}
void DeleteAllCookiesMenuItem_Click(object sender, EventArgs e)
{
this.webView2Control.CoreWebView2.CookieManager.DeleteAllCookies();
}
void DeleteCookiesMenuItem_Click(object sender, EventArgs e, string domain)
{
this.webView2Control.CoreWebView2.CookieManager.DeleteCookiesWithDomainAndPath("CookieName", domain, "/");
}
private void showBrowserProcessInfoMenuItem_Click(object sender, EventArgs e)
{
var browserInfo = this.webView2Control.CoreWebView2.BrowserProcessId;
MessageBox.Show(this, "Browser ID: " + browserInfo.ToString(), "Process ID");
}
private void showPerformanceInfoMenuItem_Click(object sender, EventArgs e)
{
var processInfoList = WebViewEnvironment.GetProcessInfos();
var processListCount = processInfoList.Count;
string message = "";
if (processListCount == 0)
{
message = "No process found.";
}
else
{
message = $"{processListCount} processes found:\n\n";
for (int i = 0; i < processListCount; ++i)
{
int processId = processInfoList[i].ProcessId;
CoreWebView2ProcessKind processKind = processInfoList[i].Kind;
var proc = Process.GetProcessById(processId);
var memoryInBytes = proc.PrivateMemorySize64;
var b2kb = memoryInBytes / 1024;
message += $"Process ID: {processId}, Process Kind: {processKind}, Memory Usage: {b2kb} KB\n";
}
}
MessageBox.Show(this, message, "Process Info");
}
// <ProcessFailed>
// Register a handler for the ProcessFailed event.
// This handler checks the failure kind and tries to:
// * Recreate the webview for browser failure and render unresponsive.
// * Reload the webview for render failure.
// * Reload the webview for frame-only render failure impacting app content.
// * Log information about the failure for other failures.
private void CoreWebView2_ProcessFailed(object sender, CoreWebView2ProcessFailedEventArgs e)
{
void ReinitIfSelectedByUser(string caption, string message)
{
this.webView2Control.BeginInvoke(new Action(() =>
{
var selection = MessageBox.Show(this, message, caption, MessageBoxButtons.YesNo);
if (selection == DialogResult.Yes)
{
this.Controls.Remove(this.webView2Control);
this.webView2Control.Dispose();
this.webView2Control = GetReplacementControl(false);
// Set background transparent
this.webView2Control.DefaultBackgroundColor = System.Drawing.Color.Transparent;
this.Controls.Add(this.webView2Control);
HandleResize();
}
}));
}
void ReloadIfSelectedByUser(string caption, string message)
{
this.webView2Control.BeginInvoke(new Action(() =>
{
var selection = MessageBox.Show(this, message, caption, MessageBoxButtons.YesNo);
if (selection == DialogResult.Yes)
{
this.webView2Control.CoreWebView2.Reload();
}
}));
}
this.webView2Control.Invoke(new Action(() =>
{
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", MessageBoxButtons.OK);
}));
if (e.ProcessFailedKind == CoreWebView2ProcessFailedKind.BrowserProcessExited)
{