Ei kuvausta

RNCWKWebView.m 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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. _directionalLockEnabled = YES;
  48. _automaticallyAdjustContentInsets = YES;
  49. _contentInset = UIEdgeInsetsZero;
  50. }
  51. // Workaround for a keyboard dismissal bug present in iOS 12
  52. // https://openradar.appspot.com/radar?id=5018321736957952
  53. if (@available(iOS 12.0, *)) {
  54. [[NSNotificationCenter defaultCenter]
  55. addObserver:self
  56. selector:@selector(keyboardWillHide)
  57. name:UIKeyboardWillHideNotification object:nil];
  58. [[NSNotificationCenter defaultCenter]
  59. addObserver:self
  60. selector:@selector(keyboardWillShow)
  61. name:UIKeyboardWillShowNotification object:nil];
  62. }
  63. return self;
  64. }
  65. - (void)dealloc
  66. {
  67. [[NSNotificationCenter defaultCenter] removeObserver:self];
  68. }
  69. /**
  70. * See https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank/25853806#25853806 for details.
  71. */
  72. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
  73. {
  74. if (!navigationAction.targetFrame.isMainFrame) {
  75. [webView loadRequest:navigationAction.request];
  76. }
  77. return nil;
  78. }
  79. - (void)didMoveToWindow
  80. {
  81. if (self.window != nil && _webView == nil) {
  82. WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
  83. if (_incognito) {
  84. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  85. } else if (_cacheEnabled) {
  86. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  87. }
  88. if(self.useSharedProcessPool) {
  89. wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPool];
  90. }
  91. wkWebViewConfig.userContentController = [WKUserContentController new];
  92. if (_messagingEnabled) {
  93. [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
  94. NSString *source = [NSString stringWithFormat:
  95. @"window.%@ = {"
  96. " postMessage: function (data) {"
  97. " window.webkit.messageHandlers.%@.postMessage(String(data));"
  98. " }"
  99. "};", MessageHandlerName, MessageHandlerName
  100. ];
  101. WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  102. [wkWebViewConfig.userContentController addUserScript:script];
  103. }
  104. wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
  105. #if WEBKIT_IOS_10_APIS_AVAILABLE
  106. wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
  107. ? WKAudiovisualMediaTypeAll
  108. : WKAudiovisualMediaTypeNone;
  109. wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
  110. #else
  111. wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
  112. #endif
  113. _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
  114. _webView.scrollView.delegate = self;
  115. _webView.UIDelegate = self;
  116. _webView.navigationDelegate = self;
  117. _webView.scrollView.scrollEnabled = _scrollEnabled;
  118. _webView.scrollView.pagingEnabled = _pagingEnabled;
  119. _webView.scrollView.bounces = _bounces;
  120. _webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
  121. _webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
  122. _webView.scrollView.directionalLockEnabled = _directionalLockEnabled;
  123. _webView.allowsLinkPreview = _allowsLinkPreview;
  124. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  125. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  126. if (_userAgent) {
  127. _webView.customUserAgent = _userAgent;
  128. }
  129. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  130. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  131. _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  132. }
  133. #endif
  134. [self addSubview:_webView];
  135. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  136. [self visitSource];
  137. }
  138. }
  139. // Update webview property when the component prop changes.
  140. - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
  141. _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
  142. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  143. }
  144. - (void)removeFromSuperview
  145. {
  146. if (_webView) {
  147. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  148. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  149. [_webView removeFromSuperview];
  150. _webView.scrollView.delegate = nil;
  151. _webView = nil;
  152. }
  153. [super removeFromSuperview];
  154. }
  155. -(void)keyboardWillHide
  156. {
  157. keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
  158. [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
  159. }
  160. -(void)keyboardWillShow
  161. {
  162. if (keyboardTimer != nil) {
  163. [keyboardTimer invalidate];
  164. }
  165. }
  166. -(void)keyboardDisplacementFix
  167. {
  168. // Additional viewport checks to prevent unintentional scrolls
  169. UIScrollView *scrollView = self.webView.scrollView;
  170. double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  171. if (maxContentOffset < 0) {
  172. maxContentOffset = 0;
  173. }
  174. if (scrollView.contentOffset.y > maxContentOffset) {
  175. // https://stackoverflow.com/a/9637807/824966
  176. [UIView animateWithDuration:.25 animations:^{
  177. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  178. }];
  179. }
  180. }
  181. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  182. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  183. if(_onLoadingProgress){
  184. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  185. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  186. _onLoadingProgress(event);
  187. }
  188. }else{
  189. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  190. }
  191. }
  192. - (void)setBackgroundColor:(UIColor *)backgroundColor
  193. {
  194. _savedBackgroundColor = backgroundColor;
  195. if (_webView == nil) {
  196. return;
  197. }
  198. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  199. self.opaque = _webView.opaque = (alpha == 1.0);
  200. _webView.scrollView.backgroundColor = backgroundColor;
  201. _webView.backgroundColor = backgroundColor;
  202. }
  203. /**
  204. * This method is called whenever JavaScript running within the web view calls:
  205. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  206. */
  207. - (void)userContentController:(WKUserContentController *)userContentController
  208. didReceiveScriptMessage:(WKScriptMessage *)message
  209. {
  210. if (_onMessage != nil) {
  211. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  212. [event addEntriesFromDictionary: @{@"data": message.body}];
  213. _onMessage(event);
  214. }
  215. }
  216. - (void)setSource:(NSDictionary *)source
  217. {
  218. if (![_source isEqualToDictionary:source]) {
  219. _source = [source copy];
  220. if (_webView != nil) {
  221. [self visitSource];
  222. }
  223. }
  224. }
  225. - (void)setContentInset:(UIEdgeInsets)contentInset
  226. {
  227. _contentInset = contentInset;
  228. [RCTView autoAdjustInsetsForView:self
  229. withScrollView:_webView.scrollView
  230. updateOffset:NO];
  231. }
  232. - (void)refreshContentInset
  233. {
  234. [RCTView autoAdjustInsetsForView:self
  235. withScrollView:_webView.scrollView
  236. updateOffset:YES];
  237. }
  238. - (void)visitSource
  239. {
  240. // Check for a static html source first
  241. NSString *html = [RCTConvert NSString:_source[@"html"]];
  242. if (html) {
  243. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  244. if (!baseURL) {
  245. baseURL = [NSURL URLWithString:@"about:blank"];
  246. }
  247. [_webView loadHTMLString:html baseURL:baseURL];
  248. return;
  249. }
  250. NSURLRequest *request = [RCTConvert NSURLRequest:_source];
  251. // Because of the way React works, as pages redirect, we actually end up
  252. // passing the redirect urls back here, so we ignore them if trying to load
  253. // the same url. We'll expose a call to 'reload' to allow a user to load
  254. // the existing page.
  255. if ([request.URL isEqual:_webView.URL]) {
  256. return;
  257. }
  258. if (!request.URL) {
  259. // Clear the webview
  260. [_webView loadHTMLString:@"" baseURL:nil];
  261. return;
  262. }
  263. [_webView loadRequest:request];
  264. }
  265. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  266. {
  267. if (_webView == nil) {
  268. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  269. return;
  270. }
  271. if (_savedHideKeyboardAccessoryView == false) {
  272. return;
  273. }
  274. UIView* subview;
  275. for (UIView* view in _webView.scrollView.subviews) {
  276. if([[view.class description] hasPrefix:@"WK"])
  277. subview = view;
  278. }
  279. if(subview == nil) return;
  280. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  281. Class newClass = NSClassFromString(name);
  282. if(newClass == nil)
  283. {
  284. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  285. if(!newClass) return;
  286. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  287. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  288. objc_registerClassPair(newClass);
  289. }
  290. object_setClass(subview, newClass);
  291. }
  292. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  293. {
  294. scrollView.decelerationRate = _decelerationRate;
  295. }
  296. - (void)setScrollEnabled:(BOOL)scrollEnabled
  297. {
  298. _scrollEnabled = scrollEnabled;
  299. _webView.scrollView.scrollEnabled = scrollEnabled;
  300. }
  301. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  302. {
  303. // Don't allow scrolling the scrollView.
  304. if (!_scrollEnabled) {
  305. scrollView.bounds = _webView.bounds;
  306. }
  307. }
  308. - (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
  309. {
  310. _directionalLockEnabled = directionalLockEnabled;
  311. _webView.scrollView.directionalLockEnabled = directionalLockEnabled;
  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