설명 없음

RNCWKWebView.m 22KB

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