-
Notifications
You must be signed in to change notification settings - Fork 517
Expand file tree
/
Copy pathScriptComponent.cpp
More file actions
1291 lines (1217 loc) · 52.6 KB
/
ScriptComponent.cpp
File metadata and controls
1291 lines (1217 loc) · 52.6 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.
#include "stdafx.h"
#include <algorithm>
#include <sstream>
#include <string>
#include <commdlg.h>
#include "ProcessComponent.h"
#include "ScriptComponent.h"
#include "CheckFailure.h"
#include "TextInputDialog.h"
using namespace Microsoft::WRL;
//! [AdditionalAllowedFrameAncestors_1]
const std::wstring myTrustedSite = L"https://appassets.example";
const std::wstring siteToEmbed = L"https://www.microsoft.com";
// The trusted page is using <iframe name="my_site_embedding_frame">
// element to embed other sites.
const std::wstring siteEmbeddingFrameName = L"my_site_embedding_frame";
bool AreSitesSame(PCWSTR url1, PCWSTR url2)
{
wil::com_ptr<IUri> uri1;
CHECK_FAILURE(CreateUri(url1, Uri_CREATE_CANONICALIZE, 0, &uri1));
DWORD scheme1 = -1;
DWORD port1 = 0;
wil::unique_bstr host1;
CHECK_FAILURE(uri1->GetScheme(&scheme1));
CHECK_FAILURE(uri1->GetHost(&host1));
CHECK_FAILURE(uri1->GetPort(&port1));
wil::com_ptr<IUri> uri2;
CHECK_FAILURE(CreateUri(url2, Uri_CREATE_CANONICALIZE, 0, &uri2));
DWORD scheme2 = -1;
DWORD port2 = 0;
wil::unique_bstr host2;
CHECK_FAILURE(uri2->GetScheme(&scheme2));
CHECK_FAILURE(uri2->GetHost(&host2));
CHECK_FAILURE(uri2->GetPort(&port2));
return (scheme1 == scheme2) && (port1 == port2) && (wcscmp(host1.get(), host2.get()) == 0);
}
// App specific logic to decide whether the page is fully trusted.
bool IsAppContentUri(PCWSTR pageUrl)
{
return AreSitesSame(pageUrl, myTrustedSite.c_str());
}
// App specific logic to decide whether a site is the one it wants to embed.
bool IsTargetSite(PCWSTR siteUrl)
{
return AreSitesSame(siteUrl, siteToEmbed.c_str());
}
//! [AdditionalAllowedFrameAncestors_1]
// Simple functions to retrieve fields from a JSON message.
// For production code, you should use a real JSON parser library.
const std::wstring GetJSONStringField(PCWSTR JsonMessage, PCWSTR fieldName)
{
std::wstring message(JsonMessage);
std::wstring startSubStr = L"\"";
startSubStr.append(fieldName);
startSubStr.append(L"\":\"");
std::string::size_type start = message.find(startSubStr);
if (start == std::wstring::npos)
return std::wstring();
start += startSubStr.length();
std::string::size_type end = message.find(L'\"', start);
if (end == std::wstring::npos)
return std::wstring();
return message.substr(start, end - start);
}
const int64_t GetJSONIntegerField(PCWSTR JsonMessage, PCWSTR fieldName)
{
std::wstring message(JsonMessage);
std::wstring startSubStr = L"\"";
startSubStr.append(fieldName);
startSubStr.append(L"\":");
std::string::size_type start = message.find(startSubStr);
if (start == std::wstring::npos)
return 0;
start += startSubStr.length();
return _wtoi64(message.substr(start).c_str());
}
ScriptComponent::ScriptComponent(AppWindow* appWindow)
: m_appWindow(appWindow), m_webView(appWindow->GetWebView())
{
HandleIFrames();
HandleCDPTargets();
}
bool ScriptComponent::HandleWindowMessage(
HWND hWnd,
UINT message,
WPARAM wParam,
LPARAM lParam,
LRESULT* result)
{
if (message == WM_COMMAND)
{
switch (LOWORD(wParam))
{
case IDM_INJECT_SCRIPT:
InjectScript();
return true;
case ID_ADD_INITIALIZE_SCRIPT:
AddInitializeScript();
return true;
case ID_REMOVE_INITIALIZE_SCRIPT:
RemoveInitializeScript();
return true;
case IDM_POST_WEB_MESSAGE_STRING:
SendStringWebMessage();
return true;
case IDM_POST_WEB_MESSAGE_JSON:
SendJsonWebMessage();
return true;
case IDM_SUBSCRIBE_TO_CDP_EVENT:
SubscribeToCdpEvent();
return true;
case IDM_CALL_CDP_METHOD:
CallCdpMethod();
return true;
case IDM_CALL_CDP_METHOD_FOR_SESSION:
CallCdpMethodForSession();
return true;
case IDM_COLLECT_HEAP_MEMORY_VIA_CDP:
CollectHeapUsageViaCdp();
return true;
case IDM_ADD_HOST_OBJECT:
AddComObject();
return true;
case IDM_INJECT_SITE_EMBEDDING_IFRAME:
AddSiteEmbeddingIFrame();
return true;
case IDM_OPEN_DEVTOOLS_WINDOW:
m_webView->OpenDevToolsWindow();
return true;
case IDM_OPEN_TASK_MANAGER_WINDOW:
OpenTaskManagerWindow();
return true;
case IDM_INJECT_SCRIPT_FRAME:
InjectScriptInIFrame();
return true;
case IDM_POST_WEB_MESSAGE_STRING_FRAME:
SendStringWebMessageIFrame();
return true;
case IDM_POST_WEB_MESSAGE_JSON_FRAME:
SendJsonWebMessageIFrame();
return true;
case IDM_INJECT_SCRIPT_WITH_RESULT:
ExecuteScriptWithResult();
return true;
case IDM_ADD_EXTENSION:
AddBrowserExtension();
return true;
case IDM_REMOVE_EXTENSION:
RemoveOrDisableBrowserExtension(true);
return true;
case IDM_DISABLE_EXTENSION:
RemoveOrDisableBrowserExtension(false);
return true;
}
}
return false;
}
void ScriptComponent::AddBrowserExtension()
{
// Get the profile object.
auto webView2_13 = m_webView.try_query<ICoreWebView2_13>();
wil::com_ptr<ICoreWebView2Profile> webView2Profile;
CHECK_FAILURE(webView2_13->get_Profile(&webView2Profile));
auto profile7 = webView2Profile.try_query<ICoreWebView2Profile7>();
CHECK_FEATURE_RETURN_EMPTY(profile7);
OPENFILENAME openFileName = {};
openFileName.lStructSize = sizeof(openFileName);
openFileName.hwndOwner = nullptr;
openFileName.hInstance = nullptr;
WCHAR fileName[MAX_PATH] = L"";
openFileName.lpstrFile = fileName;
openFileName.lpstrFilter = L"Manifest\0manifest.json\0\0";
openFileName.nMaxFile = ARRAYSIZE(fileName);
openFileName.Flags = OFN_OVERWRITEPROMPT;
if (GetOpenFileName(&openFileName))
{
// Remove the filename part of the path.
*wcsrchr(fileName, L'\\') = L'\0';
profile7->AddBrowserExtension(
fileName,
Callback<ICoreWebView2ProfileAddBrowserExtensionCompletedHandler>(
[](HRESULT error, ICoreWebView2BrowserExtension* extension) -> HRESULT
{
if (error != S_OK)
{
ShowFailure(error, L"Faile to add browser extension");
}
wil::unique_cotaskmem_string id;
extension->get_Id(&id);
wil::unique_cotaskmem_string name;
extension->get_Name(&name);
std::wstring extensionInfo;
extensionInfo.append(L"Added ");
extensionInfo.append(id.get());
extensionInfo.append(L" ");
extensionInfo.append(name.get());
MessageBox(
nullptr, extensionInfo.c_str(), L"AddBrowserExtension Result", MB_OK);
return S_OK;
})
.Get());
}
}
void ScriptComponent::RemoveOrDisableBrowserExtension(const bool remove)
{
// Get the profile object.
auto webView2_13 = m_webView.try_query<ICoreWebView2_13>();
wil::com_ptr<ICoreWebView2Profile> webView2Profile;
CHECK_FAILURE(webView2_13->get_Profile(&webView2Profile));
auto profile7 = webView2Profile.try_query<ICoreWebView2Profile7>();
CHECK_FEATURE_RETURN_EMPTY(profile7);
profile7->GetBrowserExtensions(
Callback<ICoreWebView2ProfileGetBrowserExtensionsCompletedHandler>(
[this, profile7,
remove](HRESULT error, ICoreWebView2BrowserExtensionList* extensions) -> HRESULT
{
std::wstring extensionIdString;
UINT extensionsCount = 0;
extensions->get_Count(&extensionsCount);
for (UINT index = 0; index < extensionsCount; ++index)
{
wil::com_ptr<ICoreWebView2BrowserExtension> extension;
extensions->GetValueAtIndex(index, &extension);
wil::unique_cotaskmem_string id;
wil::unique_cotaskmem_string name;
BOOL enabled = false;
extension->get_IsEnabled(&enabled);
extension->get_Id(&id);
extension->get_Name(&name);
extensionIdString += id.get();
extensionIdString += L" ";
extensionIdString += name.get();
if (!enabled)
{
extensionIdString += L" (disabled)";
}
else
{
extensionIdString += L" (enabled)";
}
extensionIdString += L"\n\r\n";
}
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
remove ? L"Remove Extension" : L"Disable/Enable Extension",
L"Extension ID:", extensionIdString.c_str());
if (dialog.confirmed)
{
for (UINT index = 0; index < extensionsCount; ++index)
{
wil::com_ptr<ICoreWebView2BrowserExtension> extension;
extensions->GetValueAtIndex(index, &extension);
wil::unique_cotaskmem_string id;
wil::unique_cotaskmem_string name;
extension->get_Id(&id);
if (_wcsicmp(id.get(), dialog.input.c_str()) == 0)
{
if (remove)
{
extension->Remove(
Callback<
ICoreWebView2BrowserExtensionRemoveCompletedHandler>(
[](HRESULT error) -> HRESULT
{
if (error != S_OK)
{
ShowFailure(error, L"Remove Extension failed");
}
MessageBox(
nullptr, L"Done", L"Remove Extension", MB_OK);
return S_OK;
})
.Get());
}
else
{
BOOL enabled = FALSE;
extension->get_IsEnabled(&enabled);
extension->Enable(
!enabled,
Callback<
ICoreWebView2BrowserExtensionEnableCompletedHandler>(
[](HRESULT error) -> HRESULT
{
if (error != S_OK)
{
ShowFailure(error, L"Enable Extension failed");
}
MessageBox(
nullptr, L"Done", L"Toggled Extension", MB_OK);
return S_OK;
})
.Get());
}
}
}
}
return S_OK;
})
.Get());
}
//! [ExecuteScript]
// Prompt the user for some script and then execute it.
void ScriptComponent::InjectScript()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Inject Script",
L"Enter script code:",
L"Enter the JavaScript code to run in the webview.",
L"window.getComputedStyle(document.body).backgroundColor");
if (dialog.confirmed)
{
m_webView->ExecuteScript(dialog.input.c_str(),
Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[appWindow = m_appWindow](HRESULT error, PCWSTR result) -> HRESULT
{
if (error != S_OK) {
ShowFailure(error, L"ExecuteScript failed");
}
appWindow->AsyncMessageBox(result, L"ExecuteScript Result");
return S_OK;
}).Get());
}
}
//! [ExecuteScript]
void ScriptComponent::InjectScriptInIFrame()
{
std::wstring iframesData = IFramesToString();
std::wstring iframesInfo =
L"Enter iframe to run the JavaScript code in.\r\nAvailable iframes:" +
(m_frames.size() > 0 ? iframesData : L"not available at this page.");
TextInputDialog dialogIFrame(
m_appWindow->GetMainWindow(), L"Inject Script Into IFrame", L"Enter iframe number:",
iframesInfo.c_str(), L"0");
if (dialogIFrame.confirmed)
{
int index = -1;
try
{
index = std::stoi(dialogIFrame.input);
}
catch (std::exception)
{
}
if (index < 0 || index >= static_cast<int>(m_frames.size()))
{
ShowFailure(S_OK, L"Can not read frame index or it is out of available range");
return;
}
std::wstring iframesEnterCode =
L"Enter the JavaScript code to run in the iframe " + dialogIFrame.input;
TextInputDialog dialogScript(
m_appWindow->GetMainWindow(), L"Inject Script Into IFrame", L"Enter script code:",
iframesEnterCode.c_str(),
L"window.getComputedStyle(document.body).backgroundColor");
if (dialogScript.confirmed)
{
wil::com_ptr<ICoreWebView2Frame2> frame2 =
m_frames[index].try_query<ICoreWebView2Frame2>();
if (frame2)
{
frame2->ExecuteScript(
dialogScript.input.c_str(),
Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[this](HRESULT error, PCWSTR result) -> HRESULT {
m_appWindow->RunAsync([error, result = std::wstring(result)]
{
if (error != S_OK)
{
ShowFailure(error, L"ExecuteScript failed");
}
else
{
MessageBox(nullptr, result.c_str(), L"ExecuteScript Result", MB_OK);
}
});
return S_OK;
})
.Get());
}
}
}
}
//! [AddScriptToExecuteOnDocumentCreated]
// Prompt the user for some script and register it to execute whenever a new page loads.
void ScriptComponent::AddInitializeScript()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Add Initialize Script",
L"Initialization Script:",
L"Enter the JavaScript code to run as the initialization script that "
L"runs before any script in the HTML document.",
// This example script stops child frames from opening new windows. Because
// the initialization script runs before any script in the HTML document, we
// can trust the results of our checks on window.parent and window.top.
L"if (window.parent !== window.top) {\r\n"
L" delete window.open;\r\n"
L"}");
if (dialog.confirmed)
{
m_webView->AddScriptToExecuteOnDocumentCreated(
dialog.input.c_str(),
Callback<ICoreWebView2AddScriptToExecuteOnDocumentCreatedCompletedHandler>(
[this](HRESULT error, PCWSTR id) -> HRESULT
{
m_lastInitializeScriptId = id;
m_appWindow->AsyncMessageBox(
m_lastInitializeScriptId, L"AddScriptToExecuteOnDocumentCreated Id");
return S_OK;
}).Get());
}
}
//! [AddScriptToExecuteOnDocumentCreated]
// Prompt the user for an initialization script ID and deregister that script.
void ScriptComponent::RemoveInitializeScript()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Remove Initialize Script",
L"Script ID:",
L"Enter the ID created from Add Initialize Script.",
m_lastInitializeScriptId.c_str());
if (dialog.confirmed)
{
m_webView->RemoveScriptToExecuteOnDocumentCreated(dialog.input.c_str());
}
}
// Prompt the user for a string and then post it as a web message.
void ScriptComponent::SendStringWebMessage()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Post Web Message String",
L"Web message string:",
L"Enter the web message as a string.");
if (dialog.confirmed)
{
m_webView->PostWebMessageAsString(dialog.input.c_str());
}
}
// Prompt the user for some JSON and then post it as a web message.
void ScriptComponent::SendJsonWebMessage()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Post Web Message JSON",
L"Web message JSON:",
L"Enter the web message as JSON.",
L"{\"SetColor\":\"blue\"}");
if (dialog.confirmed)
{
m_webView->PostWebMessageAsJson(dialog.input.c_str());
}
}
// Prompt the user for a string and then post it as a web message to the first iframe.
void ScriptComponent::SendStringWebMessageIFrame()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(), L"Post Web Message String IFrame", L"Web message string:",
L"Enter the web message as a string.");
if (dialog.confirmed)
{
if (!m_frames.empty())
{
wil::com_ptr<ICoreWebView2Frame2> frame2 =
m_frames[0].try_query<ICoreWebView2Frame2>();
if (frame2)
{
frame2->PostWebMessageAsString(dialog.input.c_str());
}
} else {
ShowFailure(S_OK, L"No iframes found");
}
}
}
// Prompt the user for some JSON and then post it as a web message to the first iframe.
void ScriptComponent::SendJsonWebMessageIFrame()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(), L"Post Web Message JSON IFrame", L"Web message JSON:",
L"Enter the web message as JSON.", L"{\"SetColor\":\"blue\"}");
if (dialog.confirmed)
{
if (!m_frames.empty())
{
wil::com_ptr<ICoreWebView2Frame2> frame2 =
m_frames[0].try_query<ICoreWebView2Frame2>();
if (frame2)
{
frame2->PostWebMessageAsJson(dialog.input.c_str());
}
}
else {
ShowFailure(S_OK, L"No iframes found");
}
}
}
//! [DevToolsProtocolMethodMultiSession]
void ScriptComponent::HandleCDPTargets()
{
wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> receiver;
// Enable Runtime events to receive Runtime.consoleAPICalled events.
m_webView->CallDevToolsProtocolMethod(L"Runtime.enable", L"{}", nullptr);
CHECK_FAILURE(
m_webView->GetDevToolsProtocolEventReceiver(L"Runtime.consoleAPICalled", &receiver));
CHECK_FAILURE(receiver->add_DevToolsProtocolEventReceived(
Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(
[this](
ICoreWebView2* sender,
ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT
{
// Get console.log message details and which target it comes from.
wil::unique_cotaskmem_string parameterObjectAsJson;
CHECK_FAILURE(args->get_ParameterObjectAsJson(¶meterObjectAsJson));
std::wstring eventSourceLabel;
std::wstring eventDetails = parameterObjectAsJson.get();
wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceivedEventArgs2> args2;
if (SUCCEEDED(args->QueryInterface(IID_PPV_ARGS(&args2))))
{
wil::unique_cotaskmem_string sessionId;
CHECK_FAILURE(args2->get_SessionId(&sessionId));
if (sessionId.get() && *sessionId.get())
{
std::wstring targetId = m_devToolsSessionMap[sessionId.get()];
eventSourceLabel = m_devToolsTargetLabelMap[targetId];
}
}
// else, leave eventSourceLabel as empty string for the default target of top
// page.
// Log events to debug output, not using dialog as there could be a lot of
// console.log events.
std::wstring message = L"console.log Event: ";
if (!eventSourceLabel.empty())
{
message = message + L"(from " + eventSourceLabel + L")";
}
message += eventDetails + L"\n";
OutputDebugString(message.c_str());
return S_OK;
})
.Get(),
&m_consoleAPICalledToken));
receiver.reset();
// Track Target and session info via CDP events.
CHECK_FAILURE(
m_webView->GetDevToolsProtocolEventReceiver(L"Target.attachedToTarget", &receiver));
CHECK_FAILURE(receiver->add_DevToolsProtocolEventReceived(
Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(
[this](
ICoreWebView2* sender,
ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT
{
// A new target is attached, add its info to maps.
wil::unique_cotaskmem_string jsonMessage;
CHECK_FAILURE(args->get_ParameterObjectAsJson(&jsonMessage));
std::wstring sessionId = GetJSONStringField(jsonMessage.get(), L"sessionId");
std::wstring targetId = GetJSONStringField(jsonMessage.get(), L"targetId");
m_devToolsSessionMap[sessionId] = targetId;
std::wstring type = GetJSONStringField(jsonMessage.get(), L"type");
std::wstring url = GetJSONStringField(jsonMessage.get(), L"url");
m_devToolsTargetLabelMap.insert_or_assign(targetId, type + L"," + url);
wil::com_ptr<ICoreWebView2_11> webview2 =
m_webView.try_query<ICoreWebView2_11>();
if (webview2)
{
// Auto-attach to targets further created from this target (identified by
// its session ID), like dedicated worker target created in the iframe.
webview2->CallDevToolsProtocolMethodForSession(
sessionId.c_str(), L"Target.setAutoAttach",
LR"({"autoAttach":true,"waitForDebuggerOnStart":false,"flatten":true})",
nullptr);
// Also enable Runtime events to receive Runtime.consoleAPICalled from the
// target.
webview2->CallDevToolsProtocolMethodForSession(
sessionId.c_str(), L"Runtime.enable", L"{}", nullptr);
}
return S_OK;
})
.Get(),
&m_targetAttachedToken));
receiver.reset();
CHECK_FAILURE(
m_webView->GetDevToolsProtocolEventReceiver(L"Target.detachedFromTarget", &receiver));
CHECK_FAILURE(receiver->add_DevToolsProtocolEventReceived(
Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(
[this](
ICoreWebView2* sender,
ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT
{
// A target is detached, remove it from the maps.
wil::unique_cotaskmem_string jsonMessage;
CHECK_FAILURE(args->get_ParameterObjectAsJson(&jsonMessage));
std::wstring sessionId = GetJSONStringField(jsonMessage.get(), L"sessionId");
auto session = m_devToolsSessionMap.find(sessionId);
if (session != m_devToolsSessionMap.end())
{
m_devToolsTargetLabelMap.erase(session->second);
m_devToolsSessionMap.erase(session);
}
return S_OK;
})
.Get(),
&m_targetDetachedToken));
receiver.reset();
CHECK_FAILURE(
m_webView->GetDevToolsProtocolEventReceiver(L"Target.targetInfoChanged", &receiver));
CHECK_FAILURE(receiver->add_DevToolsProtocolEventReceived(
Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(
[this](
ICoreWebView2* sender,
ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT
{
// A target's info (such as its URL) has changed, so update its label in the
// target label map.
wil::unique_cotaskmem_string jsonMessage;
CHECK_FAILURE(args->get_ParameterObjectAsJson(&jsonMessage));
std::wstring targetId = GetJSONStringField(jsonMessage.get(), L"targetId");
if (m_devToolsTargetLabelMap.find(targetId) !=
m_devToolsTargetLabelMap.end())
{
// This is a target that we are interested in, update label.
std::wstring type = GetJSONStringField(jsonMessage.get(), L"type");
std::wstring url = GetJSONStringField(jsonMessage.get(), L"url");
m_devToolsTargetLabelMap[targetId] = type + L"," + url;
}
return S_OK;
})
.Get(),
&m_targetInfoChangedToken));
// Setup CDP targets operation mode.
// Set auto attach to attach to dedicated worker target.
m_webView->CallDevToolsProtocolMethod(
L"Target.setAutoAttach",
LR"({"autoAttach":true,"waitForDebuggerOnStart":false,"flatten":true})", nullptr);
// Set setDiscoverTargets to get targetCreated event for shared worker target.
m_webView->CallDevToolsProtocolMethod(
L"Target.setDiscoverTargets", LR"({"discover":true})", nullptr);
}
//! [DevToolsProtocolMethodMultiSession]
void ScriptComponent::CollectHeapUsageViaCdp()
{
if (m_pendingHeapUsageCollectionCount)
{
// Already collecting, return
return;
}
wil::com_ptr<ICoreWebView2_11> webview2 = m_webView.try_query<ICoreWebView2_11>();
CHECK_FEATURE_RETURN_EMPTY(webview2);
m_pendingHeapUsageCollectionCount = 0;
m_heapUsageResult.clear();
m_heapUsageResult.str(L"Heap Usage (KB)");
m_heapUsageResult << std::endl;
// Collect main target
++m_pendingHeapUsageCollectionCount;
std::wstring main_targetInfo = L"Main Page";
m_webView->CallDevToolsProtocolMethod(
L"Runtime.getHeapUsage", L"{}",
Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(
[this, main_targetInfo](HRESULT error, PCWSTR resultJson) -> HRESULT
{
HandleHeapUsageResult(main_targetInfo, resultJson);
return S_OK;
})
.Get());
// Collect heap usage for other targets.
for (auto& target : m_devToolsSessionMap)
{
++m_pendingHeapUsageCollectionCount;
std::wstring targetLabel = m_devToolsTargetLabelMap[target.second];
webview2->CallDevToolsProtocolMethodForSession(
target.first.c_str(), L"Runtime.getHeapUsage", L"{}",
Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(
[this, targetLabel](HRESULT error, PCWSTR resultJson) -> HRESULT
{
HandleHeapUsageResult(targetLabel, resultJson);
return S_OK;
})
.Get());
}
}
void ScriptComponent::HandleHeapUsageResult(std::wstring targetInfo, PCWSTR resultJson)
{
int64_t totalSize = GetJSONIntegerField(resultJson, L"totalSize");
int64_t usedSize = GetJSONIntegerField(resultJson, L"usedSize");
m_heapUsageResult << L"total:";
m_heapUsageResult.width(8);
m_heapUsageResult << (totalSize / 1024);
m_heapUsageResult << L", used:";
m_heapUsageResult.width(8);
m_heapUsageResult << (usedSize / 1024);
m_heapUsageResult << L", ";
m_heapUsageResult << targetInfo;
m_heapUsageResult << std::endl;
if (--m_pendingHeapUsageCollectionCount == 0)
{
MessageBox(nullptr, m_heapUsageResult.str().c_str(), L"Heap Usage", MB_OK);
}
}
//! [DevToolsProtocolEventReceived]
// Prompt the user to name a CDP event, and then subscribe to that event.
void ScriptComponent::SubscribeToCdpEvent()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Subscribe to CDP Event",
L"CDP event name:",
L"Enter the name of the CDP event to subscribe to.\r\n"
L"You may also have to call the \"enable\" method of the\r\n"
L"event's domain to receive events (for example \"Log.enable\").\r\n",
L"Log.entryAdded");
if (dialog.confirmed)
{
std::wstring eventName = dialog.input;
wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> receiver;
CHECK_FAILURE(
m_webView->GetDevToolsProtocolEventReceiver(eventName.c_str(), &receiver));
// If we are already subscribed to this event, unsubscribe first.
auto preexistingToken = m_devToolsProtocolEventReceivedTokenMap.find(eventName);
if (preexistingToken != m_devToolsProtocolEventReceivedTokenMap.end())
{
CHECK_FAILURE(receiver->remove_DevToolsProtocolEventReceived(
preexistingToken->second));
}
CHECK_FAILURE(receiver->add_DevToolsProtocolEventReceived(
Callback<ICoreWebView2DevToolsProtocolEventReceivedEventHandler>(
[this, eventName](
ICoreWebView2* sender,
ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT
{
wil::unique_cotaskmem_string parameterObjectAsJson;
CHECK_FAILURE(args->get_ParameterObjectAsJson(¶meterObjectAsJson));
std::wstring title = eventName;
std::wstring details = parameterObjectAsJson.get();
//! [DevToolsProtocolEventReceivedSessionId]
wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceivedEventArgs2> args2;
if (SUCCEEDED(args->QueryInterface(IID_PPV_ARGS(&args2))))
{
wil::unique_cotaskmem_string sessionId;
CHECK_FAILURE(args2->get_SessionId(&sessionId));
if (sessionId.get() && *sessionId.get())
{
title = eventName + L" (session:" + sessionId.get() + L")";
std::wstring targetId = m_devToolsSessionMap[sessionId.get()];
std::wstring targetLabel = m_devToolsTargetLabelMap[targetId];
details = L"From " + targetLabel + L" (session:" + sessionId.get() +
L")\r\n" + details;
}
}
//! [DevToolsProtocolEventReceivedSessionId]
m_appWindow->AsyncMessageBox(details, L"CDP Event Fired: " + title);
return S_OK;
})
.Get(),
&m_devToolsProtocolEventReceivedTokenMap[eventName]));
}
}
//! [DevToolsProtocolEventReceived]
//! [CallDevToolsProtocolMethod]
// Prompt the user for the name and parameters of a CDP method, then call it.
void ScriptComponent::CallCdpMethod()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Call CDP Method",
L"CDP method name:",
L"Enter the CDP method name to call, followed by a space,\r\n"
L"followed by the parameters in JSON format.",
L"Runtime.evaluate {\"expression\":\"alert(\\\"test\\\")\"}");
if (dialog.confirmed)
{
size_t delimiterPos = dialog.input.find(L' ');
std::wstring methodName = dialog.input.substr(0, delimiterPos);
std::wstring methodParams =
(delimiterPos < dialog.input.size()
? dialog.input.substr(delimiterPos + 1)
: L"{}");
m_webView->CallDevToolsProtocolMethod(
methodName.c_str(), methodParams.c_str(),
Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(
this, &ScriptComponent::CDPMethodCallback)
.Get());
}
}
//! [CallDevToolsProtocolMethod]
//! [CallDevToolsProtocolMethodForSession]
// Prompt the user for the sessionid, name and parameters of a CDP method, then call it.
void ScriptComponent::CallCdpMethodForSession()
{
wil::com_ptr<ICoreWebView2_11> webview2 = m_webView.try_query<ICoreWebView2_11>();
CHECK_FEATURE_RETURN_EMPTY(webview2);
std::wstring sessionList = L"Sessions:";
for (auto& target : m_devToolsSessionMap)
{
sessionList += L"\r\n";
sessionList += target.first;
sessionList += L":";
sessionList += m_devToolsTargetLabelMap[target.second];
}
std::wstring description =
L"Enter the sessionId, CDP method name to call, and parameters in JSON format, "
L"separated by space,\r\n" +
sessionList;
TextInputDialog dialog(
m_appWindow->GetMainWindow(), L"Call CDP Method For Session", L"Parameters:",
description.c_str(),
L"<sessionId> Runtime.getHeapUsage {}");
if (dialog.confirmed)
{
size_t delimiter1Pos = dialog.input.find(L' ');
std::wstring sessionId = dialog.input.substr(0, delimiter1Pos);
size_t delimiter2Pos = dialog.input.find(L' ', delimiter1Pos+1);
std::wstring methodName =
dialog.input.substr(delimiter1Pos+1, delimiter2Pos - delimiter1Pos - 1);
std::wstring methodParams =
(delimiter2Pos < dialog.input.size() ? dialog.input.substr(delimiter2Pos + 1)
: L"{}");
webview2->CallDevToolsProtocolMethodForSession(
sessionId.c_str(), methodName.c_str(), methodParams.c_str(),
Callback<ICoreWebView2CallDevToolsProtocolMethodCompletedHandler>(
this, &ScriptComponent::CDPMethodCallback)
.Get());
}
}
//! [CallDevToolsProtocolMethodForSession]
HRESULT ScriptComponent::CDPMethodCallback(HRESULT error, PCWSTR resultJson)
{
std::wostringstream message;
if (SUCCEEDED(error))
{
message << "Success!\nResult = " << resultJson;
}
else
{
message << "Error!\nHRESULT = 0x" << std::hex << error << "\nResult = " << resultJson;
}
m_appWindow->AsyncMessageBox(message.str(), L"CDP method call result");
return S_OK;
}
void ScriptComponent::AddComObject()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(),
L"Add COM object",
L"CLSID or ProgID of COM object:",
L"Enter the CLSID (eg '{0002DF01-0000-0000-C000-000000000046}')\r\n"
L"or ProgID (eg 'InternetExplorer.Application') of the COM object to create and\r\n"
L"provide to the WebView as `window.chrome.remoteObjects.example`.",
L"InternetExplorer.Application");
if (dialog.confirmed)
{
CLSID classId = {};
HRESULT hr = CLSIDFromProgID(dialog.input.c_str(), &classId);
if (FAILED(hr))
{
hr = CLSIDFromString(dialog.input.c_str(), &classId);
}
if (SUCCEEDED(hr))
{
wil::com_ptr_nothrow<IDispatch> objectAsDispatch;
hr = CoCreateInstance(
classId,
nullptr,
CLSCTX_LOCAL_SERVER | CLSCTX_INPROC_SERVER | CLSCTX_INPROC_HANDLER,
IID_PPV_ARGS(&objectAsDispatch));
if (SUCCEEDED(hr))
{
wil::unique_variant objectAsVariant;
objectAsVariant.vt = VT_DISPATCH;
hr = objectAsDispatch.query_to(IID_PPV_ARGS(&objectAsVariant.pdispVal));
if (SUCCEEDED(hr))
{
hr = m_webView->AddHostObjectToScript(L"example", &objectAsVariant);
if (FAILED(hr))
{
ShowFailure(hr, L"AddHostObjectToScript failed");
}
}
else
{
ShowFailure(hr, L"COM object doesn't support IDispatch");
}
}
else
{
ShowFailure(hr, L"CoCreateInstance failed");
}
}
else
{
ShowFailure(hr, L"Failed to convert string to CLSID or ProgID");
}
}
}
void ScriptComponent::AddSiteEmbeddingIFrame()
{
// Prompt the user for which site to embed in the iframe.
TextInputDialog dialog(
m_appWindow->GetMainWindow(), L"Inject Site Embedding iframe", L"Enter iframe url:",
L"Enter the url for the injected iframe.", siteToEmbed.c_str());
if (dialog.confirmed)
{
std::wstring script =
L"(() => { const iframe = document.createElement('iframe'); iframe.src = '";
script += dialog.input;
script +=
L"'; iframe.name='my_site_embedding_frame'; document.body.appendChild(iframe); })()";
m_webView->ExecuteScript(script.c_str(), nullptr);
}
}
//! [ExecuteScriptWithResult]
void ScriptComponent::ExecuteScriptWithResult()
{
TextInputDialog dialog(
m_appWindow->GetMainWindow(), L"Execute Script With Result", L"Enter script code:",
L"Enter the JavaScript code to run in the webview.", L"");
if (dialog.confirmed)
{
wil::com_ptr<ICoreWebView2_21> webView = m_webView.try_query<ICoreWebView2_21>();
if (!webView)
{
MessageBox(
nullptr, L"Get webview2 failed!", L"ExecuteScriptWithResult Result", MB_OK);
return;
}
// The main interface for excute script, the first param is the string
// which user want to execute, the second param is the callback to process
// the result, here use a lamada to the param.
webView->ExecuteScriptWithResult(
dialog.input.c_str(),
// The callback function has two param, the first one is the status of call.s
// it will always be the S_OK for now, and the second is the result struct.
Callback<ICoreWebView2ExecuteScriptWithResultCompletedHandler>(
[this](HRESULT errorCode, ICoreWebView2ExecuteScriptResult* result) -> HRESULT
{
if (errorCode != S_OK || result == nullptr)
{
MessageBox(