forked from react-native-webview/react-native-webview
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathRNCWebViewImpl.m
More file actions
2232 lines (1999 loc) · 85.6 KB
/
RNCWebViewImpl.m
File metadata and controls
2232 lines (1999 loc) · 85.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) 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 "RNCWebViewImpl.h"
#import <React/RCTConvert.h>
#import <React/RCTAutoInsetsProtocol.h>
#import "RNCWKProcessPoolManager.h"
#import "IFrameDetector.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_IOS
// 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_IOS
@interface RNCWKWebView : WKWebView
#if !TARGET_OS_OSX
@property (nonatomic, copy) NSArray<NSDictionary *> * _Nullable menuItems;
@property (nonatomic, copy) NSArray<NSString *> * _Nullable suppressMenuItems;
#endif // !TARGET_OS_OSX
@end
@implementation RNCWKWebView
#if !TARGET_OS_OSX
- (NSString *)stringFromAction:(SEL) action {
NSString *sel = NSStringFromSelector(action);
NSDictionary *map = @{
@"cut:": @"cut",
@"copy:": @"copy",
@"paste:": @"paste",
@"delete:": @"delete",
@"select:": @"select",
@"selectAll:": @"selectAll",
@"_promptForReplace:": @"replace",
@"_define:": @"lookup",
@"_translate:": @"translate",
@"toggleBoldface:": @"bold",
@"toggleItalics:": @"italic",
@"toggleUnderline:": @"underline",
@"_share:": @"share",
};
return map[sel] ?: sel;
}
- (BOOL)canPerformAction:(SEL)action
withSender:(id)sender{
if(self.suppressMenuItems) {
NSString * sel = [self stringFromAction:action];
if ([self.suppressMenuItems containsObject: sel]) {
return NO;
}
}
if (!self.menuItems) {
return [super canPerformAction:action withSender:sender];
}
return NO;
}
- (void)buildMenuWithBuilder:(id<UIMenuBuilder>)builder API_AVAILABLE(ios(13.0)) {
if (@available(iOS 16.0, *)) {
if(self.menuItems){
[builder removeMenuForIdentifier:UIMenuLookup];
}
}
[super buildMenuWithBuilder:builder];
}
#else // TARGET_OS_OSX
- (void)scrollWheel:(NSEvent *)theEvent {
RNCWebViewImpl *rncWebView = (RNCWebViewImpl *)[self superview];
RCTAssert([rncWebView isKindOfClass:[rncWebView class]], @"superview must be an RNCWebViewImpl");
if (![rncWebView scrollEnabled]) {
[[self nextResponder] scrollWheel:theEvent];
return;
}
[super scrollWheel:theEvent];
}
#endif // TARGET_OS_OSX
@end
@interface RNCWebViewImpl () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, WKHTTPCookieStoreObserver,
#if !TARGET_OS_OSX
UIScrollViewDelegate,
UIGestureRecognizerDelegate,
#endif // !TARGET_OS_OSX
RCTAutoInsetsProtocol>
@property (nonatomic, copy) RNCWKWebView *webView;
@property (nonatomic, strong) WKUserScript *postMessageScript;
@property (nonatomic, strong) WKUserScript *injectedObjectJsonScript;
@property (nonatomic, strong) WKUserScript *atStartScript;
@property (nonatomic, strong) WKUserScript *atEndScript;
@property (nonatomic, strong) WKUserScript *iframeDetectorScript;
@end
@implementation RNCWebViewImpl
{
#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;
//Disables the display of prompts during site navigation/loading
BOOL _disablePromptDuringLoading;
#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;
_javaScriptEnabled = YES;
_allowsLinkPreview = YES;
_showsVerticalScrollIndicator = YES;
_directionalLockEnabled = YES;
_useSharedProcessPool = YES;
_cacheEnabled = YES;
_mediaPlaybackRequiresUserAction = YES;
_automaticallyAdjustContentInsets = YES;
_autoManageStatusBarEnabled = YES;
_contentInset = UIEdgeInsetsZero;
_savedKeyboardDisplayRequiresUserAction = YES;
_injectedJavaScript = nil;
_injectedJavaScriptForMainFrameOnly = YES;
_injectedJavaScriptBeforeContentLoaded = nil;
_injectedJavaScriptBeforeContentLoadedForMainFrameOnly = YES;
_disablePromptDuringLoading = YES;
_enableApplePay = NO;
self.iframeDetectorScript = [[WKUserScript alloc] initWithSource:getIFrameDetectorScript()
injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
forMainFrameOnly:NO];
#if TARGET_OS_IOS
_savedStatusBarStyle = RCTSharedApplication().statusBarStyle;
_savedStatusBarHidden = RCTSharedApplication().statusBarHidden;
#endif // TARGET_OS_IOS
#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;
_fraudulentWebsiteWarningEnabled = YES;
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 140500 /* __IPHONE_13_0 */
_textInteractionEnabled = YES;
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 150000 /* iOS 15 */
_mediaCapturePermissionGrantType = RNCWebViewPermissionGrantType_Prompt;
#endif
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 160000 /* iOS 15 */
if (@available(iOS 16.0, *)) {
_editMenuInteraction = [[UIEditMenuInteraction alloc] initWithDelegate:self];
[self addInteraction:_editMenuInteraction];
}
#endif
}
#if TARGET_OS_IOS
[[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_IOS
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
{
if (pressSender.state != UIGestureRecognizerStateEnded || !self.menuItems) {
return;
}
if (@available(iOS 16.0, *)) {
CGPoint location = [pressSender locationInView:self];
UIEditMenuConfiguration *config = [UIEditMenuConfiguration configurationWithIdentifier:nil sourcePoint:location];
[_editMenuInteraction presentEditMenuWithConfiguration:config];
} else {
// When a long press ends, bring up our custom UIMenu if defined
if (self.menuItems.count == 0) {
UIMenuController *menuController = [UIMenuController sharedMenuController];
menuController.menuItems = nil;
[menuController showMenuFromView:self rect:self.bounds];
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 showMenuFromView:self rect:self.bounds];
}
}
- (UIMenu *)editMenuInteraction:(UIEditMenuInteraction *)interaction menuForConfiguration:(UIEditMenuConfiguration *)configuration suggestedActions:(NSArray<UIMenuElement *> *)suggestedActions API_AVAILABLE(ios(16.0))
{
NSMutableArray<UICommand *> *menuItems = [NSMutableArray new];
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];
UICommand *command = [UICommand commandWithTitle:menuItemLabel
image:nil
action:NSSelectorFromString(sel)
propertyList:nil];
[menuItems addObject:command];
}
UIMenu *menu = [UIMenu menuWithChildren:menuItems];
return menu;
}
#endif // !TARGET_OS_OSX
- (void)dealloc
{
[[NSNotificationCenter defaultCenter] removeObserver:self];
if (@available(iOS 11.0, *)) {
[self.webView.configuration.websiteDataStore.httpCookieStore 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) {
NSURL *url = navigationAction.request.URL;
if (_onOpenWindow) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{@"targetUrl": url.absoluteString}];
_onOpenWindow(event);
} else {
[webView loadRequest:navigationAction.request];
}
}
return nil;
}
/**
* Enables file input on macos, see https://developer.apple.com/documentation/webkit/wkuidelegate/1641952-webview
*/
#if TARGET_OS_OSX
- (void)webView:(WKWebView *)webView runOpenPanelWithParameters:(WKOpenPanelParameters *)parameters initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSArray<NSURL *> *URLs))completionHandler
{
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
openPanel.allowsMultipleSelection = parameters.allowsMultipleSelection;
[openPanel beginSheetModalForWindow:webView.window completionHandler:^(NSInteger result) {
if (result == NSModalResponseOK)
completionHandler(openPanel.URLs);
else
completionHandler(nil);
}];
}
#endif //Target_OS_OSX
- (WKWebViewConfiguration *)setUpWkWebViewConfig
{
WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
WKPreferences *prefs = [[WKPreferences alloc]init];
BOOL _prefsUsed = NO;
if (!_javaScriptEnabled) {
prefs.javaScriptEnabled = NO;
_prefsUsed = YES;
}
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 130000 /* iOS 13 */
if (@available(iOS 13.0, *)) {
if (!_fraudulentWebsiteWarningEnabled) {
prefs.fraudulentWebsiteWarningEnabled = NO;
_prefsUsed = YES;
}
}
#endif
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] sharedProcessPool];
}
wkWebViewConfig.userContentController = [WKUserContentController new];
[wkWebViewConfig.userContentController addScriptMessageHandler:self name:@"base64Handler"];
#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;
wkWebViewConfig.allowsPictureInPictureMediaPlayback = _allowsPictureInPictureMediaPlayback;
wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
? WKAudiovisualMediaTypeAll
: WKAudiovisualMediaTypeNone;
wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
#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];
_webView = [[RNCWKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
[self setBackgroundColor: _savedBackgroundColor];
#if !TARGET_OS_OSX
_webView.menuItems = _menuItems;
_webView.suppressMenuItems = _suppressMenuItems;
_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 !TARGET_OS_OSX
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
_webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
}
#endif // !TARGET_OS_OSX
#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
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130300 || \
__IPHONE_OS_VERSION_MAX_ALLOWED >= 160400 || \
__TV_OS_VERSION_MAX_ALLOWED >= 160400
if (@available(macOS 13.3, iOS 16.4, tvOS 16.4, *))
_webView.inspectable = _webviewDebuggingEnabled;
#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;
}
#if __MAC_OS_X_VERSION_MAX_ALLOWED >= 130300 || \
__IPHONE_OS_VERSION_MAX_ALLOWED >= 160400 || \
__TV_OS_VERSION_MAX_ALLOWED >= 160400
- (void)setWebviewDebuggingEnabled:(BOOL)webviewDebuggingEnabled {
_webviewDebuggingEnabled = webviewDebuggingEnabled;
if (@available(macOS 13.3, iOS 16.4, tvOS 16.4, *))
_webView.inspectable = _webviewDebuggingEnabled;
}
#endif
#ifdef RCT_NEW_ARCH_ENABLED
- (void)destroyWebView
#else
- (void)removeFromSuperview
#endif
{
if (_webView) {
[_webView.configuration.userContentController removeScriptMessageHandlerForName:HistoryShimName];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
[_webView removeObserver:self forKeyPath:@"estimatedProgress"];
[_webView removeFromSuperview];
if (@available(iOS 15.0, macOS 12.0, *)) {
[_webView pauseAllMediaPlaybackWithCompletionHandler:nil];
} else if (@available(iOS 14.5, macOS 11.3, *)) {
[_webView suspendAllMediaPlayback:nil];
}
#if !TARGET_OS_OSX
_webView.scrollView.delegate = nil;
if (_menuItems) {
UIMenuController *menuController = [UIMenuController sharedMenuController];
menuController.menuItems = nil;
}
#endif // !TARGET_OS_OSX
_webView = nil;
if (_onContentProcessDidTerminate) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
_onContentProcessDidTerminate(event);
}
}
#ifndef RCT_NEW_ARCH_ENABLED
[super removeFromSuperview];
#endif
}
#if TARGET_OS_IOS
-(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_IOS
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
if(_onLoadingProgress){
_disablePromptDuringLoading = YES;
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 !TARGET_OS_OSX
- (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 // !TARGET_OS_OSX
#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:@"base64Handler"]) {
NSString *base64String = message.body;
[self downloadBase64File:base64String];
} else if ([message.name isEqualToString:HistoryShimName]) {
if (_onLoadingFinish) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{@"navigationType": message.body}];
_onLoadingFinish(event);
_disablePromptDuringLoading = NO;
}
} else if ([message.name isEqualToString:MessageHandlerName]) {
if (_onMessage && message.frameInfo.mainFrame) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{@"data": message.body}];
[event addEntriesFromDictionary: @{@"url": message.frameInfo.request.URL.absoluteString}];
_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];
}
}
}
- (void)setContentInset:(UIEdgeInsets)contentInset
{
#if !TARGET_OS_OSX
_contentInset = contentInset;
[RCTView autoAdjustInsetsForView:self
withScrollView:_webView.scrollView
updateOffset:NO];
#endif // !TARGET_OS_OSX
}
- (void)refreshContentInset
{
#if !TARGET_OS_OSX
[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];
__weak WKWebView *webView = _webView;
NSString *allowingReadAccessToURL = _allowingReadAccessToURL;
[self syncCookiesToWebView:^{
// Add observer to sync cookies from webview to sharedHTTPCookieStorage
[webView.configuration.websiteDataStore.httpCookieStore addObserver:self];
// 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)setMenuItems:(NSArray<NSDictionary *> *)menuItems {
_menuItems = menuItems;
_webView.menuItems = menuItems;
}
-(void)setSuppressMenuItems:(NSArray<NSString *> *)suppressMenuItems {
_suppressMenuItems = suppressMenuItems;
_webView.suppressMenuItems = suppressMenuItems;
}
#if TARGET_OS_IOS
-(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
{
_keyboardDisplayRequiresUserAction = 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, __unused 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, __unused 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, __unused 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, __unused 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)downloadBase64File:(NSString *)base64String {
NSArray *components = [base64String componentsSeparatedByString:@","];
NSString *base64ContentPart = components.lastObject;
NSData *fileData = [[NSData alloc] initWithBase64EncodedString:base64ContentPart options:NSDataBase64DecodingIgnoreUnknownCharacters];
NSString *fileExtension = [self fileExtensionFromBase64String:base64String];
[self showDownloadAlert:fileExtension invokeDownload:^{
NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"File.%@", fileExtension]];
[fileData writeToFile:tempFilePath atomically:YES];
NSURL *tempFileURL = [NSURL fileURLWithPath:tempFilePath];
UIDocumentPickerViewController *documentPicker = nil;
if (@available(iOS 14.0, *)) {
documentPicker = [[UIDocumentPickerViewController alloc] initForExportingURLs:@[tempFileURL] asCopy:YES];
} else {
// Usage of initWithURL:inMode: might lose file's extension and user has to type it manually
// Problem was solved for iOS 14 and higher with initForExportingURLs
documentPicker = [[UIDocumentPickerViewController alloc] initWithURL:tempFileURL inMode:UIDocumentPickerModeExportToService];
}
documentPicker.delegate = self;
documentPicker.modalPresentationStyle = UIModalPresentationFullScreen;
UIViewController *rootViewController = [UIApplication sharedApplication].keyWindow.rootViewController;
while (rootViewController.presentedViewController) {
rootViewController = rootViewController.presentedViewController;