Нема описа

RNCWKWebView.m 20KB

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