Нет описания

RNCWKWebView.m 23KB

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