forked from CRAlpha/react-native-wkwebview
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCRAWKWebView.m
More file actions
693 lines (599 loc) · 26.5 KB
/
CRAWKWebView.m
File metadata and controls
693 lines (599 loc) · 26.5 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
#import "CRAWKWebView.h"
#import "WeakScriptMessageDelegate.h"
#import <UIKit/UIKit.h>
#import <React/RCTAutoInsetsProtocol.h>
#import <React/RCTBridge.h>
#import <React/RCTConvert.h>
#import <React/RCTEventDispatcher.h>
#import <React/RCTLog.h>
#import <React/RCTUIManager.h>
#import <React/RCTUtils.h>
#import <React/RCTView.h>
#import <React/UIView+React.h>
#import <objc/runtime.h>
// runtime trick to remove or replace WKWebView keyboard default toolbar
// see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
@interface _SwizzleHelperWK : NSObject @end
@implementation _SwizzleHelperWK
-(id)inputAccessoryView
{
UIView *webView = (UIView *)self;
while (webView && ![webView isKindOfClass:[CRAWKWebView class]]) {
webView = webView.superview;
}
return webView.inputAccessoryView;
}
@end
@interface CRAWKWebView () <WKNavigationDelegate, RCTAutoInsetsProtocol, WKScriptMessageHandler, WKUIDelegate, UIScrollViewDelegate>
@property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
@property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
@property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
@property (nonatomic, copy) RCTDirectEventBlock onProgress;
@property (nonatomic, copy) RCTDirectEventBlock onMessage;
@property (nonatomic, copy) RCTDirectEventBlock onScroll;
@property (nonatomic, copy) RCTDirectEventBlock onNavigationResponse;
@property (assign) BOOL sendCookies;
@property (nonatomic, strong) WKUserScript *atStartScript;
@property (nonatomic, strong) WKUserScript *atEndScript;
@property (nonatomic, strong) UIView *inputAccessoryView;
@end
@implementation CRAWKWebView
{
WKWebView *_webView;
BOOL _injectJavaScriptForMainFrameOnly;
BOOL _injectedJavaScriptForMainFrameOnly;
NSString *_injectJavaScript;
NSString *_injectedJavaScript;
}
- (instancetype)initWithFrame:(CGRect)frame
{
return self = [super initWithFrame:frame];
}
RCT_NOT_IMPLEMENTED(- (instancetype)initWithCoder:(NSCoder *)aDecoder)
- (instancetype)initWithProcessPool:(WKProcessPool *)processPool
{
if(self = [self initWithFrame:CGRectZero])
{
super.backgroundColor = [UIColor clearColor];
_automaticallyAdjustContentInsets = YES;
_contentInset = UIEdgeInsetsZero;
WKWebViewConfiguration* config = [[WKWebViewConfiguration alloc] init];
config.processPool = processPool;
WKUserContentController* userController = [[WKUserContentController alloc]init];
[userController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"reactNative"];
config.userContentController = userController;
_webView = [[WKWebView alloc] initWithFrame:self.bounds configuration:config];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
_webView.scrollView.delegate = self;
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
// `contentInsetAdjustmentBehavior` is only available since iOS 11.
// We set the default behavior to "never" so that iOS
// doesn't do weird things to UIScrollView insets automatically
// and keeps it as an opt-in behavior.
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
#endif
[self setupPostMessageScript];
[_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
[self addSubview:_webView];
}
return self;
}
- (void)didSetProps:(NSArray<NSString *> *)changedProps
{
if ([changedProps containsObject:@"inputAccessoryViewID"] && self.inputAccessoryViewID) {
[self setCustomInputAccessoryViewWithNativeID:self.inputAccessoryViewID];
} else if (!self.inputAccessoryViewID) {
self.inputAccessoryView = nil;
}
}
- (void)didMoveToWindow
{
[super didMoveToWindow];
if (self.inputAccessoryViewID) {
[self setCustomInputAccessoryViewWithNativeID:self.inputAccessoryViewID];
}
}
- (void)setInjectJavaScript:(NSString *)injectJavaScript {
_injectJavaScript = injectJavaScript;
self.atStartScript = [[WKUserScript alloc] initWithSource:injectJavaScript
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:_injectJavaScriptForMainFrameOnly];
[self resetupScripts];
}
- (void)setInjectedJavaScript:(NSString *)script {
_injectedJavaScript = script;
self.atEndScript = [[WKUserScript alloc] initWithSource:script
injectionTime:WKUserScriptInjectionTimeAtDocumentEnd
forMainFrameOnly:_injectedJavaScriptForMainFrameOnly];
[self resetupScripts];
}
- (void)setInjectedJavaScriptForMainFrameOnly:(BOOL)injectedJavaScriptForMainFrameOnly {
_injectedJavaScriptForMainFrameOnly = injectedJavaScriptForMainFrameOnly;
if (_injectedJavaScript != nil) {
[self setInjectedJavaScript:_injectedJavaScript];
}
}
- (void)setInjectJavaScriptForMainFrameOnly:(BOOL)injectJavaScriptForMainFrameOnly {
_injectJavaScriptForMainFrameOnly = injectJavaScriptForMainFrameOnly;
if (_injectJavaScript != nil) {
[self setInjectJavaScript:_injectJavaScript];
}
}
- (void)setMessagingEnabled:(BOOL)messagingEnabled {
_messagingEnabled = messagingEnabled;
[self setupPostMessageScript];
}
- (void)resetupScripts {
[_webView.configuration.userContentController removeAllUserScripts];
[self setupPostMessageScript];
if (self.atStartScript) {
[_webView.configuration.userContentController addUserScript:self.atStartScript];
}
if (self.atEndScript) {
[_webView.configuration.userContentController addUserScript:self.atEndScript];
}
}
- (void)setupPostMessageScript {
if (_messagingEnabled) {
NSString *source = @"window.originalPostMessage = window.postMessage;"
"window.postMessage = function(message, targetOrigin, transfer) {"
"window.webkit.messageHandlers.reactNative.postMessage(message);"
"if (typeof targetOrigin !== 'undefined') {"
"window.originalPostMessage(message, targetOrigin, transfer);"
"}"
"};";
WKUserScript *script = [[WKUserScript alloc] initWithSource:source
injectionTime:WKUserScriptInjectionTimeAtDocumentStart
forMainFrameOnly:_injectedJavaScriptForMainFrameOnly];
[_webView.configuration.userContentController addUserScript:script];
}
}
- (void)loadRequest:(NSURLRequest *)request
{
if (request.URL && _sendCookies) {
NSDictionary *cookies = [NSHTTPCookie requestHeaderFieldsWithCookies:[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL]];
if ([cookies objectForKey:@"Cookie"]) {
NSMutableURLRequest *mutableRequest = request.mutableCopy;
[mutableRequest addValue:cookies[@"Cookie"] forHTTPHeaderField:@"Cookie"];
request = mutableRequest;
}
}
[_webView loadRequest:request];
}
-(void)setAllowsLinkPreview:(BOOL)allowsLinkPreview
{
if ([_webView respondsToSelector:@selector(allowsLinkPreview)]) {
_webView.allowsLinkPreview = allowsLinkPreview;
}
}
- (void)setCustomInputAccessoryViewWithNativeID:(NSString *)nativeID
{
#if !TARGET_OS_TV
UIView *accessoryView = [self _lookupViewForNativeID:nativeID inView:self.window];
// For backwards compatibility with React Native 0.55.4, use the content view.
if ([accessoryView respondsToSelector:@selector(content)]) {
accessoryView = [accessoryView valueForKey:@"content"];
}
if ([accessoryView respondsToSelector:@selector(inputAccessoryView)]) {
[self swizzleWebView];
self.inputAccessoryView = [accessoryView valueForKey:@"inputAccessoryView"];
}
#endif /* !TARGET_OS_TV */
}
// Recursively search the view hierarchy for a view matching the native ID
// copied from RCTUIManager.m
- (UIView *)_lookupViewForNativeID:(NSString *)nativeID inView:(UIView *)view
{
if (view != nil && [nativeID isEqualToString:view.nativeID]) {
return view;
}
for (UIView *subview in view.subviews) {
UIView *targetView = [self _lookupViewForNativeID:nativeID inView:subview];
if (targetView != nil) {
return targetView;
}
}
return nil;
}
-(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
{
[self swizzleWebView];
self.inputAccessoryView.hidden = hideKeyboardAccessoryView;
}
- (void)swizzleWebView
{
UIView* subview;
for (UIView* view in _webView.scrollView.subviews) {
if([[view.class description] hasPrefix:@"WKContent"])
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);
}
// https://github.com/Telerik-Verified-Plugins/WKWebView/commit/04e8296adeb61f289f9c698045c19b62d080c7e3
// https://stackoverflow.com/a/48623286/3297914
-(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
{
if (!keyboardDisplayRequiresUserAction) {
Class class = NSClassFromString(@"WKContentView");
NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
Method method = class_getInstanceMethod(class, selector);
IMP original = method_getImplementation(method);
IMP 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);
});
method_setImplementation(method, override);
} else {
SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
Method method = class_getInstanceMethod(class, selector);
IMP original = method_getImplementation(method);
IMP 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);
}
}
}
#if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
- (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
{
// `contentInsetAdjustmentBehavior` is available since iOS 11.
if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
CGPoint contentOffset = _webView.scrollView.contentOffset;
_webView.scrollView.contentInsetAdjustmentBehavior = behavior;
_webView.scrollView.contentOffset = contentOffset;
}
}
#endif
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
if (_onMessage) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{
@"data": message.body,
@"name": message.name
}];
_onMessage(event);
}
}
- (void)goForward
{
[_webView goForward];
}
- (void)evaluateJavaScript:(NSString *)javaScriptString
completionHandler:(void (^)(id, NSError *error))completionHandler
{
[_webView evaluateJavaScript:javaScriptString completionHandler:completionHandler];
}
- (void)postMessage:(NSString *)message
{
NSDictionary *eventInitDict = @{
@"data": message,
};
NSString *source = [NSString
stringWithFormat:@"document.dispatchEvent(new MessageEvent('message', %@));",
RCTJSONStringify(eventInitDict, NULL)
];
[_webView evaluateJavaScript:source completionHandler:nil];
}
- (void)goBack
{
[_webView goBack];
}
- (BOOL)canGoBack
{
return [_webView canGoBack];
}
- (BOOL)canGoForward
{
return [_webView canGoForward];
}
- (void)reload
{
[_webView reload];
}
- (void)stopLoading
{
[_webView stopLoading];
}
- (void)setSource:(NSDictionary *)source
{
if (![_source isEqualToDictionary:source]) {
_source = [source copy];
_sendCookies = [source[@"sendCookies"] boolValue];
if ([source[@"customUserAgent"] length] != 0 && [_webView respondsToSelector:@selector(setCustomUserAgent:)]) {
[_webView setCustomUserAgent:source[@"customUserAgent"]];
}
// Allow loading local files:
// <WKWebView source={{ file: RNFS.MainBundlePath + '/data/index.html', allowingReadAccessToURL: RNFS.MainBundlePath }} />
// Only works for iOS 9+. So iOS 8 will simply ignore those two values
NSString *file = [RCTConvert NSString:source[@"file"]];
NSString *allowingReadAccessToURL = [RCTConvert NSString:source[@"allowingReadAccessToURL"]];
if (file && [_webView respondsToSelector:@selector(loadFileURL:allowingReadAccessToURL:)]) {
NSURL *fileURL = [RCTConvert NSURL:file];
NSURL *baseURL = [RCTConvert NSURL:allowingReadAccessToURL];
[_webView loadFileURL:fileURL allowingReadAccessToURL:baseURL];
return;
}
// 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;
}
NSURLRequest *request = [RCTConvert NSURLRequest:source];
// 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;
}
[self loadRequest:request];
}
}
- (void)layoutSubviews
{
[super layoutSubviews];
_webView.frame = self.bounds;
}
- (void)setContentInset:(UIEdgeInsets)contentInset
{
_contentInset = contentInset;
[RCTView autoAdjustInsetsForView:self
withScrollView:_webView.scrollView
updateOffset:NO];
}
- (void)setBackgroundColor:(UIColor *)backgroundColor
{
CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
self.opaque = _webView.opaque = _webView.scrollView.opaque = (alpha == 1.0);
_webView.backgroundColor = _webView.scrollView.backgroundColor = backgroundColor;
}
- (UIColor *)backgroundColor
{
return _webView.backgroundColor;
}
- (NSMutableDictionary<NSString *, id> *)baseEvent
{
NSMutableDictionary<NSString *, id> *event = [[NSMutableDictionary alloc] initWithDictionary:@{
@"url": _webView.URL.absoluteString ?: @"",
@"loading" : @(_webView.loading),
@"title": _webView.title,
@"canGoBack": @(_webView.canGoBack),
@"canGoForward" : @(_webView.canGoForward),
}];
return event;
}
- (void)refreshContentInset
{
[RCTView autoAdjustInsetsForView:self
withScrollView:_webView.scrollView
updateOffset:YES];
}
- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary *)change
context:(void *)context
{
if ([keyPath isEqualToString:@"estimatedProgress"]) {
if (!_onProgress) {
return;
}
_onProgress(@{@"progress": [change objectForKey:NSKeyValueChangeNewKey]});
}
}
- (void)dealloc
{
[_webView removeObserver:self forKeyPath:@"estimatedProgress"];
_webView.navigationDelegate = nil;
_webView.UIDelegate = nil;
_webView.scrollView.delegate = nil;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
if (!scrollView.scrollEnabled) {
scrollView.bounds = _webView.bounds;
return;
}
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);
}
#pragma mark - WKNavigationDelegate methods
#if DEBUG
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler {
NSURLCredential * credential = [[NSURLCredential alloc] initWithTrust:[challenge protectionSpace].serverTrust];
completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
}
#endif
- (void)webView:(__unused WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
UIApplication *app = [UIApplication sharedApplication];
NSURLRequest *request = navigationAction.request;
NSURL* url = request.URL;
NSString* scheme = url.scheme;
BOOL isJSNavigation = [scheme isEqualToString:RCTJSNavigationScheme];
// handle mailto and tel schemes
if ([scheme isEqualToString:@"mailto"] || [scheme isEqualToString:@"tel"]) {
if ([app canOpenURL:url]) {
[app openURL:url];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
}
// skip this for the JS Navigation handler
if (!isJSNavigation && _onShouldStartLoadWithRequest) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{
@"url": (request.URL).absoluteString,
@"navigationType": @(navigationAction.navigationType)
}];
if (![self.delegate webView:self
shouldStartLoadForRequest:event
withCallback:_onShouldStartLoadWithRequest]) {
return decisionHandler(WKNavigationActionPolicyCancel);
}
}
if (_onLoadingStart) {
// We have this check to filter out iframe requests and whatnot
BOOL isTopFrame = [url isEqual:request.mainDocumentURL];
if (isTopFrame) {
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary: @{
@"url": url.absoluteString,
@"navigationType": @(navigationAction.navigationType)
}];
_onLoadingStart(event);
}
}
if (isJSNavigation) {
decisionHandler(WKNavigationActionPolicyCancel);
}
else {
decisionHandler(WKNavigationActionPolicyAllow);
}
}
- (void)webView:(__unused WKWebView *)webView didFailProvisionalNavigation:(__unused WKNavigation *)navigation withError:(NSError *)error
{
if (_onLoadingError) {
if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
// NSURLErrorCancelled is reported when a page has a redirect OR if you load
// a new URL in the WebView before the previous one came back. We can just
// ignore these since they aren't real errors.
// http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
return;
}
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary:@{
@"domain": error.domain,
@"code": @(error.code),
@"description": error.localizedDescription,
}];
_onLoadingError(event);
}
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(__unused WKNavigation *)navigation
{
// we only need the final 'finishLoad' call so only fire the event when we're actually done loading.
if (_onLoadingFinish && !webView.loading && ![webView.URL.absoluteString isEqualToString:@"about:blank"]) {
_onLoadingFinish([self baseEvent]);
}
}
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Close", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
completionHandler();
}]];
UIViewController *presentingController = RCTPresentedViewController();
[presentingController presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler {
// TODO We have to think message to confirm "YES"
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:message message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
completionHandler(YES);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
completionHandler(NO);
}]];
UIViewController *presentingController = RCTPresentedViewController();
[presentingController presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler {
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:nil preferredStyle:UIAlertControllerStyleAlert];
[alertController addTextFieldWithConfigurationHandler:^(UITextField *textField) {
textField.text = defaultText;
}];
[alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"OK", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
NSString *input = ((UITextField *)alertController.textFields.firstObject).text;
completionHandler(input);
}]];
[alertController addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
completionHandler(nil);
}]];
UIViewController *presentingController = RCTPresentedViewController();
[presentingController presentViewController:alertController animated:YES completion:nil];
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
NSString *scheme = navigationAction.request.URL.scheme;
if ((navigationAction.targetFrame.isMainFrame || _openNewWindowInWebView) && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"])) {
[webView loadRequest:navigationAction.request];
} else {
UIApplication *app = [UIApplication sharedApplication];
NSURL *url = navigationAction.request.URL;
if ([app canOpenURL:url]) {
[app openURL:url];
}
}
return nil;
}
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
{
RCTLogWarn(@"Webview Process Terminated");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
if (_onNavigationResponse) {
NSDictionary *headers = @{};
NSInteger statusCode = 200;
if([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]){
headers = ((NSHTTPURLResponse *)navigationResponse.response).allHeaderFields;
statusCode = ((NSHTTPURLResponse *)navigationResponse.response).statusCode;
}
NSMutableDictionary<NSString *, id> *event = [self baseEvent];
[event addEntriesFromDictionary:@{
@"headers": headers,
@"status": [NSHTTPURLResponse localizedStringForStatusCode:statusCode],
@"statusCode": @(statusCode),
}];
_onNavigationResponse(event);
}
decisionHandler(WKNavigationResponsePolicyAllow);
}
@end