Nav apraksta

RNCWKWebView.m 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. // Override the scrollView delegate to prevent scrolling.
  299. if (!scrollEnabled) {
  300. _webView.scrollView.delegate = self;
  301. } else {
  302. _webView.scrollView.delegate = _webView;
  303. }
  304. }
  305. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  306. {
  307. // Don't allow scrolling the scrollView.
  308. scrollView.bounds = _webView.bounds;
  309. }
  310. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  311. {
  312. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  313. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  314. }
  315. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  316. {
  317. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  318. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  319. }
  320. - (void)postMessage:(NSString *)message
  321. {
  322. NSDictionary *eventInitDict = @{@"data": message};
  323. NSString *source = [NSString
  324. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  325. RCTJSONStringify(eventInitDict, NULL)
  326. ];
  327. [self injectJavaScript: source];
  328. }
  329. - (void)layoutSubviews
  330. {
  331. [super layoutSubviews];
  332. // Ensure webview takes the position and dimensions of RNCWKWebView
  333. _webView.frame = self.bounds;
  334. }
  335. - (NSMutableDictionary<NSString *, id> *)baseEvent
  336. {
  337. NSDictionary *event = @{
  338. @"url": _webView.URL.absoluteString ?: @"",
  339. @"title": _webView.title,
  340. @"loading" : @(_webView.loading),
  341. @"canGoBack": @(_webView.canGoBack),
  342. @"canGoForward" : @(_webView.canGoForward)
  343. };
  344. return [[NSMutableDictionary alloc] initWithDictionary: event];
  345. }
  346. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  347. clientAuthenticationCredential = credential;
  348. }
  349. - (void) webView:(WKWebView *)webView
  350. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  351. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  352. {
  353. if (!clientAuthenticationCredential) {
  354. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  355. return;
  356. }
  357. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  358. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  359. } else {
  360. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  361. }
  362. }
  363. #pragma mark - WKNavigationDelegate methods
  364. /**
  365. * alert
  366. */
  367. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  368. {
  369. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  370. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  371. completionHandler();
  372. }]];
  373. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  374. }
  375. /**
  376. * confirm
  377. */
  378. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  379. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  380. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  381. completionHandler(YES);
  382. }]];
  383. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  384. completionHandler(NO);
  385. }]];
  386. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  387. }
  388. /**
  389. * prompt
  390. */
  391. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  392. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  393. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  394. textField.textColor = [UIColor lightGrayColor];
  395. textField.placeholder = defaultText;
  396. }];
  397. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  398. completionHandler([[alert.textFields lastObject] text]);
  399. }]];
  400. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  401. }
  402. /**
  403. * topViewController
  404. */
  405. -(UIViewController *)topViewController{
  406.    UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  407.    return controller;
  408. }
  409. /**
  410. * topViewControllerWithRootViewController
  411. */
  412. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  413. if (viewController==nil) return nil;
  414. if (viewController.presentedViewController!=nil) {
  415. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  416. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  417. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  418. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  419. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  420. } else {
  421. return viewController;
  422. }
  423. }
  424. /**
  425. * getCurrentWindow
  426. */
  427. -(UIWindow *)getCurrentWindow{
  428. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  429. if (window.windowLevel!=UIWindowLevelNormal) {
  430. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  431. if (window.windowLevel==UIWindowLevelNormal) {
  432. window = wid;
  433. break;
  434. }
  435. }
  436. }
  437. return window;
  438. }
  439. /**
  440. * Decides whether to allow or cancel a navigation.
  441. * @see https://fburl.com/42r9fxob
  442. */
  443. - (void) webView:(WKWebView *)webView
  444. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  445. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  446. {
  447. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  448. static dispatch_once_t onceToken;
  449. dispatch_once(&onceToken, ^{
  450. navigationTypes = @{
  451. @(WKNavigationTypeLinkActivated): @"click",
  452. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  453. @(WKNavigationTypeBackForward): @"backforward",
  454. @(WKNavigationTypeReload): @"reload",
  455. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  456. @(WKNavigationTypeOther): @"other",
  457. };
  458. });
  459. WKNavigationType navigationType = navigationAction.navigationType;
  460. NSURLRequest *request = navigationAction.request;
  461. if (_onShouldStartLoadWithRequest) {
  462. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  463. [event addEntriesFromDictionary: @{
  464. @"url": (request.URL).absoluteString,
  465. @"navigationType": navigationTypes[@(navigationType)]
  466. }];
  467. if (![self.delegate webView:self
  468. shouldStartLoadForRequest:event
  469. withCallback:_onShouldStartLoadWithRequest]) {
  470. decisionHandler(WKNavigationResponsePolicyCancel);
  471. return;
  472. }
  473. }
  474. if (_onLoadingStart) {
  475. // We have this check to filter out iframe requests and whatnot
  476. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  477. if (isTopFrame) {
  478. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  479. [event addEntriesFromDictionary: @{
  480. @"url": (request.URL).absoluteString,
  481. @"navigationType": navigationTypes[@(navigationType)]
  482. }];
  483. _onLoadingStart(event);
  484. }
  485. }
  486. // Allow all navigation by default
  487. decisionHandler(WKNavigationResponsePolicyAllow);
  488. }
  489. /**
  490. * Called when an error occurs while the web view is loading content.
  491. * @see https://fburl.com/km6vqenw
  492. */
  493. - (void) webView:(WKWebView *)webView
  494. didFailProvisionalNavigation:(WKNavigation *)navigation
  495. withError:(NSError *)error
  496. {
  497. if (_onLoadingError) {
  498. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  499. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  500. // a new URL in the WebView before the previous one came back. We can just
  501. // ignore these since they aren't real errors.
  502. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  503. return;
  504. }
  505. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
  506. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  507. // when the URL is from an http redirect. This is a common pattern when
  508. // implementing OAuth with a WebView.
  509. return;
  510. }
  511. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  512. [event addEntriesFromDictionary:@{
  513. @"didFailProvisionalNavigation": @YES,
  514. @"domain": error.domain,
  515. @"code": @(error.code),
  516. @"description": error.localizedDescription,
  517. }];
  518. _onLoadingError(event);
  519. }
  520. [self setBackgroundColor: _savedBackgroundColor];
  521. }
  522. - (void)evaluateJS:(NSString *)js
  523. thenCall: (void (^)(NSString*)) callback
  524. {
  525. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  526. if (error == nil) {
  527. if (callback != nil) {
  528. callback([NSString stringWithFormat:@"%@", result]);
  529. }
  530. } else {
  531. RCTLogError(@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.");
  532. }
  533. }];
  534. }
  535. /**
  536. * Called when the navigation is complete.
  537. * @see https://fburl.com/rtys6jlb
  538. */
  539. - (void) webView:(WKWebView *)webView
  540. didFinishNavigation:(WKNavigation *)navigation
  541. {
  542. if (_injectedJavaScript) {
  543. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  544. NSMutableDictionary *event = [self baseEvent];
  545. event[@"jsEvaluationValue"] = jsEvaluationValue;
  546. if (self.onLoadingFinish) {
  547. self.onLoadingFinish(event);
  548. }
  549. }];
  550. } else if (_onLoadingFinish) {
  551. _onLoadingFinish([self baseEvent]);
  552. }
  553. [self setBackgroundColor: _savedBackgroundColor];
  554. }
  555. - (void)injectJavaScript:(NSString *)script
  556. {
  557. [self evaluateJS: script thenCall: nil];
  558. }
  559. - (void)goForward
  560. {
  561. [_webView goForward];
  562. }
  563. - (void)goBack
  564. {
  565. [_webView goBack];
  566. }
  567. - (void)reload
  568. {
  569. /**
  570. * When the initial load fails due to network connectivity issues,
  571. * [_webView reload] doesn't reload the webpage. Therefore, we must
  572. * manually call [_webView loadRequest:request].
  573. */
  574. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  575. if (request.URL && !_webView.URL.absoluteString.length) {
  576. [_webView loadRequest:request];
  577. }
  578. else {
  579. [_webView reload];
  580. }
  581. }
  582. - (void)stopLoading
  583. {
  584. [_webView stopLoading];
  585. }
  586. - (void)setBounces:(BOOL)bounces
  587. {
  588. _bounces = bounces;
  589. _webView.scrollView.bounces = bounces;
  590. }
  591. @end