/
ReactWebViewManager.cs
465 lines (419 loc) · 16.9 KB
/
ReactWebViewManager.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
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
// Copyright (c) Microsoft Corporation. All rights reserved.
// Portions derived from React Native:
// Copyright (c) 2015-present, Facebook, Inc.
// Licensed under the MIT License.
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ReactNative.Bridge;
using ReactNative.UIManager;
using ReactNative.UIManager.Annotations;
using ReactNative.Views.Web.Events;
using ReactNativeWebViewBridge;
using System;
using Windows.UI.Xaml.Controls;
using Windows.Web.Http;
using static System.FormattableString;
namespace ReactNative.Views.Web
{
/// <summary>
/// A view manager responsible for rendering webview.
/// </summary>
public class ReactWebViewManager : SimpleViewManager<WebView>
{
private const string BLANK_URL = "about:blank";
private const int CommandGoBack = 1;
private const int CommandGoForward = 2;
private const int CommandReload = 3;
private const int CommandStopLoading = 4;
private const int CommandPostMessage = 5;
private const int CommandInjectJavaScript = 6;
private const string BridgeName = "__REACT_WEB_VIEW_BRIDGE";
private readonly ViewKeyedDictionary<WebView, WebViewData> _webViewData = new ViewKeyedDictionary<WebView, WebViewData>();
private readonly ReactContext _context;
/// <summary>
/// Instantiates the <see cref="ReactWebViewManager"/>.
/// </summary>
/// <param name="context">The React context.</param>
public ReactWebViewManager(ReactContext context)
{
_context = context;
}
/// <summary>
/// The name of the view manager.
/// </summary>
public override string Name
{
get
{
return "RCTWebView";
}
}
/// <summary>
/// The commands map for the webview manager.
/// </summary>
public override JObject ViewCommandsMap
{
get
{
return new JObject
{
{ "goBack", CommandGoBack },
{ "goForward", CommandGoForward },
{ "reload", CommandReload },
{ "stopLoading", CommandStopLoading },
{ "postMessage", CommandPostMessage },
{ "injectJavaScript", CommandInjectJavaScript },
};
}
}
/// <summary>
/// Sets the background color for the <see cref="WebView"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="color">The masked color value.</param>
[ReactProp(ViewProps.BackgroundColor, CustomType = "Color")]
public void SetBackgroundColor(WebView view, uint? color)
{
if (color.HasValue)
{
view.DefaultBackgroundColor = ColorHelpers.Parse(color.Value);
}
else
{
view.ClearValue(WebView.DefaultBackgroundColorProperty);
}
}
/// <summary>
/// Sets whether JavaScript is enabled or not.
/// </summary>
/// <param name="view">A webview instance.</param>
/// <param name="enabled">A flag signaling whether JavaScript is enabled.</param>
[ReactProp("javaScriptEnabled")]
public void SetJavaScriptEnabled(WebView view, bool enabled)
{
view.Settings.IsJavaScriptEnabled = enabled;
}
/// <summary>
/// Sets whether Indexed DB is enabled or not.
/// </summary>
/// <param name="view">A webview instance.</param>
/// <param name="enabled">A flag signaling whether Indexed DB is enabled.</param>
[ReactProp("indexedDbEnabled")]
public void SetIndexedDbEnabled(WebView view, bool enabled)
{
view.Settings.IsIndexedDBEnabled = enabled;
}
/// <summary>
/// Sets the JavaScript to be injected when the page loads.
/// </summary>
/// <param name="view">A view instance.</param>
/// <param name="injectedJavaScript">The JavaScript to inject.</param>
[ReactProp("injectedJavaScript")]
public void SetInjectedJavaScript(WebView view, string injectedJavaScript)
{
var webViewData = GetWebViewData(view);
webViewData.InjectedJavaScript = injectedJavaScript;
}
/// <summary>
/// Toggles whether messaging is enabled for the <see cref="WebView"/>.
/// </summary>
/// <param name="view">The view instance.</param>
/// <param name="messagingEnabled">
/// <code>true</code> if messaging is allowed, otherwise <code>false</code>.
/// </param>
[ReactProp("messagingEnabled")]
public void SetMessagingEnabled(WebView view, bool messagingEnabled)
{
var webViewData = GetWebViewData(view);
if (messagingEnabled)
{
var bridge = new WebViewBridge(view.GetTag());
bridge.MessagePosted += OnMessagePosted;
webViewData.Bridge = bridge;
}
else if (webViewData.Bridge != null)
{
webViewData.Bridge.MessagePosted -= OnMessagePosted;
webViewData.Bridge = null;
}
}
/// <summary>
/// Sets webview source.
/// </summary>
/// <param name="view">A webview instance.</param>
/// <param name="source">A source for the webview (either static html or an uri).</param>
[ReactProp("source")]
public void SetSource(WebView view, JObject source)
{
var webViewData = GetWebViewData(view);
webViewData.Source = source;
webViewData.SourceUpdated = true;
}
/// <summary>
/// Receive events/commands directly from JavaScript through the
/// <see cref="UIManagerModule"/>.
/// </summary>
/// <param name="view">
/// The view instance that should receive the command.
/// </param>
/// <param name="commandId">Identifer for the command.</param>
/// <param name="args">Optional arguments for the command.</param>
public override void ReceiveCommand(WebView view, int commandId, JArray args)
{
switch (commandId)
{
case CommandGoBack:
if (view.CanGoBack) view.GoBack();
break;
case CommandGoForward:
if (view.CanGoForward) view.GoForward();
break;
case CommandReload:
view.Refresh();
break;
case CommandStopLoading:
view.Stop();
break;
case CommandPostMessage:
PostMessage(view, args[0].Value<string>());
break;
case CommandInjectJavaScript:
InvokeScript(view, args[0].Value<string>());
break;
default:
throw new InvalidOperationException(
Invariant($"Unsupported command '{commandId}' received by '{typeof(ReactWebViewManager)}'."));
}
}
/// <summary>
/// Called when view is detached from view hierarchy and allows for
/// additional cleanup by the <see cref="ReactWebViewManager"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view.</param>
public override void OnDropViewInstance(ThemedReactContext reactContext, WebView view)
{
base.OnDropViewInstance(reactContext, view);
view.NavigationStarting -= OnNavigationStarting;
view.DOMContentLoaded -= OnDOMContentLoaded;
view.NavigationFailed -= OnNavigationFailed;
view.NavigationCompleted -= OnNavigationCompleted;
_webViewData.Remove(view);
}
/// <summary>
/// Creates a new view instance of type <see cref="WebView"/>.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <returns>The view instance.</returns>
protected override WebView CreateViewInstance(ThemedReactContext reactContext)
{
var view = new WebView(WebViewExecutionMode.SeparateThread);
var data = new WebViewData();
_webViewData.AddOrUpdate(view, data);
return view;
}
/// <summary>
/// Subclasses can override this method to install custom event
/// emitters on the given view.
/// </summary>
/// <param name="reactContext">The React context.</param>
/// <param name="view">The view instance.</param>
protected override void AddEventEmitters(ThemedReactContext reactContext, WebView view)
{
base.AddEventEmitters(reactContext, view);
view.NavigationStarting += OnNavigationStarting;
view.DOMContentLoaded += OnDOMContentLoaded;
view.NavigationFailed += OnNavigationFailed;
view.NavigationCompleted += OnNavigationCompleted;
}
/// <summary>
/// Callback that will be triggered after all props are updated
/// </summary>
/// <param name="view">The view instance.</param>
protected override void OnAfterUpdateTransaction(WebView view)
{
var webViewData = GetWebViewData(view);
if (webViewData.SourceUpdated)
{
NavigateToSource(view);
webViewData.SourceUpdated = false;
}
}
private void NavigateToSource(WebView view)
{
var webViewData = GetWebViewData(view);
var source = webViewData.Source;
if (source != null)
{
var html = source.Value<string>("html");
if (html != null)
{
var baseUrl = source.Value<string>("baseUrl");
if (baseUrl != null)
{
view.Source = new Uri(baseUrl);
}
view.NavigateToString(html);
return;
}
var uri = source.Value<string>("uri");
if (uri != null)
{
// HTML files need to be loaded with the ms-appx-web schema.
uri = uri.Replace("ms-appx:", "ms-appx-web:");
string previousUri = view.Source?.OriginalString;
if (!String.IsNullOrWhiteSpace(previousUri) && previousUri.Equals(uri))
{
return;
}
using (var request = new HttpRequestMessage())
{
request.RequestUri = new Uri(uri);
var method = source.Value<string>("method");
if (method != null)
{
if (method.Equals("GET"))
{
request.Method = HttpMethod.Get;
}
else if (method.Equals("POST"))
{
request.Method = HttpMethod.Post;
}
else
{
throw new InvalidOperationException(
Invariant($"Unsupported method '{method}' received by '{typeof(ReactWebViewManager)}'."));
}
}
else
{
request.Method = HttpMethod.Get;
}
var headers = (JObject)source.GetValue("headers", StringComparison.Ordinal);
if (headers != null)
{
foreach (var header in headers)
{
request.Headers.Append(header.Key, header.Value.Value<string>());
}
}
var body = source.Value<string>("body");
if (body != null)
{
request.Content = new HttpStringContent(body);
}
view.NavigateWithHttpRequestMessage(request);
return;
}
}
}
view.Navigate(new Uri(BLANK_URL));
}
private async void InvokeScript(WebView view, string script)
{
await view.InvokeScriptAsync("eval", new[] { script }).AsTask().ConfigureAwait(false);
}
private void PostMessage(WebView view, string message)
{
var json = new JObject
{
{ "data", message },
};
var script = "(function() {" +
"var event;" +
$"var data = {json.ToString(Formatting.None)};" +
"try {" +
"event = new MessageEvent('message', data);" +
"} catch (e) {" +
"event = document.createEvent('MessageEvent');" +
"event.initMessageEvent('message', true, true, data.data, data.origin, data.lastEventId, data.source);" +
"}" +
"document.dispatchEvent(event);" +
"})();";
InvokeScript(view, script);
}
private void OnNavigationStarting(object sender, WebViewNavigationStartingEventArgs e)
{
var webView = (WebView)sender;
var tag = webView.GetTag();
webView.GetReactContext().GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new WebViewLoadEvent(
tag,
WebViewLoadEvent.TopLoadingStart,
e.Uri?.OriginalString,
true,
webView.DocumentTitle,
webView.CanGoBack,
webView.CanGoForward));
var bridge = GetWebViewData(webView).Bridge;
if (bridge != null)
{
webView.AddWebAllowedObject(BridgeName, bridge);
}
}
private void OnDOMContentLoaded(WebView sender, WebViewDOMContentLoadedEventArgs args)
{
var webViewData = GetWebViewData(sender);
if (webViewData.Bridge != null)
{
InvokeScript(sender, $"window.postMessage = data => {BridgeName}.postMessage(String(data))");
}
}
private void OnNavigationFailed(object sender, WebViewNavigationFailedEventArgs e)
{
var webView = (WebView)sender;
webView.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new WebViewLoadingErrorEvent(
webView.GetTag(),
e.WebErrorStatus));
}
private void OnNavigationCompleted(object sender, WebViewNavigationCompletedEventArgs e)
{
var webView = (WebView)sender;
webView.GetReactContext()
.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new WebViewLoadEvent(
webView.GetTag(),
WebViewLoadEvent.TopLoadingFinish,
e.Uri?.OriginalString,
false,
webView.DocumentTitle,
webView.CanGoBack,
webView.CanGoForward));
if (e.IsSuccess)
{
var injectedJavaScript = GetWebViewData(webView).InjectedJavaScript;
if (injectedJavaScript != null)
{
InvokeScript(webView, injectedJavaScript);
}
}
}
private void OnMessagePosted(object sender, MessagePostedEventArgs e)
{
_context.GetNativeModule<UIManagerModule>()
.EventDispatcher
.DispatchEvent(
new MessageEvent(e.Tag, e.Message));
}
private WebViewData GetWebViewData(WebView webView)
{
return _webViewData[webView];
}
class WebViewData
{
public WebViewBridge Bridge { get; set; }
public JObject Source { get; set; }
public bool SourceUpdated { get; set; }
public string InjectedJavaScript { get; set; }
}
}
}