Nessuna descrizione

RNCWKWebView.m 20KB

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