暫無描述

RNCWKWebView.m 20KB

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