-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
346 lines (299 loc) · 13.9 KB
/
MainWindow.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
using Microsoft.Web.WebView2.Core;
using Microsoft.Web.WebView2.Wpf;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.Tracing;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
namespace CdpVsNewWindow
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
private readonly ObservableCollection<string> log = new();
private readonly CoreWebView2CreationProperties webView2CreationProperties;
private bool enableLog = true;
private int newWindowTop;
private int newWindowLeft;
public event PropertyChangedEventHandler? PropertyChanged;
Dictionary<CoreWebView2DevToolsProtocolEventReceiver, WebView2> cdpEventReceiverToWebView = new();
public MainWindow()
{
InitializeComponent();
this.Top = 0;
this.Left = 1100;
this.webView2CreationProperties = new CoreWebView2CreationProperties();
var executablePath = GetCanaryWebViewPathIfAvailable();
if (executablePath != null)
{
this.webView2CreationProperties.BrowserExecutableFolder = executablePath;
}
_ = InitializeAsync();
}
private string? GetCanaryWebViewPathIfAvailable() =>
Directory
.EnumerateDirectories(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), @"Microsoft\Edge SxS\Application"), "*", SearchOption.TopDirectoryOnly)
.Where(path => Version.TryParse(Path.GetFileName(path), out _))
.FirstOrDefault();
public ObservableCollection<string> Log => this.log;
private async Task InitializeAsync()
{
this.WebView.CreationProperties = this.webView2CreationProperties;
await this.WebView.EnsureCoreWebView2Async();
await this.WebView.CoreWebView2.Profile.ClearBrowsingDataAsync();
this.WebView.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
this.WebView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
this.WebView.NavigateToString(HTML.OpenWindow);
LogEvent($"Using WebView2 version {this.WebView.CoreWebView2.Environment.BrowserVersionString}");
}
private void LogEvent(string @event)
{
if (this.enableLog)
{
this.log.Add($"[{DateTime.Now.ToString("hh:mm:ss.ffff")}] {@event}");
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Log)));
}
}
private void CoreWebView2_NavigationStarting(object? sender, CoreWebView2NavigationStartingEventArgs e)
{
if (sender is CoreWebView2 webView)
{
LogEvent($"NavigationStarting - '{webView.Source}'");
}
}
private void CoreWebView2_ContentLoading(object? sender, CoreWebView2ContentLoadingEventArgs e)
{
if (sender is CoreWebView2 webView)
{
LogEvent($"ContentLoading - '{webView.Source}'");
}
}
private void CoreWebView2_NavigationCompleted(object? sender, CoreWebView2NavigationCompletedEventArgs e)
{
if (sender is CoreWebView2 webView)
{
LogEvent($"NavigationCompleted - '{webView.Source}'");
}
}
private void CoreWebView2_WebResourceRequested(object? sender, CoreWebView2WebResourceRequestedEventArgs e)
{
if (sender is CoreWebView2 webView)
{
if (e.Request.Uri.ToString().Contains(".png") && !e.Request.Uri.ToString().Contains("show"))
{
e.Response = webView.Environment.CreateWebResourceResponse(null, 404, "not found", string.Empty);
}
}
}
private void CoreWebView2_NewWindowRequested(object? sender, Microsoft.Web.WebView2.Core.CoreWebView2NewWindowRequestedEventArgs e)
{
var _deferral = e.GetDeferral();
_ = Dispatcher.InvokeAsync(() => OpenNewWindowAsync(e, _deferral));
}
private async void CoreWebView2_DevToolsRequestPaused(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs e)
{
if (sender is CoreWebView2DevToolsProtocolEventReceiver receiver)
{
if (TryDeserializeJson(e.ParameterObjectAsJson, out RequestPausedEventArgs request))
{
try
{
var webView = cdpEventReceiverToWebView[receiver];
if (request.Request.Url.ToString().Contains(".png") && !request.Request.Url.ToString().Contains("show"))
{
var param = $"{{\"requestId\":\"{request.RequestId}\", \"errorReason\":\"BlockedByClient\"}}";
if (string.IsNullOrEmpty(e.SessionId))
{
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.failRequest", param);
}
else
{
await webView.CoreWebView2.CallDevToolsProtocolMethodForSessionAsync(e.SessionId, "Fetch.failRequest", param);
}
}
else
{
var param = $"{{\"requestId\":\"{request.RequestId}\"}}";
if (string.IsNullOrEmpty(e.SessionId))
{
await webView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.continueRequest", param);
}
else
{
await webView.CoreWebView2.CallDevToolsProtocolMethodForSessionAsync(e.SessionId, "Fetch.continueRequest", param);
}
}
}
catch
{ }
}
else
{
throw new InvalidOperationException();
}
}
}
private async void CoreWebView2_DevToolsAttachedToTarget(object? sender, CoreWebView2DevToolsProtocolEventReceivedEventArgs e)
{
if (sender is CoreWebView2DevToolsProtocolEventReceiver receiver)
{
if (TryDeserializeJson(e.ParameterObjectAsJson, out AutoAttachedSession session))
{
var sessionId = session.SessionId;
if (string.IsNullOrEmpty(e.SessionId))
{
var webView = cdpEventReceiverToWebView[receiver];
await webView.CoreWebView2.CallDevToolsProtocolMethodForSessionAsync(sessionId, "Fetch.enable", "{\"patterns\":[{\"requestStage\":\"Request\"}]}");
// Try to resume the target. This can fail if the target was destroyed before we manage to resume it with "runIfWaitingForDebugger"
try
{
await webView.CoreWebView2.CallDevToolsProtocolMethodForSessionAsync(sessionId, "Runtime.runIfWaitingForDebugger", "{}");
}
catch
{
}
}
}
else
{
throw new InvalidOperationException();
}
}
}
public static bool TryDeserializeJson<T>(string json, out T deserializedObject)
{
deserializedObject = default;
if (string.IsNullOrWhiteSpace(json))
{
return false;
}
try
{
var options = new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true,
};
deserializedObject = JsonSerializer.Deserialize<T>(json, options);
return true;
}
catch (JsonException)
{
return false;
}
}
private async Task OpenNewWindowAsync(CoreWebView2NewWindowRequestedEventArgs e, CoreWebView2Deferral deferral)
{
this.newWindowLeft += 20;
this.newWindowTop += 20;
Window window = new Window
{
Width = Width,
Height = Height,
Left = this.newWindowLeft,
Top = this.newWindowTop
};
var newWebView = new WebView2();
newWebView.CreationProperties = this.webView2CreationProperties;
window.Owner = this;
window.Content = newWebView;
window.Show();
await newWebView.EnsureCoreWebView2Async();
LogEvent($"Creating new WebView2 version {newWebView.CoreWebView2.Environment.BrowserVersionString}");
newWebView.CoreWebView2.AddWebResourceRequestedFilter("*", CoreWebView2WebResourceContext.All);
newWebView.CoreWebView2.NewWindowRequested += CoreWebView2_NewWindowRequested;
newWebView.CoreWebView2.NavigationStarting += CoreWebView2_NavigationStarting;
newWebView.CoreWebView2.NavigationCompleted += CoreWebView2_NavigationCompleted;
newWebView.CoreWebView2.ContentLoading += CoreWebView2_ContentLoading;
var fetchReceiver = newWebView.CoreWebView2.GetDevToolsProtocolEventReceiver("Fetch.requestPaused");
cdpEventReceiverToWebView[fetchReceiver] = newWebView;
fetchReceiver.DevToolsProtocolEventReceived += CoreWebView2_DevToolsRequestPaused;
var attachedToTargetReceiver = newWebView.CoreWebView2.GetDevToolsProtocolEventReceiver("Target.attachedToTarget");
cdpEventReceiverToWebView[attachedToTargetReceiver] = newWebView;
attachedToTargetReceiver.DevToolsProtocolEventReceived += CoreWebView2_DevToolsAttachedToTarget;
if (this.Timing.SelectedIndex == 0)
{
if (this.HandlerType.SelectedIndex == 0)
{
LogEvent($"Assigning WebResourceRequested");
newWebView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
LogEvent($"Assigned WebResourceRequested");
}
else
{
LogEvent($"Calling Fetch.enable");
await newWebView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.enable", "{\"patterns\":[{\"requestStage\":\"Request\"}]}");
LogEvent($"Called Fetch.enable");
LogEvent($"Calling Target.setAutoAttach");
await newWebView.CoreWebView2.CallDevToolsProtocolMethodAsync("Target.setAutoAttach", "{\"autoAttach\":true,\"waitForDebuggerOnStart\":true,\"flatten\":true}");
LogEvent($"Called Target.setAutoAttach");
}
}
LogEvent($"Assigning NewWindow");
e.NewWindow = newWebView.CoreWebView2;
LogEvent($"Assigned NewWindow");
if (this.Timing.SelectedIndex == 1)
{
if (this.Delay.SelectedIndex > 0)
{
string value = ((ComboBoxItem)this.Delay.SelectedItem).Content.ToString();
await Task.Delay(TimeSpan.FromMilliseconds(int.Parse(value)));
}
if (this.HandlerType.SelectedIndex == 0)
{
LogEvent($"Assigning WebResourceRequested");
newWebView.CoreWebView2.WebResourceRequested += CoreWebView2_WebResourceRequested;
LogEvent($"Assigned WebResourceRequested");
}
else
{
LogEvent($"Calling Fetch.enable");
await newWebView.CoreWebView2.CallDevToolsProtocolMethodAsync("Fetch.enable", "{\"patterns\":[{\"requestStage\":\"Request\"}]}");
LogEvent($"Called Fetch.enable");
LogEvent($"Calling Target.setAutoAttach");
await newWebView.CoreWebView2.CallDevToolsProtocolMethodAsync("Target.setAutoAttach", "{\"autoAttach\":true,\"waitForDebuggerOnStart\":true,\"flatten\":true}");
LogEvent($"Called Target.setAutoAttach");
}
}
e.Handled = true;
deferral.Complete();
}
private void CopyLog_Click(object sender, RoutedEventArgs e)
{
var builder = new StringBuilder();
foreach (var @event in this.log)
{
builder.AppendLine(@event);
}
Clipboard.SetText(builder.ToString());
}
private void ClearLog_Click(object sender, RoutedEventArgs e)
{
this.log.Clear();
}
private void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
{
if (e.Key == System.Windows.Input.Key.Enter && sender is TextBox textBox &&
(Uri.TryCreate(textBox.Text, UriKind.Absolute, out var uri) || Uri.TryCreate($"https://{textBox.Text}", UriKind.Absolute, out uri)))
{
this.WebView.CoreWebView2.Navigate(uri.AbsoluteUri);
}
}
private void OpenDefaultHomepage(object sender, RoutedEventArgs e)
{
this.WebView.NavigateToString(HTML.OpenWindow);
}
}
}