-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathWebView2Browser.cs
More file actions
744 lines (637 loc) · 27.1 KB
/
WebView2Browser.cs
File metadata and controls
744 lines (637 loc) · 27.1 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
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using MtrDev.WebView2.Wrapper;
using MtrDev.WebView2.Winforms;
namespace MtrDev.WebView2.WinForms.Demo
{
public partial class WebView2Browser : Form
{
public WebView2Browser()
{
InitializeComponent();
Load += WebView2Browser_Load;
}
const int DEFAULT_DPI = 96;
const int INVALID_TAB_ID = 0;
const int UIBarHeight = 70;
const int OptionsDropdownHeight = 108;
const int OptionsDropdownWidth = 200;
private WebView2Control _optionsWebView;
private int _activeTabId;
private IDictionary<int, Tab> _tabDictionary = new Dictionary<int, Tab>();
private void WebView2Browser_Load(object sender, EventArgs e)
{
}
private void _optionsWebView_LostFocus(object sender, EventArgs e)
{
JObject jObject = new JObject();
jObject.Add("message", JToken.FromObject(Messages.MG_OPTIONS_LOST_FOCUS));
jObject.Add("args", JToken.FromObject("{}"));
string json = jObject.ToString();
controlsWebView2.PostWebMessageAsJson(json);
}
private void _optionsWebView_WebMessageRecieved(object sender, WebMessageReceivedEventArgs e)
{
OnWebMessageRecieved(e);
}
private void _optionsWebView_ZoomFactorChanged(object sender, ZoomFactorCompletedEventArgs e)
{
_optionsWebView.ZoomFactor = 1.0;
}
string GetAppDataDirectory(string path)
{
string dataDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
if (!string.IsNullOrEmpty(dataDirectory))
{
dataDirectory = Path.Combine(dataDirectory, "Microsoft");
}
else
{
dataDirectory = ".";
}
dataDirectory = Path.Combine(dataDirectory, path);
return dataDirectory;
}
string GetFullPathFor(string relativePath)
{
var location = new Uri(Assembly.GetEntryAssembly().GetName().CodeBase);
string fulllName = new FileInfo(location.AbsolutePath).Directory.FullName;
return Path.Combine(fulllName, relativePath);
}
string GetFilePathAsURI(string fullPath)
{
Uri uri = new Uri(fullPath);
return uri.AbsoluteUri;
}
public void OnWebMessageRecieved(WebMessageReceivedEventArgs args)
{
string source = args.Source;
string json = args.WebMessageAsJson;
string str = args.WebMessageAsString;
JObject jsonObj = JObject.Parse(json);
if (!jsonObj.ContainsKey("message"))
{
return;
}
if (!jsonObj.ContainsKey("args"))
{
return;
}
Messages m;
if (!Enum.TryParse<Messages>(jsonObj["message"].Value<string>(), out m))
{
return;
}
JToken msgArgs = jsonObj["args"];
switch (m)
{
case Messages.MG_CREATE_TAB:
{
int tabId = msgArgs["tabId"].Value<int>();
bool shouldBeActive = msgArgs["active"].Value<bool>();
Tab newTab = Tab.CreateNewTab(this, _contentEnvironment, tabId, shouldBeActive);
if (!_tabDictionary.ContainsKey(tabId))
{
newTab.Dock = DockStyle.Fill;
tableLayoutPanel1.Controls.Add(newTab, 0, 1);
_tabDictionary.Add(tabId, newTab);
}
}
break;
case Messages.MG_NAVIGATE:
{
string uri = msgArgs["uri"].Value<string>();
string browserScheme = "browser://";
if (uri.Contains(browserScheme))
{
string path = uri.Substring(browserScheme.Length);
if (path == "favorites" ||
path == "settings" ||
path == "history")
{
string filePath = "Content\\content_ui\\";
filePath = Path.Combine(filePath, path);
filePath += ".html";
string fullPath = GetFullPathFor(filePath);
_tabDictionary[_activeTabId].Navigate(fullPath);
}
else
{
System.Diagnostics.Debug.WriteLine("Requested unknown browser page");
}
}
else
{
_tabDictionary[_activeTabId].Navigate(uri);
}
}
break;
case Messages.MG_GO_FORWARD:
{
_tabDictionary[_activeTabId].GoForward();
}
break;
case Messages.MG_GO_BACK:
{
_tabDictionary[_activeTabId].GoBack();
}
break;
case Messages.MG_RELOAD:
{
_tabDictionary[_activeTabId].Reload();
}
break;
case Messages.MG_CANCEL:
{
_tabDictionary[_activeTabId].CallDevToolsProtocolMethod("Page.stopLoading", "{}", null);
}
break;
case Messages.MG_SWITCH_TAB:
{
int tabId = msgArgs["tabId"].Value<int>();
SwitchToTab(tabId);
}
break;
case Messages.MG_CLOSE_TAB:
{
int tabId = msgArgs["tabId"].Value<int>();
tableLayoutPanel1.Controls.Remove(_tabDictionary[tabId]);
_tabDictionary.Remove(tabId);
}
break;
case Messages.MG_CLOSE_WINDOW:
{
Close();
}
break;
case Messages.MG_SHOW_OPTIONS:
{
_optionsWebView.Visible = true;
ResizeUIWebViews();
_optionsWebView.BringToFront();
_optionsWebView.Focus();
}
break;
case Messages.MG_HIDE_OPTIONS:
{
_optionsWebView.Visible = false;
}
break;
case Messages.MG_OPTION_SELECTED:
{
_tabDictionary[_activeTabId].Focus();
}
break;
case Messages.MG_GET_FAVORITES:
case Messages.MG_GET_SETTINGS:
case Messages.MG_GET_HISTORY:
{
// Forward back to requesting tab
JToken tabIdToken = msgArgs["tabId"];
int tabId = tabIdToken.Value<int>();
RemoveFields(msgArgs, new string[] { "tabId" });
PostJsonToWebView(jsonObj, _tabDictionary[tabId]);
}
break;
}
}
private void RemoveFields(JToken token, string[] fields)
{
JContainer container = token as JContainer;
if (container == null) return;
List<JToken> removeList = new List<JToken>();
foreach (JToken el in container.Children())
{
JProperty p = el as JProperty;
if (p != null && fields.Contains(p.Name))
{
removeList.Add(el);
}
RemoveFields(el, fields);
}
foreach (JToken el in removeList)
{
el.Remove();
}
}
private void CreateBrowserOptionsWebView()
{
_optionsWebView = new WebView2Control(_controlEnvironment);
_optionsWebView.Visible = false;
_optionsWebView.AreDevToolsEnabled = false;
_optionsWebView.ZoomFactorChanged += _optionsWebView_ZoomFactorChanged;
_optionsWebView.WebMessageRecieved += _optionsWebView_WebMessageRecieved;
_optionsWebView.LostFocus += _optionsWebView_LostFocus;
_optionsWebView.BrowserCreated += (s, e) => {
ResizeUIWebViews();
};
Controls.Add(_optionsWebView);
string optionsPath = GetFullPathFor("Content\\controls_ui\\options.html");
_optionsWebView.Navigate(optionsPath);
}
private void ResizeUIWebViews()
{
if (_optionsWebView != null)
{
int dpiDropdownWidth = (int)GetDPIAwareBound(OptionsDropdownWidth);
int dpiBarHeight = (int)GetDPIAwareBound(UIBarHeight);
int dpiDropdownHeight = (int)GetDPIAwareBound(OptionsDropdownHeight);
int x = Bounds.Width - dpiDropdownWidth;
Rectangle bounds = new Rectangle(x, dpiBarHeight, dpiDropdownWidth, dpiDropdownHeight);
_optionsWebView.Bounds = bounds;
}
}
private void PostJsonToWebView(JObject jObjectj, WebView2Control webview)
{
string json = jObjectj.ToString();
webview.PostWebMessageAsJson(json);
}
private void PostJsonToWebView(string json, WebView2Control webview)
{
webview.PostWebMessageAsJson(json);
}
private void controlsWebView2_BeforeEnvironmentCreated(object sender, BeforeEnvironmentCreatedEventArgs e)
{
e.UserDataFolder = GetAppDataDirectory("User Data");
}
private void webView2Control2_BeforeEnvironmentCreated(object sender, BeforeEnvironmentCreatedEventArgs e)
{
e.UserDataFolder = GetAppDataDirectory("Browser Data");
}
private void controlsWebView2_BrowserCreated(object sender, EventArgs e)
{
string controlsPath = GetFullPathFor("Content\\controls_ui\\default.html");
controlsWebView2.Navigate(controlsPath);
controlsWebView2.AreDevToolsEnabled = true;
CreateBrowserOptionsWebView();
}
private void controlsWebView2_ZoomFactorChanged(object sender, ZoomFactorCompletedEventArgs e)
{
controlsWebView2.ZoomFactor = 1.0;
}
private void controlsWebView2_WebMessageRecieved(object sender, WebMessageReceivedEventArgs e)
{
OnWebMessageRecieved(e);
}
public void HandleTabCreated(int tabId, bool shouldBeActive)
{
if (shouldBeActive)
{
SwitchToTab(tabId);
}
}
public void HandleTabSecurityUpdate(int tabId, DevToolsProtocolEventReceivedEventArgs eventArgs)
{
JObject paramJson = JObject.Parse(eventArgs.ParameterObjectAsJson);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("message");
writer.WriteValue(Messages.MG_SECURITY_UPDATE);
writer.WritePropertyName("args");
writer.WriteStartObject();
writer.WritePropertyName("tabId");
writer.WriteValue(tabId);
writer.WritePropertyName("state");
writer.WriteValue(paramJson.GetValue("securityState"));
}
string json = sw.ToString();
PostJsonToWebView(json, controlsWebView2);
}
private void SwitchToTab(int tabId)
{
int previousActiveTab = _activeTabId;
if (_tabDictionary.ContainsKey(tabId))
{
_tabDictionary[tabId].Visible = true;
_activeTabId = tabId;
if (previousActiveTab != INVALID_TAB_ID && previousActiveTab != _activeTabId)
{
_tabDictionary[previousActiveTab].Visible = false;
}
}
}
public void HandleTabURIUpdate(int tabId, Tab webview)
{
if (!_tabDictionary.ContainsKey(tabId))
return;
string source = webview.Source;
JObject jObject = new JObject();
jObject.Add("message", JToken.FromObject(Messages.MG_UPDATE_URI));
JObject args = new JObject();
args.Add("tabId", JToken.FromObject(tabId));
args.Add("uri", JToken.FromObject(source));
jObject.Add("args", args);
string uri = source;
string favoritesURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\favorites.html"));
string settingsURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
string historyURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\history.html"));
if (uri == favoritesURI)
{
args.Add("uriToShow", JToken.FromObject("browser://favorites"));
}
else if (uri == settingsURI)
{
args.Add("uriToShow", JToken.FromObject("browser://settings"));
}
else if (uri == historyURI)
{
args.Add("uriToShow", JToken.FromObject("browser://history"));
}
bool canGoForward = webview.CanGoForward;
args.Add("canGoForward", JToken.FromObject(canGoForward));
bool canGoBack = webview.CanGoBack;
args.Add("canGoBack", JToken.FromObject(canGoBack));
PostJsonToWebView(jObject, controlsWebView2);
}
public void HandleTabNavStarting(int tabId, Tab webview)
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("message");
writer.WriteValue(Messages.MG_NAV_STARTING);
writer.WritePropertyName("args");
writer.WriteStartObject();
writer.WritePropertyName("tabId");
writer.WriteValue(tabId);
}
string json = sw.ToString();
PostJsonToWebView(json, controlsWebView2);
}
public void HandleTabNavCompleted(int tabId, Tab webview, bool isSuccess)
{
string getTitleScript =
// Look for a title tag
"(() => {" +
" const titleTag = document.getElementsByTagName('title')[0];" +
" if (titleTag) {" +
" return titleTag.innerHTML;" +
" }" +
// No title tag, look for the file name
" pathname = window.location.pathname;" +
" var filename = pathname.split('/').pop();" +
" if (filename) {" +
" return filename;" +
" }" +
// No file name, look for the hostname
" const hostname = window.location.hostname;" +
" if (hostname) {" +
" return hostname;" +
" }" +
// Fallback: let the UI use a generic title
" return '';" +
"})();";
string getFaviconURI =
"(() => {" +
// Let the UI use a fallback favicon
" let faviconURI = '';" +
" let links = document.getElementsByTagName('link');" +
// Test each link for a favicon
" Array.from(links).map(element => {" +
" let rel = element.rel;" +
// Favicon is declared, try to get the href
" if (rel && (rel == 'shortcut icon' || rel == 'icon')) {" +
" if (!element.href) {" +
" return;" +
" }" +
// href to icon found, check it's full URI
" try {" +
" let urlParser = new URL(element.href);" +
" faviconURI = urlParser.href;" +
" } catch(e) {" +
// Try prepending origin
" let origin = window.location.origin;" +
" let faviconLocation = `${origin}/${element.href}`;" +
" try {" +
" urlParser = new URL(faviconLocation);" +
" faviconURI = urlParser.href;" +
" } catch (e2) {" +
" return;" +
" }" +
" }" +
" }" +
" });" +
" return faviconURI;" +
"})();";
webview.ExecuteScript(getTitleScript, (ExecuteScriptCompletedEventArgs args) =>
{
if (args.ErrorCode != 0)
return;
StringBuilder titleSb = new StringBuilder();
StringWriter titleSw = new StringWriter(titleSb);
using (JsonWriter writer = new JsonTextWriter(titleSw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("message");
writer.WriteValue(Messages.MG_UPDATE_TAB);
writer.WritePropertyName("args");
writer.WriteStartObject();
writer.WritePropertyName("title");
writer.WriteValue(args.ResultAsJson.Trim('"'));
writer.WritePropertyName("tabId");
writer.WriteValue(tabId);
}
string titleJson = titleSb.ToString();
PostJsonToWebView(titleJson, controlsWebView2);
});
webview.ExecuteScript(getFaviconURI, (ExecuteScriptCompletedEventArgs args) =>
{
if (args.ErrorCode != 0)
return;
StringBuilder iconSb = new StringBuilder();
StringWriter iconSw = new StringWriter(iconSb);
using (JsonWriter writer = new JsonTextWriter(iconSw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("message");
writer.WriteValue(Messages.MG_UPDATE_FAVICON);
writer.WritePropertyName("args");
writer.WriteStartObject();
writer.WritePropertyName("uri");
writer.WriteValue(args.ResultAsJson);
writer.WritePropertyName("tabId");
writer.WriteValue(tabId);
}
string iconJson = iconSw.ToString();
PostJsonToWebView(iconJson, controlsWebView2);
});
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
using (JsonWriter writer = new JsonTextWriter(sw))
{
writer.Formatting = Formatting.Indented;
writer.WriteStartObject();
writer.WritePropertyName("message");
writer.WriteValue(Messages.MG_NAV_COMPLETED);
writer.WritePropertyName("args");
writer.WriteStartObject();
writer.WritePropertyName("tabId");
writer.WriteValue(tabId);
writer.WritePropertyName("isError");
writer.WriteValue(!isSuccess);
}
string json = sw.ToString();
PostJsonToWebView(json, controlsWebView2);
}
public void HandleTabMessageReceived(int tabId, Tab webview, WebMessageReceivedEventArgs eventArgs)
{
string jsonString = eventArgs.WebMessageAsJson;
JObject jsonObj = JObject.Parse(jsonString);
string uri = webview.Source;
Messages message;
if (!Enum.TryParse<Messages>(jsonObj["message"].Value<string>(), out message))
{
return;
}
JToken args = jsonObj["args"];
switch (message)
{
case Messages.MG_GET_FAVORITES:
case Messages.MG_REMOVE_FAVORITE:
{
string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\favorites.html"));
// Only the favorites UI can request favorites
if (fileURI == uri)
{
args["tabId"] = tabId;
PostJsonToWebView(jsonObj, controlsWebView2);
}
}
break;
case Messages.MG_GET_SETTINGS:
{
string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
// Only the settings UI can request settings
if (fileURI == uri)
{
args["tabId"] = tabId;
PostJsonToWebView(jsonObj, controlsWebView2);
}
}
break;
case Messages.MG_CLEAR_CACHE:
{
string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
// Only the settings UI can request cache clearing
if (fileURI == uri)
{
args["content"] = false;
args["controls"] = false;
if (ClearContentCache())
{
args["content"] = true;
}
if (ClearControlsCache())
{
args["controls"] = true;
}
PostJsonToWebView(jsonObj, _tabDictionary[tabId]);
}
}
break;
case Messages.MG_CLEAR_COOKIES:
{
string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\settings.html"));
// Only the settings UI can request cookies clearing
if (fileURI == uri)
{
args["content"] = false;
args["controls"] = false;
if (ClearContentCookies())
{
args["content"] = true;
}
if (ClearControlsCookies())
{
args["controls"] = true;
}
PostJsonToWebView(jsonObj, _tabDictionary[tabId]);
}
}
break;
case Messages.MG_GET_HISTORY:
case Messages.MG_REMOVE_HISTORY_ITEM:
case Messages.MG_CLEAR_HISTORY:
{
string fileURI = GetFilePathAsURI(GetFullPathFor("Content\\content_ui\\history.html"));
// Only the history UI can request history
if (fileURI == uri)
{
args["tabId"] = tabId;
PostJsonToWebView(jsonObj, controlsWebView2);
}
}
break;
default:
{
//OutputDebugString(L"Unexpected message\n");
}
break;
}
}
private WebView2Environment _contentEnvironment;
private WebView2Environment _controlEnvironment;
private void webView2Control2_EnvironmentCreated(object sender, EnvironmentCreatedEventArgs e)
{
_contentEnvironment = e.WebViewEnvironment;
}
protected override void OnResize(EventArgs e)
{
ResizeUIWebViews();
base.OnResize(e);
}
private void controlsWebView2_EnvironmentCreated(object sender, EnvironmentCreatedEventArgs e)
{
_controlEnvironment = e.WebViewEnvironment;
}
private bool ClearContentCache()
{
_tabDictionary[_activeTabId].CallDevToolsProtocolMethod("Network.clearBrowserCache", "{}", null);
return true;
}
private bool ClearControlsCache()
{
_tabDictionary[_activeTabId].CallDevToolsProtocolMethod("Network.clearBrowserCache", "{}", null);
return true;
}
private bool ClearContentCookies()
{
_tabDictionary[_activeTabId].CallDevToolsProtocolMethod("Network.clearBrowserCookies", "{}", null);
return true;
}
private bool ClearControlsCookies()
{
controlsWebView2.CallDevToolsProtocolMethod("Network.clearBrowserCookies", "{}", null);
return true;
}
// This method is not available until Windows 8.1
[DllImport("User32.dll", ExactSpelling = true, SetLastError = true)]
static extern uint GetDpiForWindow(IntPtr hWnd);
int GetDPIAwareBound(int bound)
{
// Remove the GetDpiForWindow call when using Windows 7 or any version
// below 1607 (Windows 10). You will also have to make sure the build
// directory is clean before building again.
int dpiForWindow = (int)GetDpiForWindow(Handle);
return (bound * dpiForWindow / DEFAULT_DPI);
}
}
}