react-native-webview.git

RNCWKWebView.m 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663
  1. /**
  2. * Copyright (c) 2015-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. */
  7. #import "RNCWKWebView.h"
  8. #import <React/RCTConvert.h>
  9. #import <React/RCTAutoInsetsProtocol.h>
  10. #import "RNCWKProcessPoolManager.h"
  11. #import <UIKit/UIKit.h>
  12. #import "objc/runtime.h"
  13. static NSTimer *keyboardTimer;
  14. static NSString *const MessageHandlerName = @"ReactNativeWebView";
  15. static NSURLCredential* clientAuthenticationCredential;
  16. // runtime trick to remove WKWebView keyboard default toolbar
  17. // see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
  18. @interface _SwizzleHelperWK : NSObject @end
  19. @implementation _SwizzleHelperWK
  20. -(id)inputAccessoryView
  21. {
  22. return nil;
  23. }
  24. @end
  25. @interface RNCWKWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIScrollViewDelegate, RCTAutoInsetsProtocol>
  26. @property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
  27. @property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
  28. @property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
  29. @property (nonatomic, copy) RCTDirectEventBlock onLoadingProgress;
  30. @property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
  31. @property (nonatomic, copy) RCTDirectEventBlock onMessage;
  32. @property (nonatomic, copy) WKWebView *webView;
  33. @end
  34. @implementation RNCWKWebView
  35. {
  36. UIColor * _savedBackgroundColor;
  37. BOOL _savedHideKeyboardAccessoryView;
  38. }
  39. - (instancetype)initWithFrame:(CGRect)frame
  40. {
  41. if ((self = [super initWithFrame:frame])) {
  42. super.backgroundColor = [UIColor clearColor];
  43. _bounces = YES;
  44. _scrollEnabled = YES;
  45. _showsHorizontalScrollIndicator = YES;
  46. _showsVerticalScrollIndicator = YES;
  47. _automaticallyAdjustContentInsets = YES;
  48. _contentInset = UIEdgeInsetsZero;
  49. }
  50. // Workaround for a keyboard dismissal bug present in iOS 12
  51. // https://openradar.appspot.com/radar?id=5018321736957952
  52. if (@available(iOS 12.0, *)) {
  53. [[NSNotificationCenter defaultCenter]
  54. addObserver:self
  55. selector:@selector(keyboardWillHide)
  56. name:UIKeyboardWillHideNotification object:nil];
  57. [[NSNotificationCenter defaultCenter]
  58. addObserver:self
  59. selector:@selector(keyboardWillShow)
  60. name:UIKeyboardWillShowNotification object:nil];
  61. }
  62. return self;
  63. }
  64. - (void)dealloc
  65. {
  66. [[NSNotificationCenter defaultCenter] removeObserver:self];
  67. }
  68. /**
  69. * See https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank/25853806#25853806 for details.
  70. */
  71. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
  72. {
  73. if (!navigationAction.targetFrame.isMainFrame) {
  74. [webView loadRequest:navigationAction.request];
  75. }
  76. return nil;
  77. }
  78. - (void)didMoveToWindow
  79. {
  80. if (self.window != nil && _webView == nil) {
  81. WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
  82. if (_incognito) {
  83. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  84. } else if (_cacheEnabled) {
  85. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  86. }
  87. if(self.useSharedProcessPool) {
  88. wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPool];
  89. }
  90. wkWebViewConfig.userContentController = [WKUserContentController new];
  91. if (_messagingEnabled) {
  92. [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
  93. NSString *source = [NSString stringWithFormat:
  94. @"window.%@ = {"
  95. " postMessage: function (data) {"
  96. " window.webkit.messageHandlers.%@.postMessage(String(data));"
  97. " }"
  98. "};", MessageHandlerName, MessageHandlerName
  99. ];
  100. WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  101. [wkWebViewConfig.userContentController addUserScript:script];
  102. }
  103. wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
  104. #if WEBKIT_IOS_10_APIS_AVAILABLE
  105. wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
  106. ? WKAudiovisualMediaTypeAll
  107. : WKAudiovisualMediaTypeNone;
  108. wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
  109. #else
  110. wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
  111. #endif
  112. _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
  113. _webView.scrollView.delegate = self;
  114. _webView.UIDelegate = self;
  115. _webView.navigationDelegate = self;
  116. _webView.scrollView.scrollEnabled = _scrollEnabled;
  117. _webView.scrollView.pagingEnabled = _pagingEnabled;
  118. _webView.scrollView.bounces = _bounces;
  119. _webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
  120. _webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
  121. _webView.allowsLinkPreview = _allowsLinkPreview;
  122. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  123. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  124. if (_userAgent) {
  125. _webView.customUserAgent = _userAgent;
  126. }
  127. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  128. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  129. _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  130. }
  131. #endif
  132. [self addSubview:_webView];
  133. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  134. [self visitSource];
  135. }
  136. }
  137. // Update webview property when the component prop changes.
  138. - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
  139. _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
  140. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  141. }
  142. - (void)removeFromSuperview
  143. {
  144. if (_webView) {
  145. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  146. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  147. [_webView removeFromSuperview];
  148. _webView.scrollView.delegate = nil;
  149. _webView = nil;
  150. }
  151. [super removeFromSuperview];
  152. }
  153. -(void)keyboardWillHide
  154. {
  155. keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
  156. [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
  157. }
  158. -(void)keyboardWillShow
  159. {
  160. if (keyboardTimer != nil) {
  161. [keyboardTimer invalidate];
  162. }
  163. }
  164. -(void)keyboardDisplacementFix
  165. {
  166. // Additional viewport checks to prevent unintentional scrolls
  167. UIScrollView *scrollView = self.webView.scrollView;
  168. double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  169. if (maxContentOffset < 0) {
  170. maxContentOffset = 0;
  171. }
  172. if (scrollView.contentOffset.y > maxContentOffset) {
  173. // https://stackoverflow.com/a/9637807/824966
  174. [UIView animateWithDuration:.25 animations:^{
  175. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  176. }];
  177. }
  178. }
  179. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  180. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  181. if(_onLoadingProgress){
  182. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  183. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  184. _onLoadingProgress(event);
  185. }
  186. }else{
  187. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  188. }
  189. }
  190. - (void)setBackgroundColor:(UIColor *)backgroundColor
  191. {
  192. _savedBackgroundColor = backgroundColor;
  193. if (_webView == nil) {
  194. return;
  195. }
  196. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  197. self.opaque = _webView.opaque = (alpha == 1.0);
  198. _webView.scrollView.backgroundColor = backgroundColor;
  199. _webView.backgroundColor = backgroundColor;
  200. }
  201. /**
  202. * This method is called whenever JavaScript running within the web view calls:
  203. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  204. */
  205. - (void)userContentController:(WKUserContentController *)userContentController
  206. didReceiveScriptMessage:(WKScriptMessage *)message
  207. {
  208. if (_onMessage != nil) {
  209. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  210. [event addEntriesFromDictionary: @{@"data": message.body}];
  211. _onMessage(event);
  212. }
  213. }
  214. - (void)setSource:(NSDictionary *)source
  215. {
  216. if (![_source isEqualToDictionary:source]) {
  217. _source = [source copy];
  218. if (_webView != nil) {
  219. [self visitSource];
  220. }
  221. }
  222. }
  223. - (void)setContentInset:(UIEdgeInsets)contentInset
  224. {
  225. _contentInset = contentInset;
  226. [RCTView autoAdjustInsetsForView:self
  227. withScrollView:_webView.scrollView
  228. updateOffset:NO];
  229. }
  230. - (void)refreshContentInset
  231. {
  232. [RCTView autoAdjustInsetsForView:self
  233. withScrollView:_webView.scrollView
  234. updateOffset:YES];
  235. }
  236. - (void)visitSource
  237. {
  238. // Check for a static html source first
  239. NSString *html = [RCTConvert NSString:_source[@"html"]];
  240. if (html) {
  241. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  242. if (!baseURL) {
  243. baseURL = [NSURL URLWithString:@"about:blank"];
  244. }
  245. [_webView loadHTMLString:html baseURL:baseURL];
  246. return;
  247. }
  248. NSURLRequest *request = [RCTConvert NSURLRequest:_source];
  249. // Because of the way React works, as pages redirect, we actually end up
  250. // passing the redirect urls back here, so we ignore them if trying to load
  251. // the same url. We'll expose a call to 'reload' to allow a user to load
  252. // the existing page.
  253. if ([request.URL isEqual:_webView.URL]) {
  254. return;
  255. }
  256. if (!request.URL) {
  257. // Clear the webview
  258. [_webView loadHTMLString:@"" baseURL:nil];
  259. return;
  260. }
  261. [_webView loadRequest:request];
  262. }
  263. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  264. {
  265. if (_webView == nil) {
  266. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  267. return;
  268. }
  269. if (_savedHideKeyboardAccessoryView == false) {
  270. return;
  271. }
  272. UIView* subview;
  273. for (UIView* view in _webView.scrollView.subviews) {
  274. if([[view.class description] hasPrefix:@"WK"])
  275. subview = view;
  276. }
  277. if(subview == nil) return;
  278. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  279. Class newClass = NSClassFromString(name);
  280. if(newClass == nil)
  281. {
  282. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  283. if(!newClass) return;
  284. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  285. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  286. objc_registerClassPair(newClass);
  287. }
  288. object_setClass(subview, newClass);
  289. }
  290. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  291. {
  292. scrollView.decelerationRate = _decelerationRate;
  293. }
  294. - (void)setScrollEnabled:(BOOL)scrollEnabled
  295. {
  296. _scrollEnabled = scrollEnabled;
  297. _webView.scrollView.scrollEnabled = scrollEnabled;
  298. }
  299. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  300. {
  301. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  302. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  303. }
  304. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  305. {
  306. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  307. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  308. }
  309. - (void)postMessage:(NSString *)message
  310. {
  311. NSDictionary *eventInitDict = @{@"data": message};
  312. NSString *source = [NSString
  313. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  314. RCTJSONStringify(eventInitDict, NULL)
  315. ];
  316. [self injectJavaScript: source];
  317. }
  318. - (void)layoutSubviews
  319. {
  320. [super layoutSubviews];
  321. // Ensure webview takes the position and dimensions of RNCWKWebView
  322. _webView.frame = self.bounds;
  323. }
  324. - (NSMutableDictionary<NSString *, id> *)baseEvent
  325. {
  326. NSDictionary *event = @{
  327. @"url": _webView.URL.absoluteString ?: @"",
  328. @"title": _webView.title,
  329. @"loading" : @(_webView.loading),
  330. @"canGoBack": @(_webView.canGoBack),
  331. @"canGoForward" : @(_webView.canGoForward)
  332. };
  333. return [[NSMutableDictionary alloc] initWithDictionary: event];
  334. }
  335. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  336. clientAuthenticationCredential = credential;
  337. }
  338. - (void) webView:(WKWebView *)webView
  339. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  340. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  341. {
  342. if (!clientAuthenticationCredential) {
  343. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  344. return;
  345. }
  346. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  347. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  348. } else {
  349. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  350. }
  351. }
  352. #pragma mark - WKNavigationDelegate methods
  353. /**
  354. * alert
  355. */
  356. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  357. {
  358. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  359. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  360. completionHandler();
  361. }]];
  362. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  363. }
  364. /**
  365. * confirm
  366. */
  367. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  368. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  369. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  370. completionHandler(YES);
  371. }]];
  372. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  373. completionHandler(NO);
  374. }]];
  375. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  376. }
  377. /**
  378. * prompt
  379. */
  380. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  381. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  382. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  383. textField.textColor = [UIColor lightGrayColor];
  384. textField.placeholder = defaultText;
  385. }];
  386. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  387. completionHandler([[alert.textFields lastObject] text]);
  388. }]];
  389. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  390. }
  391. /**
  392. * topViewController
  393. */
  394. -(UIViewController *)topViewController{
  395.    UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  396.    return controller;
  397. }
  398. /**
  399. * topViewControllerWithRootViewController
  400. */
  401. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  402. if (viewController==nil) return nil;
  403. if (viewController.presentedViewController!=nil) {
  404. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  405. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  406. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  407. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  408. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  409. } else {
  410. return viewController;
  411. }
  412. }
  413. /**
  414. * getCurrentWindow
  415. */
  416. -(UIWindow *)getCurrentWindow{
  417. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  418. if (window.windowLevel!=UIWindowLevelNormal) {
  419. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  420. if (window.windowLevel==UIWindowLevelNormal) {
  421. window = wid;
  422. break;
  423. }
  424. }
  425. }
  426. return window;
  427. }
  428. /**
  429. * Decides whether to allow or cancel a navigation.
  430. * @see https://fburl.com/42r9fxob
  431. */
  432. - (void) webView:(WKWebView *)webView
  433. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  434. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  435. {
  436. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  437. static dispatch_once_t onceToken;
  438. dispatch_once(&onceToken, ^{
  439. navigationTypes = @{
  440. @(WKNavigationTypeLinkActivated): @"click",
  441. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  442. @(WKNavigationTypeBackForward): @"backforward",
  443. @(WKNavigationTypeReload): @"reload",
  444. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  445. @(WKNavigationTypeOther): @"other",
  446. };
  447. });
  448. WKNavigationType navigationType = navigationAction.navigationType;
  449. NSURLRequest *request = navigationAction.request;
  450. if (_onShouldStartLoadWithRequest) {
  451. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  452. [event addEntriesFromDictionary: @{
  453. @"url": (request.URL).absoluteString,
  454. @"navigationType": navigationTypes[@(navigationType)]
  455. }];
  456. if (![self.delegate webView:self
  457. shouldStartLoadForRequest:event
  458. withCallback:_onShouldStartLoadWithRequest]) {
  459. decisionHandler(WKNavigationResponsePolicyCancel);
  460. return;
  461. }
  462. }
  463. if (_onLoadingStart) {
  464. // We have this check to filter out iframe requests and whatnot
  465. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  466. if (isTopFrame) {
  467. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  468. [event addEntriesFromDictionary: @{
  469. @"url": (request.URL).absoluteString,
  470. @"navigationType": navigationTypes[@(navigationType)]
  471. }];
  472. _onLoadingStart(event);
  473. }
  474. }
  475. // Allow all navigation by default
  476. decisionHandler(WKNavigationResponsePolicyAllow);
  477. }
  478. /**
  479. * Called when an error occurs while the web view is loading content.
  480. * @see https://fburl.com/km6vqenw
  481. */
  482. - (void) webView:(WKWebView *)webView
  483. didFailProvisionalNavigation:(WKNavigation *)navigation
  484. withError:(NSError *)error
  485. {
  486. if (_onLoadingError) {
  487. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  488. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  489. // a new URL in the WebView before the previous one came back. We can just
  490. // ignore these since they aren't real errors.
  491. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  492. return;
  493. }
  494. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
  495. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  496. // when the URL is from an http redirect. This is a common pattern when
  497. // implementing OAuth with a WebView.
  498. return;
  499. }
  500. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  501. [event addEntriesFromDictionary:@{
  502. @"didFailProvisionalNavigation": @YES,
  503. @"domain": error.domain,
  504. @"code": @(error.code),
  505. @"description": error.localizedDescription,
  506. }];
  507. _onLoadingError(event);
  508. }
  509. [self setBackgroundColor: _savedBackgroundColor];
  510. }
  511. - (void)evaluateJS:(NSString *)js
  512. thenCall: (void (^)(NSString*)) callback
  513. {
  514. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  515. if (error == nil) {
  516. if (callback != nil) {
  517. callback([NSString stringWithFormat:@"%@", result]);
  518. }
  519. } else {
  520. RCTLogError(@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.");
  521. }
  522. }];
  523. }
  524. /**
  525. * Called when the navigation is complete.
  526. * @see https://fburl.com/rtys6jlb
  527. */
  528. - (void) webView:(WKWebView *)webView
  529. didFinishNavigation:(WKNavigation *)navigation
  530. {
  531. if (_injectedJavaScript) {
  532. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  533. NSMutableDictionary *event = [self baseEvent];
  534. event[@"jsEvaluationValue"] = jsEvaluationValue;
  535. if (self.onLoadingFinish) {
  536. self.onLoadingFinish(event);
  537. }
  538. }];
  539. } else if (_onLoadingFinish) {
  540. _onLoadingFinish([self baseEvent]);
  541. }
  542. [self setBackgroundColor: _savedBackgroundColor];
  543. }
  544. - (void)injectJavaScript:(NSString *)script
  545. {
  546. [self evaluateJS: script thenCall: nil];
  547. }
  548. - (void)goForward
  549. {
  550. [_webView goForward];
  551. }
  552. - (void)goBack
  553. {
  554. [_webView goBack];
  555. }
  556. - (void)reload
  557. {
  558. /**
  559. * When the initial load fails due to network connectivity issues,
  560. * [_webView reload] doesn't reload the webpage. Therefore, we must
  561. * manually call [_webView loadRequest:request].
  562. */
  563. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  564. if (request.URL && !_webView.URL.absoluteString.length) {
  565. [_webView loadRequest:request];
  566. }
  567. else {
  568. [_webView reload];
  569. }
  570. }
  571. - (void)stopLoading
  572. {
  573. [_webView stopLoading];
  574. }
  575. - (void)setBounces:(BOOL)bounces
  576. {
  577. _bounces = bounces;
  578. _webView.scrollView.bounces = bounces;
  579. }
  580. @end