forked from MicrosoftEdge/WebView2Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MainWindow.xaml.cs
392 lines (347 loc) · 15.8 KB
/
MainWindow.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
// 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 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 AddOrUpdateCookieCommand = new RoutedCommand();
public static RoutedCommand DeleteCookiesCommand = new RoutedCommand();
public static RoutedCommand DeleteAllCookiesCommand = new RoutedCommand();
public static RoutedCommand SetUserAgentCommand = new RoutedCommand();
bool _isNavigating = false;
public MainWindow()
{
InitializeComponent();
}
void NewCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
new MainWindow().Show();
}
void CloseCmdExecuted(object sender, ExecutedRoutedEventArgs e)
{
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 = webView != null && webView.CoreWebView2 != null && !_isNavigating;
}
void RefreshCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
webView.Reload();
}
void BrowseStopCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = webView != null && webView.CoreWebView2 != null && _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 = webView != null && webView.CoreWebView2 != null;
}
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 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", "/");
}
private CoreWebView2Settings _coreWebView2Settings;
void SetUserAgentCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
if (_coreWebView2Settings == null)
{
_coreWebView2Settings = webView.CoreWebView2.Settings;
}
var dialog = new TextInputDialog(
title: "SetUserAgent",
description: "Enter UserAgent");
if (dialog.ShowDialog() == true)
{
_coreWebView2Settings.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.NavigateToString(@"<!DOCTYPE html><h1>DOMContentLoaded sample page</h1><h2>The content below will be added after DOM content is loaded </h2>");
}
private CoreWebView2Environment _coreWebView2Environment;
async void NavigateWithWebResourceRequestCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// Need CoreWebView2Environment
if (_coreWebView2Environment == null)
{
_coreWebView2Environment = webView.CoreWebView2.Environment;
}
// 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 =
_coreWebView2Environment.CreateWebResourceRequest(
"https://www.w3schools.com/action_page.php",
"POST",
postDataStream,
"Content-Type: application/x-www-form-urlencoded\r\n");
webView.CoreWebView2.NavigateWithWebResourceRequest(webResourceRequest);
}
}
void GoToPageCmdCanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = webView != null && !_isNavigating;
}
async void GoToPageCmdExecuted(object target, ExecutedRoutedEventArgs e)
{
// 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.
await webView.EnsureCoreWebView2Async();
webView.CoreWebView2.Navigate((string)e.Parameter);
}
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");
}
}
void WebView_NavigationStarting(object sender, CoreWebView2NavigationStartingEventArgs e)
{
_isNavigating = true;
RequeryCommands();
}
void WebView_NavigationCompleted(object sender, CoreWebView2NavigationCompletedEventArgs e)
{
_isNavigating = false;
RequeryCommands();
}
private static void OnShowNextWebResponseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
MainWindow window = (MainWindow)d;
if ((bool)e.NewValue)
{
window.webView.CoreWebView2.WebResourceResponseReceived += window.CoreWebView2_WebResourceResponseReceived;
}
else
{
window.webView.CoreWebView2.WebResourceResponseReceived -= window.CoreWebView2_WebResourceResponseReceived;
}
}
public static readonly DependencyProperty ShowNextWebResponseProperty = DependencyProperty.Register(
nameof(ShowNextWebResponse),
typeof(Boolean),
typeof(MainWindow),
new PropertyMetadata(false, OnShowNextWebResponseChanged));
public bool ShowNextWebResponse
{
get => (bool)this.GetValue(ShowNextWebResponseProperty);
set => this.SetValue(ShowNextWebResponseProperty, value);
}
async void CoreWebView2_WebResourceResponseReceived(object sender, CoreWebView2WebResourceResponseReceivedEventArgs e)
{
ShowNextWebResponse = false;
CoreWebView2WebResourceRequest request = e.Request;
CoreWebView2WebResourceResponseView response = e.Response;
string caption = "Web Resource Response Received";
// Start with capacity 64 for minimum message size
StringBuilder messageBuilder = new StringBuilder(64);
string HttpMessageContentToString(System.IO.Stream content) => content == null ? "[null]" : "[data]";
void AppendHeaders(IEnumerable headers)
{
foreach (var header in headers)
{
messageBuilder.AppendLine($" {header}");
}
}
// Request
messageBuilder.AppendLine("Request");
messageBuilder.AppendLine($"URI: {request.Uri}");
messageBuilder.AppendLine($"Method: {request.Method}");
messageBuilder.AppendLine("Headers:");
AppendHeaders(request.Headers);
messageBuilder.AppendLine($"Content: {HttpMessageContentToString(request.Content)}");
messageBuilder.AppendLine();
// Response
messageBuilder.AppendLine("Response");
messageBuilder.AppendLine($"Status: {response.StatusCode}");
messageBuilder.AppendLine($"Reason: {response.ReasonPhrase}");
messageBuilder.AppendLine("Headers:");
AppendHeaders(response.Headers);
try
{
Stream content = await response.GetContentAsync();
messageBuilder.AppendLine($"Content: {HttpMessageContentToString(content)}");
}
catch (System.Runtime.InteropServices.COMException)
{
messageBuilder.AppendLine($"Content: [failed to load]");
}
MessageBox.Show(messageBuilder.ToString(), caption);
}
void RequeryCommands()
{
// Seems like there should be a way to bind CanExecute directly to a bool property
// so that the binding can take care keeping CanExecute up-to-date when the property's
// value changes, but apparently there isn't. Instead we listen for the WebView events
// which signal that one of the underlying bool properties might have changed and
// bluntly tell all commands to re-check their CanExecute status.
//
// Another way to trigger this re-check would be to create our own bool dependency
// properties on this class, bind them to the underlying properties, and implement a
// PropertyChangedCallback on them. That arguably more directly binds the status of
// the commands to the WebView's state, but at the cost of having an extraneous
// dependency property sitting around for each underlying property, which doesn't seem
// worth it, especially given that the WebView API explicitly documents which events
// signal the property value changes.
CommandManager.InvalidateRequerySuggested();
}
}
}