-
Notifications
You must be signed in to change notification settings - Fork 4.7k
/
RNCWebView.m
1664 lines (1489 loc) · 63.2 KB
/
RNCWebView.m
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) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
#import "RNCWebView.h"
#import <React/RCTConvert.h>
#import <React/RCTAutoInsetsProtocol.h>
#import "RNCWKProcessPoolManager.h"
#if !TARGET_OS_OSX
#import <UIKit/UIKit.h>
#else
#import <React/RCTUIKit.h>
#endif // !TARGET_OS_OSX
#import "objc/runtime.h"
static NSTimer *keyboardTimer;
static NSString *const HistoryShimName = @"ReactNativeHistoryShim";
static NSString *const MessageHandlerName = @"ReactNativeWebView";
static NSURLCredential* clientAuthenticationCredential;
static NSDictionary* customCertificatesForHost;
NSString *const CUSTOM_SELECTOR = @"_CUSTOM_SELECTOR_";
#if !TARGET_OS_OSX
// runtime trick to remove WKWebView keyboard default toolbar
// see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
@interface _SwizzleHelperWK : UIView
@property (nonatomic, copy) WKWebView *webView;
@end
@implementation _SwizzleHelperWK
-(id)inputAccessoryView
{
if (_webView == nil) {
return nil;
}
if ([_webView respondsToSelector:@selector(inputAssistantItem)]) {
UITextInputAssistantItem *inputAssistantItem = [_webView inputAssistantItem];
inputAssistantItem.leadingBarButtonGroups = @[];
inputAssistantItem.trailingBarButtonGroups = @[];
}
return nil;
}
@end
#endif // !TARGET_OS_OSX
#if TARGET_OS_OSX
@interface RNCWKWebView : WKWebView
@end
@implementation RNCWKWebView
- (void)scrollWheel:(NSEvent *)theEvent {
RNCWebView *rncWebView = (RNCWebView *)[self superview];
RCTAssert([rncWebView isKindOfClass:[rncWebView class]], @"superview must be an RNCWebView");
if (![rncWebView scrollEnabled]) {
[[self nextResponder] scrollWheel:theEvent];
return;
}
[super scrollWheel:theEvent];
}
@end
#endif // TARGET_OS_OSX
@interface RNCWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler,
#if !TARGET_OS_OSX
UIScrollViewDelegate,
#endif // !TARGET_OS_OSX
RCTAutoInsetsProtocol>
@property (nonatomic, copy) RCTDirectEventBlock onFileDownload;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingProgress;
@property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
@property (nonatomic, copy) RCTDirectEventBlock onHttpError;
@property (nonatomic, copy) RCTDirectEventBlock onMessage;
@property (nonatomic, copy) RCTDirectEventBlock onScroll;
@property (nonatomic, copy) RCTDirectEventBlock onContentProcessDidTerminate;
#if !TARGET_OS_OSX
@property (nonatomic, copy) WKWebView *webView;
#else
@property (nonatomic, copy) RNCWKWebView *webView;
#endif // !TARGET_OS_OSX
@property (nonatomic, strong) WKUserScript *postMessageScript;
@property (nonatomic, strong) WKUserScript *atStartScript;
@property (nonatomic, strong) WKUserScript *atEndScript;
@end
@implementation RNCWebView
{
#if !TARGET_OS_OSX
UIColor * _savedBackgroundColor;
#else
RCTUIColor * _savedBackgroundColor;
#endif // !TARGET_OS_OSX
BOOL _savedHideKeyboardAccessoryView;
BOOL _savedKeyboardDisplayRequiresUserAction;
// Workaround for StatusBar appearance bug for iOS 12
// https://github.com/react-native-webview/react-native-webview/issues/62
BOOL _isFullScreenVideoOpen;
#if !TARGET_OS_OSX
UIStatusBarStyle _savedStatusBarStyle;
#endif // !TARGET_OS_OSX
BOOL _savedStatusBarHidden;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
UIScrollViewContentInsetAdjustmentBehavior _savedContentInsetAdjustmentBehavior;
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 /* __IPHONE_13_0 */
BOOL _savedAutomaticallyAdjustsScrollIndicatorInsets;
#endif
}
- (instancetype)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame])) {
#if !TARGET_OS_OSX
super.backgroundColor = [UIColor clearColor];
#else
super.backgroundColor = [RCTUIColor clearColor];
#endif // !TARGET_OS_OSX
_bounces = YES;
_scrollEnabled = YES;
_showsHorizontalScrollIndicator = YES;
_showsVerticalScrollIndicator = YES;
_directionalLockEnabled = YES;
_automaticallyAdjustContentInsets = YES;
_autoManageStatusBarEnabled = YES;
_contentInset = UIEdgeInsetsZero;
_savedKeyboardDisplayRequiresUserAction = YES;
#if !TARGET_OS_OSX
_savedStatusBarStyle = RCTSharedApplication().statusBarStyle;
_savedStatusBarHidden = RCTSharedApplication().statusBarHidden;
#endif // !TARGET_OS_OSX
_injectedJavaScript = nil;
_injectedJavaScriptForMainFrameOnly = YES;
_injectedJavaScriptBeforeContentLoaded = nil;
_injectedJavaScriptBeforeContentLoadedForMainFrameOnly = YES;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
_savedContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 /* __IPHONE_13_0 */
_savedAutomaticallyAdjustsScrollIndicatorInsets = NO;
#endif
_enableApplePay = NO;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000 /* iOS 15 */
_mediaCapturePermissionGrantType = RNCWebViewPermissionGrantType_Prompt;
#endif
}
#if !TARGET_OS_OSX
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(appDidBecomeActive)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(appWillResignActive)
name:UIApplicationWillResignActiveNotification
object:nil];
if (@available(iOS 12.0, *)) {
// Workaround for a keyboard dismissal bug present in iOS 12
// https://openradar.appspot.com/radar?id=5018321736957952
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardWillHide)
name:UIKeyboardWillHideNotification object:nil];
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(keyboardWillShow)
name:UIKeyboardWillShowNotification object:nil];
// Workaround for StatusBar appearance bug for iOS 12
// https://github.com/react-native-webview/react-native-webview/issues/62
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(showFullScreenVideoStatusBars)
name:UIWindowDidBecomeVisibleNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(hideFullScreenVideoStatusBars)
name:UIWindowDidBecomeHiddenNotification
object:nil];
}
#endif // !TARGET_OS_OSX
return self;
}
#if !TARGET_OS_OSX
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
// Only allow long press gesture
if ([otherGestureRecognizer isKindOfClass:[UILongPressGestureRecognizer class]]) {
return YES;
}else{
return NO;
}
}
// Listener for long presses
- (void)startLongPress:(UILongPressGestureRecognizer *)pressSender
{
// When a long press ends, bring up our custom UIMenu
if(pressSender.state == UIGestureRecognizerStateEnded) {
if (!self.menuItems || self.menuItems.count == 0) {
return;
}
UIMenuController *menuController = [UIMenuController sharedMenuController];
NSMutableArray *menuControllerItems = [NSMutableArray arrayWithCapacity:self.menuItems.count];
for(NSDictionary *menuItem in self.menuItems) {
NSString *menuItemLabel = [RCTConvert NSString:menuItem[@"label"]];
NSString *menuItemKey = [RCTConvert NSString:menuItem[@"key"]];
NSString *sel = [NSString stringWithFormat:@"%@%@", CUSTOM_SELECTOR, menuItemKey];
UIMenuItem *item = [[UIMenuItem alloc] initWithTitle: menuItemLabel
action: NSSelectorFromString(sel)];
[menuControllerItems addObject: item];
}
menuController.menuItems = menuControllerItems;
[menuController setMenuVisible:YES animated:YES];
}
}
#endif // !TARGET_OS_OSX
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)tappedMenuItem:(NSString *)eventType
{
// Get the selected text
// NOTE: selecting text in an iframe or shadow DOM will not work
[self.webView evaluateJavaScript: @"window.getSelection().toString()" completionHandler: ^(id result, NSError *error) {
if (error != nil) {
RCTLogWarn(@"%@", [NSString stringWithFormat:@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. %@", error]);
} else {
if (self.onCustomMenuSelection) {
NSPredicate *filter = [NSPredicate predicateWithFormat:@"key contains[c] %@ ",eventType];
NSArray *filteredMenuItems = [self.menuItems filteredArrayUsingPredicate:filter];
NSDictionary *selectedMenuItem = filteredMenuItems[0];
NSString *label = [RCTConvert NSString:selectedMenuItem[@"label"]];
self.onCustomMenuSelection(@{
@"key": eventType,
@"label": label,
@"selectedText": result
});
} else {
RCTLogWarn(@"Error evaluating onCustomMenuSelection: You must implement an `onCustomMenuSelection` callback when using custom menu items");
}
}
}];
}
// Overwrite method that interprets which action to call upon UIMenu Selection
// https://developer.apple.com/documentation/objectivec/nsobject/1571960-methodsignatureforselector
- (NSMethodSignature *)methodSignatureForSelector:(SEL)sel
{
NSMethodSignature *existingSelector = [super methodSignatureForSelector:sel];
if (existingSelector) {
return existingSelector;
}
return [super methodSignatureForSelector:@selector(tappedMenuItem:)];
}
// Needed to forward messages to other objects
// https://developer.apple.com/documentation/objectivec/nsobject/1571955-forwardinvocation
- (void)forwardInvocation:(NSInvocation *)invocation
{
NSString *sel = NSStringFromSelector([invocation selector]);
NSRange match = [sel rangeOfString:CUSTOM_SELECTOR];
if (match.location == 0) {
[self tappedMenuItem:[sel substringFromIndex:17]];
} else {
[super forwardInvocation:invocation];
}
}
// Allows the instance to respond to UIMenuController Actions
- (BOOL)canBecomeFirstResponder
{
return YES;
}
// Control which items show up on the UIMenuController
- (BOOL)canPerformAction:(SEL)action withSender:(id)sender
{
NSString *sel = NSStringFromSelector(action);
// Do any of them have our custom keys?
NSRange match = [sel rangeOfString:CUSTOM_SELECTOR];
if (match.location == 0) {
return YES;
}
return NO;
}
/**
* See https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank/25853806#25853806 for details.
*/
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
if (!navigationAction.targetFrame.isMainFrame) {
[webView loadRequest:navigationAction.request];
}
return nil;
}
- (WKWebViewConfiguration *)setUpWkWebViewConfig
{
WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
WKPreferences *prefs = [[WKPreferences alloc]init];
BOOL _prefsUsed = NO;
if (!_javaScriptEnabled) {
prefs.javaScriptEnabled = NO;
_prefsUsed = YES;
}
if (_allowUniversalAccessFromFileURLs) {
[wkWebViewConfig setValue:@TRUE forKey:@"allowUniversalAccessFromFileURLs"];
}
if (_allowFileAccessFromFileURLs) {
[prefs setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
_prefsUsed = YES;
}
if (_javaScriptCanOpenWindowsAutomatically) {
[prefs setValue:@TRUE forKey:@"javaScriptCanOpenWindowsAutomatically"];
_prefsUsed = YES;
}
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 140500 /* iOS 14.5 */
if (@available(iOS 14.5, *)) {
if (!_textInteractionEnabled) {
[prefs setValue:@FALSE forKey:@"textInteractionEnabled"];
_prefsUsed = YES;
}
}
#endif
if (_prefsUsed) {
wkWebViewConfig.preferences = prefs;
}
if (_incognito) {
wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
} else if (_cacheEnabled) {
wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
}
if(self.useSharedProcessPool) {
wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPoolForScopeKey:self.scopeKey];
}
wkWebViewConfig.userContentController = [WKUserContentController new];
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 /* iOS 13 */
if (@available(iOS 13.0, *)) {
WKWebpagePreferences *pagePrefs = [[WKWebpagePreferences alloc]init];
pagePrefs.preferredContentMode = _contentMode;
wkWebViewConfig.defaultWebpagePreferences = pagePrefs;
}
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 140000 /* iOS 14 */
if (@available(iOS 14.0, *)) {
if ([wkWebViewConfig respondsToSelector:@selector(limitsNavigationsToAppBoundDomains)]) {
if (_limitsNavigationsToAppBoundDomains) {
wkWebViewConfig.limitsNavigationsToAppBoundDomains = YES;
}
}
}
#endif
// Shim the HTML5 history API:
[wkWebViewConfig.userContentController addScriptMessageHandler:[[RNCWeakScriptMessageDelegate alloc] initWithDelegate:self]
name:HistoryShimName];
[self resetupScripts:wkWebViewConfig];
if(@available(macos 10.11, ios 9.0, *)) {
wkWebViewConfig.allowsAirPlayForMediaPlayback = _allowsAirPlayForMediaPlayback;
}
#if !TARGET_OS_OSX
wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
#if WEBKIT_IOS_10_APIS_AVAILABLE
wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
? WKAudiovisualMediaTypeAll
: WKAudiovisualMediaTypeNone;
wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
#else
wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
#endif
#endif // !TARGET_OS_OSX
if (_applicationNameForUserAgent) {
wkWebViewConfig.applicationNameForUserAgent = [NSString stringWithFormat:@"%@ %@", wkWebViewConfig.applicationNameForUserAgent, _applicationNameForUserAgent];
}
return wkWebViewConfig;
}
- (void)didMoveToWindow
{
if (self.window != nil && _webView == nil) {
WKWebViewConfiguration *wkWebViewConfig = [self setUpWkWebViewConfig];
#if !TARGET_OS_OSX
_webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
#else
_webView = [[RNCWKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
#endif // !TARGET_OS_OSX
[self setBackgroundColor: _savedBackgroundColor];
#if !TARGET_OS_OSX
_webView.scrollView.delegate = self;
#endif // !TARGET_OS_OSX
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
#if !TARGET_OS_OSX
if (_pullToRefreshEnabled) {
[self addPullToRefreshControl];
}
_webView.scrollView.scrollEnabled = _scrollEnabled;
_webView.scrollView.pagingEnabled = _pagingEnabled;
//For UIRefreshControl to work correctly, the bounces should always be true
_webView.scrollView.bounces = _pullToRefreshEnabled || _bounces;
_webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
_webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
_webView.scrollView.directionalLockEnabled = _directionalLockEnabled;
#endif // !TARGET_OS_OSX
_webView.allowsLinkPreview = _allowsLinkPreview;
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
_webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
_webView.customUserAgent = _userAgent;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
_webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
}
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 /* __IPHONE_13_0 */
if (@available(iOS 13.0, *)) {
_webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = _savedAutomaticallyAdjustsScrollIndicatorInsets;
}
#endif
[self addSubview:_webView];
[self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
[self setKeyboardDisplayRequiresUserAction: _savedKeyboardDisplayRequiresUserAction];
[self visitSource];
}
#if !TARGET_OS_OSX
// Allow this object to recognize gestures
if (self.menuItems != nil) {
UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(startLongPress:)];
longPress.delegate = self;
longPress.minimumPressDuration = 0.4f;
longPress.numberOfTouchesRequired = 1;
longPress.cancelsTouchesInView = YES;
[self addGestureRecognizer:longPress];
}
#endif // !TARGET_OS_OSX
}
// Update webview property when the component prop changes.
- (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
_allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
_webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
}
- (void)removeFromSuperview
{
if (_webView) {
[_webView.configuration.userContentController removeScriptMessageHandlerForName:HistoryShimName];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
[_webView removeObserver:self forKeyPath:@"estimatedProgress"];
[_webView removeFromSuperview];
#if !TARGET_OS_OSX
_webView.scrollView.delegate = nil;
#endif // !TARGET_OS_OSX
_webView = nil;
if (_onContentProcessDidTerminate) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
_onContentProcessDidTerminate(event);
}
}
[super removeFromSuperview];
}
#if !TARGET_OS_OSX
-(void)showFullScreenVideoStatusBars
{
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (!_autoManageStatusBarEnabled) {
return;
}
_isFullScreenVideoOpen = YES;
RCTUnsafeExecuteOnMainQueueSync(^{
[RCTSharedApplication() setStatusBarStyle:self->_savedStatusBarStyle animated:YES];
});
#pragma clang diagnostic pop
}
-(void)hideFullScreenVideoStatusBars
{
#pragma clang diagnostic ignored "-Wdeprecated-declarations"
if (!_autoManageStatusBarEnabled) {
return;
}
_isFullScreenVideoOpen = NO;
RCTUnsafeExecuteOnMainQueueSync(^{
[RCTSharedApplication() setStatusBarHidden:self->_savedStatusBarHidden animated:YES];
[RCTSharedApplication() setStatusBarStyle:self->_savedStatusBarStyle animated:YES];
});
#pragma clang diagnostic pop
}
-(void)keyboardWillHide
{
keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
[[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
}
-(void)keyboardWillShow
{
if (keyboardTimer != nil) {
[keyboardTimer invalidate];
}
}
-(void)keyboardDisplacementFix
{
// Additional viewport checks to prevent unintentional scrolls
UIScrollView *scrollView = self.webView.scrollView;
double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
if (maxContentOffset < 0) {
maxContentOffset = 0;
}
if (scrollView.contentOffset.y > maxContentOffset) {
// https://stackoverflow.com/a/9637807/824966
[UIView animateWithDuration:.25 animations:^{
scrollView.contentOffset = CGPointMake(0, maxContentOffset);
}];
}
}
#endif // !TARGET_OS_OSX
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
if(_onLoadingProgress){
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
_onLoadingProgress(event);
}
}else{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#if !TARGET_OS_OSX
- (void)setBackgroundColor:(UIColor *)backgroundColor
#else
- (void)setBackgroundColor:(RCTUIColor *)backgroundColor
#endif // !TARGET_OS_OSX
{
_savedBackgroundColor = backgroundColor;
if (_webView == nil) {
return;
}
CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
BOOL opaque = (alpha == 1.0);
#if !TARGET_OS_OSX
self.opaque = _webView.opaque = opaque;
_webView.scrollView.backgroundColor = backgroundColor;
_webView.backgroundColor = backgroundColor;
#else
// https://stackoverflow.com/questions/40007753/macos-wkwebview-background-transparency
NSOperatingSystemVersion version = { 10, 12, 0 };
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion:version]) {
[_webView setValue:@(opaque) forKey: @"drawsBackground"];
} else {
[_webView setValue:@(!opaque) forKey: @"drawsTransparentBackground"];
}
#endif // !TARGET_OS_OSX
}
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
- (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
{
_savedContentInsetAdjustmentBehavior = behavior;
if (_webView == nil) {
return;
}
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
CGPoint contentOffset = _webView.scrollView.contentOffset;
_webView.scrollView.contentInsetAdjustmentBehavior = behavior;
_webView.scrollView.contentOffset = contentOffset;
}
}
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 /* __IPHONE_13_0 */
- (void)setAutomaticallyAdjustsScrollIndicatorInsets:(BOOL)automaticallyAdjustsScrollIndicatorInsets{
_savedAutomaticallyAdjustsScrollIndicatorInsets = automaticallyAdjustsScrollIndicatorInsets;
if (_webView == nil) {
return;
}
if ([_webView.scrollView respondsToSelector:@selector(setAutomaticallyAdjustsScrollIndicatorInsets:)]) {
_webView.scrollView.automaticallyAdjustsScrollIndicatorInsets = automaticallyAdjustsScrollIndicatorInsets;
}
}
#endif
/**
* This method is called whenever JavaScript running within the web view calls:
* - window.webkit.messageHandlers[MessageHandlerName].postMessage
*/
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message
{
if ([message.name isEqualToString:HistoryShimName]) {
if (_onLoadingFinish) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{@"navigationType": message.body}];
_onLoadingFinish(event);
}
} else if ([message.name isEqualToString:MessageHandlerName]) {
if (_onMessage) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{@"data": message.body}];
_onMessage(event);
}
}
}
- (void)setSource:(NSDictionary *)source
{
if (![_source isEqualToDictionary:source]) {
_source = [source copy];
if (_webView != nil) {
[self visitSource];
}
}
}
- (void)setAllowingReadAccessToURL:(NSString *)allowingReadAccessToURL
{
if (![_allowingReadAccessToURL isEqualToString:allowingReadAccessToURL]) {
_allowingReadAccessToURL = [allowingReadAccessToURL copy];
if (_webView != nil) {
[self visitSource];
}
}
}
#if !TARGET_OS_OSX
- (void)setContentInset:(UIEdgeInsets)contentInset
{
_contentInset = contentInset;
[RCTView autoAdjustInsetsForView:self
withScrollView:_webView.scrollView
updateOffset:NO];
}
- (void)refreshContentInset
{
[RCTView autoAdjustInsetsForView:self
withScrollView:_webView.scrollView
updateOffset:YES];
}
#endif // !TARGET_OS_OSX
- (void)visitSource
{
// Check for a static html source first
NSString *html = [RCTConvert NSString:_source[@"html"]];
if (html) {
NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
if (!baseURL) {
baseURL = [NSURL URLWithString:@"about:blank"];
}
[_webView loadHTMLString:html baseURL:baseURL];
return;
}
// Add cookie for subsequent resource requests sent by page itself, if cookie was set in headers on WebView
NSString *headerCookie = [RCTConvert NSString:_source[@"headers"][@"cookie"]];
if(headerCookie) {
NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys:headerCookie,@"Set-Cookie",nil];
NSURL *urlString = [NSURL URLWithString:_source[@"uri"]];
NSArray *httpCookies = [NSHTTPCookie cookiesWithResponseHeaderFields:headers forURL:urlString];
[self writeCookiesToWebView:httpCookies completion:nil];
}
NSURLRequest *request = [self requestForSource:_source];
[self syncCookiesToWebView:^{
// Because of the way React works, as pages redirect, we actually end up
// passing the redirect urls back here, so we ignore them if trying to load
// the same url. We'll expose a call to 'reload' to allow a user to load
// the existing page.
if ([request.URL isEqual:_webView.URL]) {
return;
}
if (!request.URL) {
// Clear the webview
[_webView loadHTMLString:@"" baseURL:nil];
return;
}
if (request.URL.host) {
[_webView loadRequest:request];
}
else {
NSURL* readAccessUrl = _allowingReadAccessToURL ? [RCTConvert NSURL:_allowingReadAccessToURL] : request.URL;
[_webView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];
}
}];
}
#if !TARGET_OS_OSX
-(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
{
if (_webView == nil) {
_savedKeyboardDisplayRequiresUserAction = keyboardDisplayRequiresUserAction;
return;
}
if (_savedKeyboardDisplayRequiresUserAction == true) {
return;
}
UIView* subview;
for (UIView* view in _webView.scrollView.subviews) {
if([[view.class description] hasPrefix:@"WK"])
subview = view;
}
if(subview == nil) return;
Class class = subview.class;
NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
NSOperatingSystemVersion iOS_12_2_0 = (NSOperatingSystemVersion){12, 2, 0};
NSOperatingSystemVersion iOS_13_0_0 = (NSOperatingSystemVersion){13, 0, 0};
Method method;
IMP override;
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_13_0_0]) {
// iOS 13.0.0 - Future
SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:");
method = class_getInstanceMethod(class, selector);
IMP original = method_getImplementation(method);
override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
});
}
else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_12_2_0]) {
// iOS 12.2.0 - iOS 13.0.0
SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
method = class_getInstanceMethod(class, selector);
IMP original = method_getImplementation(method);
override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
});
}
else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
// iOS 11.3.0 - 12.2.0
SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
method = class_getInstanceMethod(class, selector);
IMP original = method_getImplementation(method);
override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
});
} else {
// iOS 9.0 - 11.3.0
SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
method = class_getInstanceMethod(class, selector);
IMP original = method_getImplementation(method);
override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {
((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);
});
}
method_setImplementation(method, override);
}
-(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
{
if (_webView == nil) {
_savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
return;
}
if (_savedHideKeyboardAccessoryView == false) {
return;
}
UIView* subview;
for (UIView* view in _webView.scrollView.subviews) {
if([[view.class description] hasPrefix:@"WK"])
subview = view;
}
if(subview == nil) return;
NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
Class newClass = NSClassFromString(name);
if(newClass == nil)
{
newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
if(!newClass) return;
Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
objc_registerClassPair(newClass);
}
object_setClass(subview, newClass);
}
// UIScrollViewDelegate method
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
scrollView.decelerationRate = _decelerationRate;
}
#endif // !TARGET_OS_OSX
- (void)setUserAgent:(NSString*)userAgent
{
_userAgent = userAgent;
_webView.customUserAgent = userAgent;
}
- (void)setScrollEnabled:(BOOL)scrollEnabled
{
_scrollEnabled = scrollEnabled;
#if !TARGET_OS_OSX
_webView.scrollView.scrollEnabled = scrollEnabled;
#endif // !TARGET_OS_OSX
}
#if !TARGET_OS_OSX
// UIScrollViewDelegate method
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
// Don't allow scrolling the scrollView.
if (!_scrollEnabled) {
scrollView.bounds = _webView.bounds;
}
else if (_onScroll != nil) {
NSDictionary *event = @{
@"contentOffset": @{
@"x": @(scrollView.contentOffset.x),
@"y": @(scrollView.contentOffset.y)
},
@"contentInset": @{
@"top": @(scrollView.contentInset.top),
@"left": @(scrollView.contentInset.left),
@"bottom": @(scrollView.contentInset.bottom),
@"right": @(scrollView.contentInset.right)
},
@"contentSize": @{
@"width": @(scrollView.contentSize.width),
@"height": @(scrollView.contentSize.height)
},
@"layoutMeasurement": @{
@"width": @(scrollView.frame.size.width),
@"height": @(scrollView.frame.size.height)
},
@"zoomScale": @(scrollView.zoomScale ?: 1),
};
_onScroll(event);
}
}
- (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
{
_directionalLockEnabled = directionalLockEnabled;
_webView.scrollView.directionalLockEnabled = directionalLockEnabled;
}
- (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
{
_showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
_webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
}
- (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
{
_showsVerticalScrollIndicator = showsVerticalScrollIndicator;
_webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
}
#endif // !TARGET_OS_OSX
- (void)postMessage:(NSString *)message
{
NSDictionary *eventInitDict = @{@"data": message};
NSString *source = [NSString
stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
RCTJSONStringify(eventInitDict, NULL)
];
[self injectJavaScript: source];
}
- (void)layoutSubviews
{
[super layoutSubviews];
// Ensure webview takes the position and dimensions of RNCWebView
_webView.frame = self.bounds;
#if !TARGET_OS_OSX
_webView.scrollView.contentInset = _contentInset;
#endif // !TARGET_OS_OSX
}
- (NSMutableDictionary<NSString *, id> *)baseEvent
{
NSDictionary *event = @{
@"url": _webView.URL.absoluteString ?: @"",
@"title": _webView.title ?: @"",
@"loading" : @(_webView.loading),
@"canGoBack": @(_webView.canGoBack),
@"canGoForward" : @(_webView.canGoForward)
};
return [[NSMutableDictionary alloc] initWithDictionary: event];
}
+ (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
clientAuthenticationCredential = credential;
}
+ (void)setCustomCertificatesForHost:(nullable NSDictionary*)certificates {
customCertificatesForHost = certificates;
}
- (void) webView:(WKWebView *)webView
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
{
NSString* host = nil;
if (webView.URL != nil) {
host = webView.URL.host;
}
if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
return;
}
if ([[challenge protectionSpace] serverTrust] != nil && customCertificatesForHost != nil && host != nil) {
SecCertificateRef localCertificate = (__bridge SecCertificateRef)([customCertificatesForHost objectForKey:host]);
if (localCertificate != nil) {
NSData *localCertificateData = (NSData*) CFBridgingRelease(SecCertificateCopyData(localCertificate));
SecTrustRef trust = [[challenge protectionSpace] serverTrust];
long count = SecTrustGetCertificateCount(trust);
for (long i = 0; i < count; i++) {
SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(trust, i);
if (serverCertificate == nil) { continue; }
NSData *serverCertificateData = (NSData *) CFBridgingRelease(SecCertificateCopyData(serverCertificate));
if ([serverCertificateData isEqualToData:localCertificateData]) {
NSURLCredential *useCredential = [NSURLCredential credentialForTrust:trust];
if (challenge.sender != nil) {
[challenge.sender useCredential:useCredential forAuthenticationChallenge:challenge];
}
completionHandler(NSURLSessionAuthChallengeUseCredential, useCredential);
return;
}
}
}
}
if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodHTTPBasic) {
NSString *username = [_basicAuthCredential valueForKey:@"username"];
NSString *password = [_basicAuthCredential valueForKey:@"password"];
if (username && password) {
NSURLCredential *credential = [NSURLCredential credentialWithUser:username password:password persistence:NSURLCredentialPersistenceNone];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
return;
}
}
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
#pragma mark - WKNavigationDelegate methods
/**
* alert
*/
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
#if !TARGET_OS_OSX
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {