暂无描述

RNCWKWebView.m 20KB

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