-
Notifications
You must be signed in to change notification settings - Fork 517
Expand file tree
/
Copy pathScriptComponent.cpp
More file actions
430 lines (402 loc) · 14.6 KB
/
ScriptComponent.cpp
File metadata and controls
430 lines (402 loc) · 14.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
// 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 "ProcessComponent.h"
#include "ScriptComponent.h"
#include "CheckFailure.h"
#include "TextInputDialog.h"
using namespace Microsoft::WRL;
ScriptComponent::ScriptComponent(AppWindow* appWindow)
: m_appWindow(appWindow), m_webView(appWindow->GetWebView())
{
HandleIFrames();
}
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_ADD_HOST_OBJECT:
AddComObject();
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;
}
}
return false;
}
//! [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>(
[](HRESULT error, PCWSTR result) -> HRESULT
{
if (error != S_OK) {
ShowFailure(error, L"ExecuteScript failed");
}
MessageBox(nullptr, result, L"ExecuteScript Result", MB_OK);
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<ICoreWebView2ExperimentalFrame> frameExperimental =
m_frames[index].try_query<ICoreWebView2ExperimentalFrame>();
if (frameExperimental)
{
frameExperimental->ExecuteScript(
dialogScript.input.c_str(),
Callback<ICoreWebView2ExecuteScriptCompletedHandler>(
[](HRESULT error, PCWSTR result) -> HRESULT {
if (error != S_OK)
{
ShowFailure(error, L"ExecuteScript failed");
}
MessageBox(nullptr, result, 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;
MessageBox(nullptr, id, L"AddScriptToExecuteOnDocumentCreated Id", MB_OK);
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());
}
}
//! [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>(
[eventName](
ICoreWebView2* sender,
ICoreWebView2DevToolsProtocolEventReceivedEventArgs* args) -> HRESULT {
wil::unique_cotaskmem_string parameterObjectAsJson;
CHECK_FAILURE(args->get_ParameterObjectAsJson(¶meterObjectAsJson));
MessageBox(
nullptr, parameterObjectAsJson.get(),
(L"CDP Event Fired: " + eventName).c_str(), MB_OK);
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>(
[](HRESULT error, PCWSTR resultJson) -> HRESULT
{
MessageBox(nullptr, resultJson, L"CDP Method Result", MB_OK);
return S_OK;
}).Get());
}
}
//! [CallDevToolsProtocolMethod]
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::HandleIFrames()
{
wil::com_ptr<ICoreWebView2_4> webview2_4 = m_webView.try_query<ICoreWebView2_4>();
if (webview2_4)
{
CHECK_FAILURE(webview2_4->add_FrameCreated(
Callback<ICoreWebView2FrameCreatedEventHandler>(
[this](ICoreWebView2* sender, ICoreWebView2FrameCreatedEventArgs* args)
-> HRESULT {
wil::com_ptr<ICoreWebView2Frame> webviewFrame;
CHECK_FAILURE(args->get_Frame(&webviewFrame));
m_frames.emplace_back(webviewFrame);
webviewFrame->add_Destroyed(
Callback<ICoreWebView2FrameDestroyedEventHandler>(
[this](ICoreWebView2Frame* sender, IUnknown* args) -> HRESULT {
auto frame =
std::find(m_frames.begin(), m_frames.end(), sender);
if (frame != m_frames.end())
{
m_frames.erase(frame);
}
return S_OK;
})
.Get(),
NULL);
return S_OK;
})
.Get(),
NULL));
}
}
std::wstring ScriptComponent::IFramesToString()
{
std::wstring data;
for (size_t i = 0; i < m_frames.size(); i++)
{
wil::unique_cotaskmem_string name;
CHECK_FAILURE(m_frames[i]->get_Name(&name));
if (i > 0)
data += L"; ";
data += std::to_wstring(i) + L": " +
(!std::wcslen(name.get()) ? L"<empty_name>" : name.get());
}
return data;
}
void ScriptComponent::OpenTaskManagerWindow()
{
auto webView6 = m_webView.try_query<ICoreWebView2_6>();
if (webView6)
{
webView6->OpenTaskManagerWindow();
}
}
ScriptComponent::~ScriptComponent()
{
for (auto& pair : m_devToolsProtocolEventReceivedTokenMap)
{
wil::com_ptr<ICoreWebView2DevToolsProtocolEventReceiver> receiver;
CHECK_FAILURE(
m_webView->GetDevToolsProtocolEventReceiver(pair.first.c_str(), &receiver));
receiver->remove_DevToolsProtocolEventReceived(pair.second);
}
}