react-native-webview.git

RNCWKWebView.m 22KB

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