forked from MicrosoftEdge/WebView2Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSettingsComponent.cpp
More file actions
598 lines (560 loc) · 22.2 KB
/
SettingsComponent.cpp
File metadata and controls
598 lines (560 loc) · 22.2 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
// 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.
#include "stdafx.h"
#include "SettingsComponent.h"
#include "CheckFailure.h"
#include "TextInputDialog.h"
using namespace Microsoft::WRL;
// Some utility functions
static wil::unique_bstr GetDomainOfUri(PWSTR uri);
static PCWSTR NameOfPermissionType(WEBVIEW2_PERMISSION_TYPE type);
SettingsComponent::SettingsComponent(
AppWindow* appWindow, IWebView2Environment3* environment, SettingsComponent* old)
: m_appWindow(appWindow), m_webViewEnvironment(environment),
m_webView(appWindow->GetWebView())
{
wil::com_ptr<IWebView2Settings> settings;
CHECK_FAILURE(m_webView->get_Settings(&settings));
m_settings = settings.try_query<IWebView2Settings2>();
// Copy old settings if desired
if (old)
{
BOOL setting;
CHECK_FAILURE(old->m_settings->get_IsScriptEnabled(&setting));
CHECK_FAILURE(m_settings->put_IsScriptEnabled(setting));
CHECK_FAILURE(old->m_settings->get_IsWebMessageEnabled(&setting));
CHECK_FAILURE(m_settings->put_IsWebMessageEnabled(setting));
CHECK_FAILURE(old->m_settings->get_AreDefaultScriptDialogsEnabled(&setting));
CHECK_FAILURE(m_settings->put_AreDefaultScriptDialogsEnabled(setting));
CHECK_FAILURE(old->m_settings->get_IsStatusBarEnabled(&setting));
CHECK_FAILURE(m_settings->put_IsStatusBarEnabled(setting));
CHECK_FAILURE(old->m_settings->get_AreDevToolsEnabled(&setting));
CHECK_FAILURE(m_settings->put_AreDevToolsEnabled(setting));
SetBlockImages(old->m_blockImages);
SetUserAgent(old->m_overridingUserAgent);
m_deferScriptDialogs = old->m_deferScriptDialogs;
m_isScriptEnabled = old->m_isScriptEnabled;
m_blockedSitesSet = old->m_blockedSitesSet;
m_blockedSites = std::move(old->m_blockedSites);
m_overridingUserAgent = std::move(old->m_overridingUserAgent);
}
//! [NavigationStarting]
// Register a handler for the NavigationStarting event.
// This handler will check the domain being navigated to, and if the domain
// matches a list of blocked sites, it will cancel the navigation and
// possibly display a warning page. It will also disable JavaScript on
// selected websites.
CHECK_FAILURE(m_webView->add_NavigationStarting(
Callback<IWebView2NavigationStartingEventHandler>(
[this](IWebView2WebView* sender,
IWebView2NavigationStartingEventArgs* args) -> HRESULT
{
wil::unique_cotaskmem_string uri;
CHECK_FAILURE(args->get_Uri(&uri));
if (ShouldBlockUri(uri.get()))
{
CHECK_FAILURE(args->put_Cancel(true));
// If the user clicked a link to navigate, show a warning page.
BOOL userInitiated;
CHECK_FAILURE(args->get_IsUserInitiated(&userInitiated));
if (userInitiated)
{
//! [NavigateToString]
static const PCWSTR htmlContent =
L"<h1>Domain Blocked</h1>"
L"<p>You've attempted to navigate to a domain in the blocked "
L"sites list. Press back to return to the previous page.</p>";
CHECK_FAILURE(sender->NavigateToString(htmlContent));
//! [NavigateToString]
}
}
//! [IsScriptEnabled]
// Changes to settings will apply at the next navigation, which includes the
// navigation after a NavigationStarting event. We can use this to change
// settings according to what site we're visiting.
if (ShouldBlockScriptForUri(uri.get()))
{
m_settings->put_IsScriptEnabled(FALSE);
}
else
{
m_settings->put_IsScriptEnabled(m_isScriptEnabled)
10BC0
;
}
//! [IsScriptEnabled]
return S_OK;
}).Get(), &m_navigationStartingToken));
//! [NavigationStarting]
//! [FrameNavigationStarting]
// Register a handler for the FrameNavigationStarting event.
// This handler will prevent a frame from navigating to a blocked domain.
CHECK_FAILURE(m_webView->add_FrameNavigationStarting(
Callback<IWebView2NavigationStartingEventHandler>(
[this](IWebView2WebView* sender,
IWebView2NavigationStartingEventArgs* args) -> HRESULT
{
wil::unique_cotaskmem_string uri;
CHECK_FAILURE(args->get_Uri(&uri));
if (ShouldBlockUri(uri.get()))
{
CHECK_FAILURE(args->put_Cancel(true));
}
return S_OK;
}).Get(), &m_frameNavigationStartingToken));
//! [FrameNavigationStarting]
//! [ScriptDialogOpening]
// Register a handler for the ScriptDialogOpening event.
// This handler will set up a custom prompt dialog for the user,
// and may defer the event if the setting to defer dialogs is enabled.
CHECK_FAILURE(m_webView->add_ScriptDialogOpening(
Callback<IWebView2ScriptDialogOpeningEventHandler>(
[this](
IWebView2WebView* sender,
IWebView2ScriptDialogOpeningEventArgs* args) -> HRESULT
{
wil::com_ptr<IWebView2ScriptDialogOpeningEventArgs> eventArgs = args;
auto showDialog = [this, eventArgs]
{
wil::unique_cotaskmem_string uri;
WEBVIEW2_SCRIPT_DIALOG_KIND type;
wil::unique_cotaskmem_string message;
wil::unique_cotaskmem_string defaultText;
CHECK_FAILURE(eventArgs->get_Uri(&uri));
CHECK_FAILURE(eventArgs->get_Kind(&type));
CHECK_FAILURE(eventArgs->get_Message(&message));
CHECK_FAILURE(eventArgs->get_DefaultText(&defaultText));
std::wstring promptString = std::wstring(L"The page at '")
+ uri.get() + L"' says:";
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Script Dialog",
promptString.c_str(),
message.get(),
defaultText.get(),
/* readonly */ type != WEBVIEW2_SCRIPT_DIALOG_KIND_PROMPT);
if (dialog.confirmed)
{
CHECK_FAILURE(eventArgs->put_ResultText(dialog.input.c_str()));
CHECK_FAILURE(eventArgs->Accept());
}
};
if (m_deferScriptDialogs)
{
wil::com_ptr<IWebView2Deferral> deferral;
CHECK_FAILURE(args->GetDeferral(&deferral));
m_completeDeferredDialog = [showDialog, deferral]
{
showDialog();
CHECK_FAILURE(deferral->Complete());
};
}
else
{
showDialog();
}
return S_OK;
}).Get(), &m_scriptDialogOpeningToken));
//! [ScriptDialogOpening]
//! [PermissionRequested]
// Register a handler for the PermissionRequested event.
// This handler prompts the user to allow or deny the request.
CHECK_FAILURE(m_webView->add_PermissionRequested(
Callback<IWebView2PermissionRequestedEventHandler>(
[this](
IWebView2WebView* sender,
IWebView2PermissionRequestedEventArgs* args) -> HRESULT
{
wil::unique_cotaskmem_string uri;
WEBVIEW2_PERMISSION_TYPE type = WEBVIEW2_PERMISSION_TYPE_UNKNOWN_PERMISSION;
BOOL userInitiated = FALSE;
CHECK_FAILURE(args->get_Uri(&uri));
CHECK_FAILURE(args->get_PermissionType(&type));
CHECK_FAILURE(args->get_IsUserInitiated(&userInitiated));
std::wstring message = L"Do you want to grant permission for ";
message += NameOfPermissionType(type);
message += L" to the website at ";
message += uri.get();
message += L"?\n\n";
message += (userInitiated
? L"This request came from a user gesture."
: L"This request did not come from a user gesture.");
int response = MessageBox(nullptr, message.c_str(), L"Permission Request",
MB_YESNOCANCEL | MB_ICONWARNING);
WEBVIEW2_PERMISSION_STATE state =
response == IDYES ? WEBVIEW2_PERMISSION_STATE_ALLOW
: response == IDNO ? WEBVIEW2_PERMISSION_STATE_DENY
: WEBVIEW2_PERMISSION_STATE_DEFAULT;
CHECK_FAILURE(args->put_State(state));
return S_OK;
}).Get(), &m_permissionRequestedToken));
//! [PermissionRequested]
}
bool SettingsComponent::HandleWindowMessage(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam,
LRESULT* result)
{
if (message == WM_COMMAND)
{
switch (LOWORD(wParam))
{
case ID_BLOCKEDSITES:
{
ChangeBlockedSites();
return true;
}
case ID_SETTINGS_SETUSERAGENT:
{
ChangeUserAgent();
return true;
}
case IDM_TOGGLE_JAVASCRIPT:
{
m_isScriptEnabled = !m_isScriptEnabled;
m_settings->put_IsScriptEnabled(m_isScriptEnabled);
MessageBox(nullptr,
(std::wstring(L"JavaScript will be ")
+ (m_isScriptEnabled ? L"enabled" : L"disabled")
+ L" after the next navigation.").c_str(),
L"Settings change", MB_OK);
return true;
}
case IDM_TOGGLE_WEB_MESSAGING:
{
BOOL isWebMessageEnabled;
m_settings->get_IsWebMessageEnabled(&isWebMessageEnabled);
m_settings->put_IsWebMessageEnabled(!isWebMessageEnabled);
MessageBox(nullptr,
(std::wstring(L"Web Messaging will be ")
+ (!isWebMessageEnabled ? L"enabled" : L"disabled")
+ L" after the next navigation.").c_str(),
L"Settings change", MB_OK);
return true;
}
case ID_SETTINGS_STATUS_BAR_ENABLED:
{
BOOL isStatusBarEnabled;
m_settings->get_IsStatusBarEnabled(&isStatusBarEnabled);
m_settings->put_IsStatusBarEnabled(!isStatusBarEnabled);
MessageBox(nullptr,
(std::wstring(L"Status bar will be ") +
+ (!isStatusBarEnabled ? L"enabled" : L"disabled")
+ L" after the next navigation.").c_str(),
L"Settings change", MB_OK);
return true;
}
case ID_SETTINGS_DEV_TOOLS_ENABLED:
{
BOOL areDevToolsEnabled = FALSE;
m_settings->get_AreDevToolsEnabled(&areDevToolsEnabled);
m_settings->put_AreDevToolsEnabled(!areDevToolsEnabled);
MessageBox(nullptr,
(std::wstring(L"Dev tools will be ")
+ (!areDevToolsEnabled ? L"enabled" : L"disabled")
+ L" after the next navigation.").c_str(),
L"Settings change", MB_OK);
return true;
}
case IDM_USE_DEFAULT_SCRIPT_DIALOGS:
{
BOOL defaultCurrentlyEnabled;
m_settings->get_AreDefaultScriptDialogsEnabled(&defaultCurrentlyEnabled);
if (!defaultCurrentlyEnabled)
{
m_settings->put_AreDefaultScriptDialogsEnabled(TRUE);
MessageBox(nullptr,
L"Default script dialogs will be used after the next navigation.",
L"Settings change", MB_OK);
}
return true;
}
case IDM_USE_CUSTOM_SCRIPT_DIALOGS:
{
BOOL defaultCurrentlyEnabled;
m_settings->get_AreDefaultScriptDialogsEnabled(&defaultCurrentlyEnabled);
if (defaultCurrentlyEnabled)
{
m_settings->put_AreDefaultScriptDialogsEnabled(FALSE);
m_deferScriptDialogs = false;
MessageBox(nullptr,
L"Custom script dialogs without deferral will be used after the next navigation.",
L"Settings change", MB_OK);
}
else if (m_deferScriptDialogs)
{
m_deferScriptDialogs = false;
MessageBox(nullptr,
L"Custom script dialogs without deferral will be used now.",
L"Settings change", MB_OK);
}
return true;
}
case IDM_USE_DEFERRED_SCRIPT_DIALOGS:
{
BOOL defaultCurrentlyEnabled;
m_settings->get_AreDefaultScriptDialogsEnabled(&defaultCurrentlyEnabled);
if (defaultCurrentlyEnabled)
{
m_settings->put_AreDefaultScriptDialogsEnabled(FALSE);
m_deferScriptDialogs = true;
MessageBox(nullptr,
L"Custom script dialogs with deferral will be used after the next navigation.",
L"Settings change", MB_OK);
}
else if (!m_deferScriptDialogs)
{
m_deferScriptDialogs = true;
MessageBox(nullptr,
L"Custom script dialogs with deferral will be used now.",
L"Settings change", MB_OK);
}
return true;
}
case IDM_COMPLETE_JAVASCRIPT_DIALOG:
{
CompleteScriptDialogDeferral();
return true;
}
case ID_SETTINGS_BLOCKALLIMAGES:
{
SetBlockImages(!m_blockImages);
MessageBox(nullptr,
(std::wstring(L"Image blocking has been ") +
(m_blockImages ? L"enabled." : L"disabled."))
.c_str(),
L"Settings change", MB_OK);
return true;
}
case ID_SETTINGS_CONTEXT_MENUS_ENABLED:
{
//! [DisableContextMenu]
BOOL allowContextMenus;
CHECK_FAILURE(m_settings->get_AreDefaultContextMenusEnabled(
&allowContextMenus));
if (allowContextMenus) {
CHECK_FAILURE(m_settings->put_AreDefaultContextMenusEnabled(FALSE));
MessageBox(nullptr,
L"Context menus will be disabled after the next navigation.",
L"Settings change", MB_OK);
}
else {
CHECK_FAILURE(m_settings->put_AreDefaultContextMenusEnabled(TRUE));
MessageBox(nullptr,
L"Context menus will be enabled after the next navigation.",
L"Settings change", MB_OK);
}
//! [DisableContextMenu]
return true;
}
}
}
return false;
}
// Prompt the user for a list of blocked domains
void SettingsComponent::ChangeBlockedSites()
{
std::wstring blockedSitesString;
if (m_blockedSitesSet)
{
for (auto& site : m_blockedSites)
{
if (!blockedSitesString.empty())
{
blockedSitesString += L";";
}
blockedSitesString += site;
}
}
else
{
blockedSitesString = L"foo.com;bar.org";
}
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Blocked Sites",
L"Sites:",
L"Enter hostnames to block, separated by semicolons.",
blockedSitesString.c_str());
if (dialog.confirmed)
{
m_blockedSitesSet = true;
m_blockedSites.clear();
size_t begin = 0;
size_t end = 0;
while (end != std::wstring::npos)
{
end = dialog.input.find(L';', begin);
if (end != begin)
{
m_blockedSites.push_back(dialog.input.substr(begin, end - begin));
}
begin = end + 1;
}
}
}
// Check the URI's domain against the blocked sites list
bool SettingsComponent::ShouldBlockUri(PWSTR uri)
{
wil::unique_bstr domain = GetDomainOfUri(uri);
for (auto site = m_blockedSites.begin();
site != m_blockedSites.end(); site++)
{
if (wcscmp(site->c_str(), domain.get()) == 0)
{
return true;
}
}
return false;
}
// Decide whether a website should have script disabled. Since we're only using this
// for sample code and we don't actually want to break any websites, just return false.
bool SettingsComponent::ShouldBlockScriptForUri(PWSTR uri)
{
return false;
}
// Turn on or off image blocking by adding or removing a WebResourceRequested handler
// which selectively intercepts requests for images.
void SettingsComponent::SetBlockImages(bool blockImages)
{
if (blockImages != m_blockImages)
{
m_blockImages = blockImages;
//! [WebResourceRequested]
if (m_blockImages)
{
m_webView->AddWebResourceRequestedFilter(L"*", WEBVIEW2_WEB_RESOURCE_CONTEXT_IMAGE);
CHECK_FAILURE(m_webView->add_WebResourceRequested(
Callback<IWebView2WebResourceRequestedEventHandler>(
[this](
IWebView2WebView* sender,
IWebView2WebResourceRequestedEventArgs* args) {
wil::com_ptr<IWebView2WebResourceRequestedEventArgs2>
webResourceEventArgs2;
args->QueryInterface(IID_PPV_ARGS(&webResourceEventArgs2));
WEBVIEW2_WEB_RESOURCE_CONTEXT resourceContext;
CHECK_FAILURE(
webResourceEventArgs2->get_ResourceContext(&resourceContext));
// Ensure that the type is image
if (resourceContext != WEBVIEW2_WEB_RESOURCE_CONTEXT_IMAGE)
{
return E_INVALIDARG;
}
// Override the response with an empty one to block the image.
// If put_Response is not called, the request will continue as normal.
wil::com_ptr<IWebView2WebResourceResponse> response;
CHECK_FAILURE(m_webViewEnvironment->CreateWebResourceResponse(
nullptr, 403 /*NoContent*/, L"Blocked", L"", &response));
CHECK_FAILURE(args->put_Response(response.get()));
return S_OK;
})
.Get(),
&m_webResourceRequestedTokenForImageBlocking));
}
else
{
CHECK_FAILURE(m_webView->remove_WebResourceRequested(
m_webResourceRequestedTokenForImageBlocking));
}
//! [WebResourceRequested]
}
}
// Prompt the user for a new User Agent string
void SettingsComponent::ChangeUserAgent() {
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"User Agent",
L"User agent:",
L"Enter user agent, or leave blank to restore default.",
m_changeUserAgent
? m_overridingUserAgent.c_str()
: L"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3818.0 Safari/537.36 Edg/77.0.188.0");
if (dialog.confirmed)
{
SetUserAgent(dialog.input);
}
}
// Register a WebResourceRequested handler which adds a custom User-Agent
// HTTP header to all requests.
void SettingsComponent::SetUserAgent(const std::wstring& userAgent)
{
if (m_changeUserAgent)
{
CHECK_FAILURE(m_webView->remove_WebResourceRequested(
m_webResourceRequestedTokenForUserAgent));
}
m_overridingUserAgent = userAgent;
if (m_overridingUserAgent.empty())
{
m_changeUserAgent = false;
}
else
{
m_changeUserAgent = true;
// Register a handler for the WebResourceRequested event.
// This handler adds a User-Agent HTTP header to the request,
// then lets the request continue normally.
m_webView->AddWebResourceRequestedFilter(L"*", WEBVIEW2_WEB_RESOURCE_CONTEXT_ALL);
m_webView->add_WebResourceRequested(
Callback<IWebView2WebResourceRequestedEventHandler>(
[this](IWebView2WebView* sender, IWebView2WebResourceRequestedEventArgs* args) {
wil::com_ptr<IWebView2WebResourceRequest> request;
CHECK_FAILURE(args->get_Request(&request));
wil::com_ptr<IWebView2HttpRequestHeaders> requestHeaders;
CHECK_FAILURE(request->get_Headers(&requestHeaders));
requestHeaders->SetHeader(L"User-Agent", m_overridingUserAgent.c_str());
return S_OK;
})
.Get(),
&m_webResourceRequestedTokenForUserAgent);
}
}
void SettingsComponent::CompleteScriptDialogDeferral()
{
if (m_completeDeferredDialog)
{
m_completeDeferredDialog();
m_completeDeferredDialog = nullptr;
}
}
SettingsComponent::~SettingsComponent()
{
m_webView->remove_NavigationStarting(m_navigationStartingToken);
m_webView->remove_FrameNavigationStarting(m_frameNavigationStartingToken);
m_webView->remove_WebResourceRequested(m_webResourceRequestedTokenForImageBlocking);
m_webView->remove_WebResourceRequested(m_webResourceRequestedTokenForUserAgent);
m_webView->remove_ScriptDialogOpening(m_scriptDialogOpeningToken);
m_webView->remove_PermissionRequested(m_permissionRequestedToken);
}
// Take advantage of urlmon's URI library to parse a URI
static wil::unique_bstr GetDomainOfUri(PWSTR uri)
{
wil::com_ptr<IUri> uriObject;
CreateUri(uri,
Uri_CREATE_CANONICALIZE | Uri_CREATE_NO_DECODE_EXTRA_INFO,
0, &uriObject);
wil::unique_bstr domain;
uriObject->GetHost(&domain);
return domain;
}
static PCWSTR NameOfPermissionType(WEBVIEW2_PERMISSION_TYPE type)
{
switch (type)
{
case WEBVIEW2_PERMISSION_TYPE_MICROPHONE:
return L"Microphone";
case WEBVIEW2_PERMISSION_TYPE_CAMERA:
return L"Camera";
case WEBVIEW2_PERMISSION_TYPE_GEOLOCATION:
return L"Geolocation";
case WEBVIEW2_PERMISSION_TYPE_NOTIFICATIONS:
return L"Notifications";
case WEBVIEW2_PERMISSION_TYPE_OTHER_SENSORS:
return L"Generic Sensors";
case WEBVIEW2_PERMISSION_TYPE_CLIPBOARD_READ:
return L"Clipboard Read";
default:
return L"Unknown resources";
}
}