forked from react-native-webview/react-native-webview
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRNCWebChromeClient.java
More file actions
517 lines (427 loc) · 21.1 KB
/
RNCWebChromeClient.java
File metadata and controls
517 lines (427 loc) · 21.1 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
package com.reactnativecommunity.webview;
import android.Manifest;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.Message;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.ConsoleMessage;
import android.webkit.GeolocationPermissions;
import android.webkit.JsResult;
import android.webkit.JsPromptResult;
import android.webkit.PermissionRequest;
import android.webkit.ValueCallback;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.FrameLayout;
import androidx.annotation.RequiresApi;
import androidx.core.content.ContextCompat;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.LifecycleEventListener;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.common.build.ReactBuildConfig;
import com.facebook.react.modules.core.PermissionAwareActivity;
import com.facebook.react.modules.core.PermissionListener;
import com.facebook.react.uimanager.UIManagerHelper;
import com.reactnativecommunity.webview.events.TopLoadingProgressEvent;
import com.reactnativecommunity.webview.events.TopOpenWindowEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class RNCWebChromeClient extends WebChromeClient implements LifecycleEventListener {
protected static final FrameLayout.LayoutParams FULLSCREEN_LAYOUT_PARAMS = new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT, Gravity.CENTER);
protected static final int FULLSCREEN_SYSTEM_UI_VISIBILITY = View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN |
View.SYSTEM_UI_FLAG_LAYOUT_STABLE |
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION |
View.SYSTEM_UI_FLAG_FULLSCREEN |
View.SYSTEM_UI_FLAG_IMMERSIVE |
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
protected static final int COMMON_PERMISSION_REQUEST = 3;
protected RNCWebView mWebView;
protected View mVideoView;
protected WebChromeClient.CustomViewCallback mCustomViewCallback;
// This boolean block JS prompts and alerts from displaying during loading
protected boolean blockJsDuringLoading = true;
protected boolean suppressJavaScriptDialogs = false;
/*
* - Permissions -
* As native permissions are asynchronously handled by the PermissionListener, many fields have
* to be stored to send permissions results to the webview
*/
// Webview camera & audio permission callback
protected PermissionRequest permissionRequest;
// Webview camera & audio permission already granted
protected List<String> grantedPermissions;
// Webview geolocation permission callback
protected GeolocationPermissions.Callback geolocationPermissionCallback;
// Webview geolocation permission origin callback
protected String geolocationPermissionOrigin;
// true if native permissions dialog is shown, false otherwise
protected boolean permissionsRequestShown = false;
// Pending Android permissions for the next request
protected List<String> pendingPermissions = new ArrayList<>();
protected RNCWebView.ProgressChangedFilter progressChangedFilter = null;
protected boolean mAllowsProtectedMedia = false;
protected boolean mHasOnOpenWindowEvent = false;
public RNCWebChromeClient(RNCWebView webView) {
this.mWebView = webView;
}
@Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {
final WebView newWebView = new WebView(view.getContext());
if(mHasOnOpenWindowEvent) {
newWebView.setWebViewClient(new WebViewClient(){
@Override
public boolean shouldOverrideUrlLoading (WebView subview, String url) {
WritableMap event = Arguments.createMap();
event.putString("targetUrl", url);
((RNCWebView) view).dispatchEvent(
view,
new TopOpenWindowEvent(RNCWebViewWrapper.getReactTagFromWebView(view), event)
);
return true;
}
});
}
final WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
transport.setWebView(newWebView);
resultMsg.sendToTarget();
return true;
}
@Override
public boolean onConsoleMessage(ConsoleMessage message) {
if (ReactBuildConfig.DEBUG) {
return super.onConsoleMessage(message);
}
// Ignore console logs in non debug builds.
return true;
}
@Override
public void onProgressChanged(WebView webView, int newProgress) {
super.onProgressChanged(webView, newProgress);
final String url = webView.getUrl();
if (progressChangedFilter.isWaitingForCommandLoadUrl()) {
return;
}
int reactTag = RNCWebViewWrapper.getReactTagFromWebView(webView);
WritableMap event = Arguments.createMap();
event.putDouble("target", reactTag);
event.putString("title", webView.getTitle());
event.putString("url", url);
event.putBoolean("canGoBack", webView.canGoBack());
event.putBoolean("canGoForward", webView.canGoForward());
event.putDouble("progress", (float) newProgress / 100);
UIManagerHelper.getEventDispatcherForReactTag(this.mWebView.getThemedReactContext(), reactTag).dispatchEvent(new TopLoadingProgressEvent(reactTag, event));
}
@Override
public void onPermissionRequest(final PermissionRequest request) {
// Reset state to handle new request
grantedPermissions = new ArrayList<>();
permissionRequest = null;
ArrayList<String> requestedAndroidPermissions = new ArrayList<>();
ArrayList<String> permissionsNeedingDialog = new ArrayList<>();
ArrayList<String> permissionLabels = new ArrayList<>();
for (String requestedResource : request.getResources()) {
String androidPermission = null;
String requestPermissionIdentifier = null;
if (requestedResource.equals(PermissionRequest.RESOURCE_AUDIO_CAPTURE)) {
androidPermission = Manifest.permission.RECORD_AUDIO;
requestPermissionIdentifier = "microphone";
} else if (requestedResource.equals(PermissionRequest.RESOURCE_VIDEO_CAPTURE)) {
androidPermission = Manifest.permission.CAMERA;
requestPermissionIdentifier = "camera";
} else if(requestedResource.equals(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) {
if (mAllowsProtectedMedia) {
grantedPermissions.add(requestedResource);
} else {
/**
* Legacy handling (Kept in case it was working under some conditions (given Android version or something))
*
* Try to ask user to grant permission using Activity.requestPermissions
*
* Find more details here: https://github.com/react-native-webview/react-native-webview/pull/2732
*/
androidPermission = PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID;
} }
if (androidPermission != null) {
if (ContextCompat.checkSelfPermission(this.mWebView.getThemedReactContext(), androidPermission) == PackageManager.PERMISSION_GRANTED) {
// Permission already granted at OS level, but still need user confirmation
permissionsNeedingDialog.add(androidPermission);
permissionLabels.add(requestPermissionIdentifier);
} else {
// Permission not granted at OS level, need to request it
requestedAndroidPermissions.add(androidPermission);
}
}
}
// Show a SINGLE dialog for all permissions that are already granted at OS level
if (!permissionsNeedingDialog.isEmpty()) {
Uri originUri = request.getOrigin();
String host = originUri.getHost();
// Build message for all requested permissions
String permissionList = String.join(" and ", permissionLabels);
String alertMessage = String.format("Allow %s to use your %s?", host, permissionList);
AlertDialog.Builder builder = new AlertDialog.Builder(this.mWebView.getContext());
builder.setMessage(alertMessage);
builder.setCancelable(false);
builder.setPositiveButton("Allow", (dialog, which) -> {
// Add all permissions to granted list
for (String permission : permissionsNeedingDialog) {
if (permission.equals(Manifest.permission.CAMERA)) {
grantedPermissions.add(PermissionRequest.RESOURCE_VIDEO_CAPTURE);
} else if (permission.equals(Manifest.permission.RECORD_AUDIO)) {
grantedPermissions.add(PermissionRequest.RESOURCE_AUDIO_CAPTURE);
} else if (permission.equals(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) {
grantedPermissions.add(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID);
}
}
// If no additional system permissions needed, grant immediately
if (requestedAndroidPermissions.isEmpty()) {
if (!grantedPermissions.isEmpty()) {
try {
request.grant(grantedPermissions.toArray(new String[0]));
} catch (IllegalStateException e) {
// Request was already granted or denied, ignore
} finally {
grantedPermissions = null;
permissionRequest = null;
}
}
// DO NOT set permissionRequest since we're handling it entirely here
} else {
// Still need to request system permissions - set permissionRequest for listener callback
permissionRequest = request;
requestPermissions(requestedAndroidPermissions);
}
});
builder.setNegativeButton("Don't allow", (dialog, which) -> {
request.deny();
// Clean up state
grantedPermissions = null;
permissionRequest = null;
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
//Delay making `allow` clickable for 500ms to avoid unwanted presses.
Button posButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
posButton.setEnabled(false);
this.runDelayed(() -> posButton.setEnabled(true), 500);
return;
}
// If all the permissions are already granted (no dialog needed), send the response to the WebView synchronously
if (requestedAndroidPermissions.isEmpty()) {
if (!grantedPermissions.isEmpty()) {
request.grant(grantedPermissions.toArray(new String[0]));
grantedPermissions = null;
}
return;
}
// Otherwise, ask to Android System for native permissions asynchronously
this.permissionRequest = request;
requestPermissions(requestedAndroidPermissions);
}
private void runDelayed(Runnable function, long delayMillis) {
Handler handler = new Handler();
handler.postDelayed(function, delayMillis);
}
@Override
public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
if (ContextCompat.checkSelfPermission(this.mWebView.getThemedReactContext(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
/*
* Keep the trace of callback and origin for the async permission request
*/
geolocationPermissionCallback = callback;
geolocationPermissionOrigin = origin;
requestPermissions(Collections.singletonList(Manifest.permission.ACCESS_FINE_LOCATION));
} else {
String alertMessage = String.format("Allow %s to use your location?", origin);
AlertDialog.Builder builder = new AlertDialog.Builder(this.mWebView.getContext());
builder.setMessage(alertMessage);
builder.setCancelable(false);
builder.setPositiveButton("Allow", (dialog, which) -> {
callback.invoke(origin, true, false);
});
builder.setNegativeButton("Don't allow", (dialog, which) -> {
callback.invoke(origin, false, false);
});
AlertDialog alertDialog = builder.create();
alertDialog.show();
//Delay making `allow` clickable for 500ms to avoid unwanted presses.
Button posButton = alertDialog.getButton(AlertDialog.BUTTON_POSITIVE);
posButton.setEnabled(false);
this.runDelayed(() -> posButton.setEnabled(true), 500);
}
}
private PermissionAwareActivity getPermissionAwareActivity() {
Activity activity = this.mWebView.getThemedReactContext().getCurrentActivity();
if (activity == null) {
throw new IllegalStateException("Tried to use permissions API while not attached to an Activity.");
} else if (!(activity instanceof PermissionAwareActivity)) {
throw new IllegalStateException("Tried to use permissions API but the host Activity doesn't implement PermissionAwareActivity.");
}
return (PermissionAwareActivity) activity;
}
private synchronized void requestPermissions(List<String> permissions) {
/*
* If permissions request dialog is displayed on the screen and another request is sent to the
* activity, the last permission asked is skipped. As a work-around, we use pendingPermissions
* to store next required permissions.
*/
if (permissionsRequestShown) {
pendingPermissions.addAll(permissions);
return;
}
PermissionAwareActivity activity = getPermissionAwareActivity();
permissionsRequestShown = true;
activity.requestPermissions(
permissions.toArray(new String[0]),
COMMON_PERMISSION_REQUEST,
webviewPermissionsListener
);
// Pending permissions have been sent, the list can be cleared
pendingPermissions.clear();
}
private PermissionListener webviewPermissionsListener = (requestCode, permissions, grantResults) -> {
permissionsRequestShown = false;
/*
* As a "pending requests" approach is used, requestCode cannot help to define if the request
* came from geolocation or camera/audio. This is why shouldAnswerToPermissionRequest is used
*/
boolean shouldAnswerToPermissionRequest = false;
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
boolean granted = grantResults[i] == PackageManager.PERMISSION_GRANTED;
if (permission.equals(Manifest.permission.ACCESS_FINE_LOCATION)
&& geolocationPermissionCallback != null
&& geolocationPermissionOrigin != null) {
if (granted) {
geolocationPermissionCallback.invoke(geolocationPermissionOrigin, true, false);
} else {
geolocationPermissionCallback.invoke(geolocationPermissionOrigin, false, false);
}
geolocationPermissionCallback = null;
geolocationPermissionOrigin = null;
}
if (permission.equals(Manifest.permission.RECORD_AUDIO)) {
if (granted && grantedPermissions != null) {
grantedPermissions.add(PermissionRequest.RESOURCE_AUDIO_CAPTURE);
}
shouldAnswerToPermissionRequest = true;
}
if (permission.equals(Manifest.permission.CAMERA)) {
if (granted && grantedPermissions != null) {
grantedPermissions.add(PermissionRequest.RESOURCE_VIDEO_CAPTURE);
}
shouldAnswerToPermissionRequest = true;
}
if (permission.equals(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID)) {
if (granted && grantedPermissions != null) {
grantedPermissions.add(PermissionRequest.RESOURCE_PROTECTED_MEDIA_ID);
}
shouldAnswerToPermissionRequest = true;
}
}
if (shouldAnswerToPermissionRequest
&& permissionRequest != null
&& grantedPermissions != null) {
try {
permissionRequest.grant(grantedPermissions.toArray(new String[0]));
} catch (IllegalStateException e) {
// Request was already granted or denied, ignore
} finally {
permissionRequest = null;
grantedPermissions = null;
}
}
if (!pendingPermissions.isEmpty()) {
requestPermissions(pendingPermissions);
return false;
}
return true;
};
protected void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType) {
this.mWebView.getThemedReactContext().getNativeModule(RNCWebViewModule.class).startPhotoPickerIntent(filePathCallback, acceptType);
}
protected void openFileChooser(ValueCallback<Uri> filePathCallback) {
this.mWebView.getThemedReactContext().getNativeModule(RNCWebViewModule.class).startPhotoPickerIntent(filePathCallback, "");
}
protected void openFileChooser(ValueCallback<Uri> filePathCallback, String acceptType, String capture) {
this.mWebView.getThemedReactContext().getNativeModule(RNCWebViewModule.class).startPhotoPickerIntent(filePathCallback, acceptType);
}
@Override
public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback, FileChooserParams fileChooserParams) {
String[] acceptTypes = fileChooserParams.getAcceptTypes();
boolean allowMultiple = fileChooserParams.getMode() == WebChromeClient.FileChooserParams.MODE_OPEN_MULTIPLE;
return this.mWebView.getThemedReactContext().getNativeModule(RNCWebViewModule.class).startPhotoPickerIntent(filePathCallback, acceptTypes, allowMultiple, fileChooserParams.isCaptureEnabled());
}
@Override
public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {
if (shouldSuppressDialogs()) {
result.cancel();
return true;
} else {
return super.onJsPrompt(view, url, message, defaultValue, result);
}
}
@Override
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
if (shouldSuppressDialogs()) {
result.cancel();
return true;
}
return super.onJsAlert(view, url, message, result);
}
@Override
public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {
if (shouldSuppressDialogs()) {
result.cancel();
return true;
}
return super.onJsConfirm(view, url, message, result);
}
@Override
public void onHostResume() {
if (mVideoView != null && mVideoView.getSystemUiVisibility() != FULLSCREEN_SYSTEM_UI_VISIBILITY) {
mVideoView.setSystemUiVisibility(FULLSCREEN_SYSTEM_UI_VISIBILITY);
}
}
@Override
public void onHostPause() { }
@Override
public void onHostDestroy() { }
protected ViewGroup getRootView() {
return this.mWebView.getThemedReactContext().getCurrentActivity().findViewById(android.R.id.content);
}
public void setProgressChangedFilter(RNCWebView.ProgressChangedFilter filter) {
progressChangedFilter = filter;
}
/**
* Set whether or not protected media should be allowed
* /!\ Setting this to false won't revoke permission already granted to the current webpage.
* In order to do so, you'd need to reload the page /!\
*/
public void setAllowsProtectedMedia(boolean enabled) {
mAllowsProtectedMedia = enabled;
}
public void setHasOnOpenWindowEvent(boolean hasEvent) {
mHasOnOpenWindowEvent = hasEvent;
}
public void setSuppressJavaScriptDialogs(boolean suppress) {
suppressJavaScriptDialogs = suppress;
}
private boolean shouldSuppressDialogs() {
return suppressJavaScriptDialogs || blockJsDuringLoading;
}
}