Keine Beschreibung

RNCWKWebView.m 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644
  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 (maxContentOffset < 0) {
  158. maxContentOffset = 0;
  159. }
  160. if (scrollView.contentOffset.y > maxContentOffset) {
  161. // https://stackoverflow.com/a/9637807/824966
  162. [UIView animateWithDuration:.25 animations:^{
  163. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  164. }];
  165. }
  166. }
  167. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  168. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  169. if(_onLoadingProgress){
  170. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  171. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  172. _onLoadingProgress(event);
  173. }
  174. }else{
  175. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  176. }
  177. }
  178. - (void)setBackgroundColor:(UIColor *)backgroundColor
  179. {
  180. _savedBackgroundColor = backgroundColor;
  181. if (_webView == nil) {
  182. return;
  183. }
  184. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  185. self.opaque = _webView.opaque = (alpha == 1.0);
  186. _webView.scrollView.backgroundColor = backgroundColor;
  187. _webView.backgroundColor = backgroundColor;
  188. }
  189. /**
  190. * This method is called whenever JavaScript running within the web view calls:
  191. * - window.webkit.messageHandlers.[MessageHanderName].postMessage
  192. */
  193. - (void)userContentController:(WKUserContentController *)userContentController
  194. didReceiveScriptMessage:(WKScriptMessage *)message
  195. {
  196. if (_onMessage != nil) {
  197. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  198. [event addEntriesFromDictionary: @{@"data": message.body}];
  199. _onMessage(event);
  200. }
  201. }
  202. - (void)setSource:(NSDictionary *)source
  203. {
  204. if (![_source isEqualToDictionary:source]) {
  205. _source = [source copy];
  206. if (_webView != nil) {
  207. [self visitSource];
  208. }
  209. }
  210. }
  211. - (void)setContentInset:(UIEdgeInsets)contentInset
  212. {
  213. _contentInset = contentInset;
  214. [RCTView autoAdjustInsetsForView:self
  215. withScrollView:_webView.scrollView
  216. updateOffset:NO];
  217. }
  218. - (void)refreshContentInset
  219. {
  220. [RCTView autoAdjustInsetsForView:self
  221. withScrollView:_webView.scrollView
  222. updateOffset:YES];
  223. }
  224. - (void)visitSource
  225. {
  226. // Check for a static html source first
  227. NSString *html = [RCTConvert NSString:_source[@"html"]];
  228. if (html) {
  229. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  230. if (!baseURL) {
  231. baseURL = [NSURL URLWithString:@"about:blank"];
  232. }
  233. [_webView loadHTMLString:html baseURL:baseURL];
  234. return;
  235. }
  236. NSURLRequest *request = [RCTConvert NSURLRequest:_source];
  237. // Because of the way React works, as pages redirect, we actually end up
  238. // passing the redirect urls back here, so we ignore them if trying to load
  239. // the same url. We'll expose a call to 'reload' to allow a user to load
  240. // the existing page.
  241. if ([request.URL isEqual:_webView.URL]) {
  242. return;
  243. }
  244. if (!request.URL) {
  245. // Clear the webview
  246. [_webView loadHTMLString:@"" baseURL:nil];
  247. return;
  248. }
  249. [_webView loadRequest:request];
  250. }
  251. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  252. {
  253. if (_webView == nil) {
  254. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  255. return;
  256. }
  257. if (_savedHideKeyboardAccessoryView == false) {
  258. return;
  259. }
  260. UIView* subview;
  261. for (UIView* view in _webView.scrollView.subviews) {
  262. if([[view.class description] hasPrefix:@"WK"])
  263. subview = view;
  264. }
  265. if(subview == nil) return;
  266. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  267. Class newClass = NSClassFromString(name);
  268. if(newClass == nil)
  269. {
  270. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  271. if(!newClass) return;
  272. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  273. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  274. objc_registerClassPair(newClass);
  275. }
  276. object_setClass(subview, newClass);
  277. }
  278. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  279. {
  280. scrollView.decelerationRate = _decelerationRate;
  281. }
  282. - (void)setScrollEnabled:(BOOL)scrollEnabled
  283. {
  284. _scrollEnabled = scrollEnabled;
  285. _webView.scrollView.scrollEnabled = scrollEnabled;
  286. }
  287. - (void)postMessage:(NSString *)message
  288. {
  289. NSDictionary *eventInitDict = @{@"data": message};
  290. NSString *source = [NSString
  291. stringWithFormat:@"document.dispatchEvent(new MessageEvent('message', %@));",
  292. RCTJSONStringify(eventInitDict, NULL)
  293. ];
  294. [self evaluateJS: source thenCall: nil];
  295. }
  296. - (void)layoutSubviews
  297. {
  298. [super layoutSubviews];
  299. // Ensure webview takes the position and dimensions of RNCWKWebView
  300. _webView.frame = self.bounds;
  301. }
  302. - (NSMutableDictionary<NSString *, id> *)baseEvent
  303. {
  304. NSDictionary *event = @{
  305. @"url": _webView.URL.absoluteString ?: @"",
  306. @"title": _webView.title,
  307. @"loading" : @(_webView.loading),
  308. @"canGoBack": @(_webView.canGoBack),
  309. @"canGoForward" : @(_webView.canGoForward)
  310. };
  311. return [[NSMutableDictionary alloc] initWithDictionary: event];
  312. }
  313. #pragma mark - WKNavigationDelegate methods
  314. /**
  315. * alert
  316. */
  317. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  318. {
  319. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  320. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  321. completionHandler();
  322. }]];
  323. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  324. }
  325. /**
  326. * confirm
  327. */
  328. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  329. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  330. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  331. completionHandler(YES);
  332. }]];
  333. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  334. completionHandler(NO);
  335. }]];
  336. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  337. }
  338. /**
  339. * prompt
  340. */
  341. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  342. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  343. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  344. textField.textColor = [UIColor lightGrayColor];
  345. textField.placeholder = defaultText;
  346. }];
  347. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  348. completionHandler([[alert.textFields lastObject] text]);
  349. }]];
  350. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  351. }
  352. /**
  353. * topViewController
  354. */
  355. -(UIViewController *)topViewController{
  356.    UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  357.    return controller;
  358. }
  359. /**
  360. * topViewControllerWithRootViewController
  361. */
  362. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  363. if (viewController==nil) return nil;
  364. if (viewController.presentedViewController!=nil) {
  365. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  366. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  367. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  368. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  369. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  370. } else {
  371. return viewController;
  372. }
  373. }
  374. /**
  375. * getCurrentWindow
  376. */
  377. -(UIWindow *)getCurrentWindow{
  378. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  379. if (window.windowLevel!=UIWindowLevelNormal) {
  380. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  381. if (window.windowLevel==UIWindowLevelNormal) {
  382. window = wid;
  383. break;
  384. }
  385. }
  386. }
  387. return window;
  388. }
  389. /**
  390. * Decides whether to allow or cancel a navigation.
  391. * @see https://fburl.com/42r9fxob
  392. */
  393. - (void) webView:(WKWebView *)webView
  394. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  395. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  396. {
  397. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  398. static dispatch_once_t onceToken;
  399. dispatch_once(&onceToken, ^{
  400. navigationTypes = @{
  401. @(WKNavigationTypeLinkActivated): @"click",
  402. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  403. @(WKNavigationTypeBackForward): @"backforward",
  404. @(WKNavigationTypeReload): @"reload",
  405. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  406. @(WKNavigationTypeOther): @"other",
  407. };
  408. });
  409. WKNavigationType navigationType = navigationAction.navigationType;
  410. NSURLRequest *request = navigationAction.request;
  411. if (_onShouldStartLoadWithRequest) {
  412. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  413. [event addEntriesFromDictionary: @{
  414. @"url": (request.URL).absoluteString,
  415. @"navigationType": navigationTypes[@(navigationType)]
  416. }];
  417. if (![self.delegate webView:self
  418. shouldStartLoadForRequest:event
  419. withCallback:_onShouldStartLoadWithRequest]) {
  420. decisionHandler(WKNavigationResponsePolicyCancel);
  421. return;
  422. }
  423. }
  424. if (_onLoadingStart) {
  425. // We have this check to filter out iframe requests and whatnot
  426. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  427. if (isTopFrame) {
  428. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  429. [event addEntriesFromDictionary: @{
  430. @"url": (request.URL).absoluteString,
  431. @"navigationType": navigationTypes[@(navigationType)]
  432. }];
  433. _onLoadingStart(event);
  434. }
  435. }
  436. // Allow all navigation by default
  437. decisionHandler(WKNavigationResponsePolicyAllow);
  438. }
  439. /**
  440. * Called when an error occurs while the web view is loading content.
  441. * @see https://fburl.com/km6vqenw
  442. */
  443. - (void) webView:(WKWebView *)webView
  444. didFailProvisionalNavigation:(WKNavigation *)navigation
  445. withError:(NSError *)error
  446. {
  447. if (_onLoadingError) {
  448. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  449. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  450. // a new URL in the WebView before the previous one came back. We can just
  451. // ignore these since they aren't real errors.
  452. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  453. return;
  454. }
  455. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
  456. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  457. // when the URL is from an http redirect. This is a common pattern when
  458. // implementing OAuth with a WebView.
  459. return;
  460. }
  461. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  462. [event addEntriesFromDictionary:@{
  463. @"didFailProvisionalNavigation": @YES,
  464. @"domain": error.domain,
  465. @"code": @(error.code),
  466. @"description": error.localizedDescription,
  467. }];
  468. _onLoadingError(event);
  469. }
  470. [self setBackgroundColor: _savedBackgroundColor];
  471. }
  472. - (void)evaluateJS:(NSString *)js
  473. thenCall: (void (^)(NSString*)) callback
  474. {
  475. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  476. if (error == nil) {
  477. if (callback != nil) {
  478. callback([NSString stringWithFormat:@"%@", result]);
  479. }
  480. } else {
  481. RCTLogError(@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.");
  482. }
  483. }];
  484. }
  485. /**
  486. * Called when the navigation is complete.
  487. * @see https://fburl.com/rtys6jlb
  488. */
  489. - (void) webView:(WKWebView *)webView
  490. didFinishNavigation:(WKNavigation *)navigation
  491. {
  492. if (_messagingEnabled) {
  493. #if RCT_DEV
  494. // Implementation inspired by Lodash.isNative.
  495. NSString *isPostMessageNative = @"String(String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage'))";
  496. [self evaluateJS: isPostMessageNative thenCall: ^(NSString *result) {
  497. if (! [result isEqualToString:@"true"]) {
  498. RCTLogError(@"Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
  499. }
  500. }];
  501. #endif
  502. NSString *source = [NSString stringWithFormat:
  503. @"(function() {"
  504. "window.originalPostMessage = window.postMessage;"
  505. "window.postMessage = function(data) {"
  506. "window.webkit.messageHandlers.%@.postMessage(String(data));"
  507. "};"
  508. "})();",
  509. MessageHanderName
  510. ];
  511. [self evaluateJS: source thenCall: nil];
  512. }
  513. if (_injectedJavaScript) {
  514. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  515. NSMutableDictionary *event = [self baseEvent];
  516. event[@"jsEvaluationValue"] = jsEvaluationValue;
  517. if (self.onLoadingFinish) {
  518. self.onLoadingFinish(event);
  519. }
  520. }];
  521. } else if (_onLoadingFinish) {
  522. _onLoadingFinish([self baseEvent]);
  523. }
  524. [self setBackgroundColor: _savedBackgroundColor];
  525. }
  526. - (void)injectJavaScript:(NSString *)script
  527. {
  528. [self evaluateJS: script thenCall: nil];
  529. }
  530. - (void)goForward
  531. {
  532. [_webView goForward];
  533. }
  534. - (void)goBack
  535. {
  536. [_webView goBack];
  537. }
  538. - (void)reload
  539. {
  540. /**
  541. * When the initial load fails due to network connectivity issues,
  542. * [_webView reload] doesn't reload the webpage. Therefore, we must
  543. * manually call [_webView loadRequest:request].
  544. */
  545. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  546. if (request.URL && !_webView.URL.absoluteString.length) {
  547. [_webView loadRequest:request];
  548. }
  549. else {
  550. [_webView reload];
  551. }
  552. }
  553. - (void)stopLoading
  554. {
  555. [_webView stopLoading];
  556. }
  557. - (void)setBounces:(BOOL)bounces
  558. {
  559. _bounces = bounces;
  560. _webView.scrollView.bounces = bounces;
  561. }
  562. @end