Няма описание

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