Aucune description

RNCWKWebView.m 21KB

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