Sin descripción

RNCWKWebView.m 21KB

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