Nav apraksta

RNCWKWebView.m 23KB

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