react-native-webview.git

RNCWebView.m 41KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080
  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 "RNCWebView.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 NSTimer *keyboardTimer;
  14. static NSString *const HistoryShimName = @"ReactNativeHistoryShim";
  15. static NSString *const MessageHandlerName = @"ReactNativeWebView";
  16. static NSURLCredential* clientAuthenticationCredential;
  17. static NSDictionary* customCertificatesForHost;
  18. // runtime trick to remove WKWebView keyboard default toolbar
  19. // see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
  20. @interface _SwizzleHelperWK : UIView
  21. @property (nonatomic, copy) WKWebView *webView;
  22. @end
  23. @implementation _SwizzleHelperWK
  24. -(id)inputAccessoryView
  25. {
  26. if (_webView == nil) {
  27. return nil;
  28. }
  29. if ([_webView respondsToSelector:@selector(inputAssistantItem)]) {
  30. UITextInputAssistantItem *inputAssistantItem = [_webView inputAssistantItem];
  31. inputAssistantItem.leadingBarButtonGroups = @[];
  32. inputAssistantItem.trailingBarButtonGroups = @[];
  33. }
  34. return nil;
  35. }
  36. @end
  37. @interface RNCWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIScrollViewDelegate, RCTAutoInsetsProtocol>
  38. @property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
  39. @property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
  40. @property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
  41. @property (nonatomic, copy) RCTDirectEventBlock onLoadingProgress;
  42. @property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
  43. @property (nonatomic, copy) RCTDirectEventBlock onHttpError;
  44. @property (nonatomic, copy) RCTDirectEventBlock onMessage;
  45. @property (nonatomic, copy) RCTDirectEventBlock onScroll;
  46. @property (nonatomic, copy) RCTDirectEventBlock onContentProcessDidTerminate;
  47. @property (nonatomic, copy) WKWebView *webView;
  48. @end
  49. @implementation RNCWebView
  50. {
  51. UIColor * _savedBackgroundColor;
  52. BOOL _savedHideKeyboardAccessoryView;
  53. BOOL _savedKeyboardDisplayRequiresUserAction;
  54. // Workaround for StatusBar appearance bug for iOS 12
  55. // https://github.com/react-native-community/react-native-webview/issues/62
  56. BOOL _isFullScreenVideoOpen;
  57. UIStatusBarStyle _savedStatusBarStyle;
  58. BOOL _savedStatusBarHidden;
  59. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  60. UIScrollViewContentInsetAdjustmentBehavior _savedContentInsetAdjustmentBehavior;
  61. #endif
  62. }
  63. - (instancetype)initWithFrame:(CGRect)frame
  64. {
  65. if ((self = [super initWithFrame:frame])) {
  66. super.backgroundColor = [UIColor clearColor];
  67. _bounces = YES;
  68. _scrollEnabled = YES;
  69. _showsHorizontalScrollIndicator = YES;
  70. _showsVerticalScrollIndicator = YES;
  71. _directionalLockEnabled = YES;
  72. _automaticallyAdjustContentInsets = YES;
  73. _contentInset = UIEdgeInsetsZero;
  74. _savedKeyboardDisplayRequiresUserAction = YES;
  75. _savedStatusBarStyle = RCTSharedApplication().statusBarStyle;
  76. _savedStatusBarHidden = RCTSharedApplication().statusBarHidden;
  77. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  78. _savedContentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  79. #endif
  80. }
  81. if (@available(iOS 12.0, *)) {
  82. // Workaround for a keyboard dismissal bug present in iOS 12
  83. // https://openradar.appspot.com/radar?id=5018321736957952
  84. [[NSNotificationCenter defaultCenter]
  85. addObserver:self
  86. selector:@selector(keyboardWillHide)
  87. name:UIKeyboardWillHideNotification object:nil];
  88. [[NSNotificationCenter defaultCenter]
  89. addObserver:self
  90. selector:@selector(keyboardWillShow)
  91. name:UIKeyboardWillShowNotification object:nil];
  92. // Workaround for StatusBar appearance bug for iOS 12
  93. // https://github.com/react-native-community/react-native-webview/issues/62
  94. [[NSNotificationCenter defaultCenter] addObserver:self
  95. selector:@selector(showFullScreenVideoStatusBars)
  96. name:UIWindowDidBecomeVisibleNotification
  97. object:nil];
  98. [[NSNotificationCenter defaultCenter] addObserver:self
  99. selector:@selector(hideFullScreenVideoStatusBars)
  100. name:UIWindowDidBecomeHiddenNotification
  101. object:nil];
  102. }
  103. return self;
  104. }
  105. - (void)dealloc
  106. {
  107. [[NSNotificationCenter defaultCenter] removeObserver:self];
  108. }
  109. /**
  110. * See https://stackoverflow.com/questions/25713069/why-is-wkwebview-not-opening-links-with-target-blank/25853806#25853806 for details.
  111. */
  112. - (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
  113. {
  114. if (!navigationAction.targetFrame.isMainFrame) {
  115. [webView loadRequest:navigationAction.request];
  116. }
  117. return nil;
  118. }
  119. - (void)didMoveToWindow
  120. {
  121. if (self.window != nil && _webView == nil) {
  122. WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
  123. WKPreferences *prefs = [[WKPreferences alloc]init];
  124. BOOL _prefsUsed = NO;
  125. if (!_javaScriptEnabled) {
  126. prefs.javaScriptEnabled = NO;
  127. _prefsUsed = YES;
  128. }
  129. if (_allowFileAccessFromFileURLs) {
  130. [prefs setValue:@TRUE forKey:@"allowFileAccessFromFileURLs"];
  131. _prefsUsed = YES;
  132. }
  133. if (_prefsUsed) {
  134. wkWebViewConfig.preferences = prefs;
  135. }
  136. if (_incognito) {
  137. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  138. } else if (_cacheEnabled) {
  139. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore defaultDataStore];
  140. }
  141. if(self.useSharedProcessPool) {
  142. wkWebViewConfig.processPool = [[RNCWKProcessPoolManager sharedManager] sharedProcessPool];
  143. }
  144. wkWebViewConfig.userContentController = [WKUserContentController new];
  145. // Shim the HTML5 history API:
  146. [wkWebViewConfig.userContentController addScriptMessageHandler:self name:HistoryShimName];
  147. NSString *source = [NSString stringWithFormat:
  148. @"(function(history) {\n"
  149. " function notify(type) {\n"
  150. " setTimeout(function() {\n"
  151. " window.webkit.messageHandlers.%@.postMessage(type)\n"
  152. " }, 0)\n"
  153. " }\n"
  154. " function shim(f) {\n"
  155. " return function pushState() {\n"
  156. " notify('other')\n"
  157. " return f.apply(history, arguments)\n"
  158. " }\n"
  159. " }\n"
  160. " history.pushState = shim(history.pushState)\n"
  161. " history.replaceState = shim(history.replaceState)\n"
  162. " window.addEventListener('popstate', function() {\n"
  163. " notify('backforward')\n"
  164. " })\n"
  165. "})(window.history)\n", HistoryShimName
  166. ];
  167. WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  168. [wkWebViewConfig.userContentController addUserScript:script];
  169. if (_messagingEnabled) {
  170. [wkWebViewConfig.userContentController addScriptMessageHandler:self name:MessageHandlerName];
  171. NSString *source = [NSString stringWithFormat:
  172. @"window.%@ = {"
  173. " postMessage: function (data) {"
  174. " window.webkit.messageHandlers.%@.postMessage(String(data));"
  175. " }"
  176. "};", MessageHandlerName, MessageHandlerName
  177. ];
  178. WKUserScript *script = [[WKUserScript alloc] initWithSource:source injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  179. [wkWebViewConfig.userContentController addUserScript:script];
  180. if (_injectedJavaScriptBeforeContentLoaded) {
  181. // If user has provided an injectedJavascript prop, execute it at the start of the document
  182. WKUserScript *injectedScript = [[WKUserScript alloc] initWithSource:_injectedJavaScriptBeforeContentLoaded injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES];
  183. [wkWebViewConfig.userContentController addUserScript:injectedScript];
  184. }
  185. }
  186. wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
  187. #if WEBKIT_IOS_10_APIS_AVAILABLE
  188. wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
  189. ? WKAudiovisualMediaTypeAll
  190. : WKAudiovisualMediaTypeNone;
  191. wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
  192. #else
  193. wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
  194. #endif
  195. if (_applicationNameForUserAgent) {
  196. wkWebViewConfig.applicationNameForUserAgent = [NSString stringWithFormat:@"%@ %@", wkWebViewConfig.applicationNameForUserAgent, _applicationNameForUserAgent];
  197. }
  198. if(_sharedCookiesEnabled) {
  199. // More info to sending cookies with WKWebView
  200. // https://stackoverflow.com/questions/26573137/can-i-set-the-cookies-to-be-used-by-a-wkwebview/26577303#26577303
  201. if (@available(iOS 11.0, *)) {
  202. // Set Cookies in iOS 11 and above, initialize websiteDataStore before setting cookies
  203. // See also https://forums.developer.apple.com/thread/97194
  204. // check if websiteDataStore has not been initialized before
  205. if(!_incognito && !_cacheEnabled) {
  206. wkWebViewConfig.websiteDataStore = [WKWebsiteDataStore nonPersistentDataStore];
  207. }
  208. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  209. [wkWebViewConfig.websiteDataStore.httpCookieStore setCookie:cookie completionHandler:nil];
  210. }
  211. } else {
  212. NSMutableString *script = [NSMutableString string];
  213. // Clear all existing cookies in a direct called function. This ensures that no
  214. // javascript error will break the web content javascript.
  215. // We keep this code here, if someone requires that Cookies are also removed within the
  216. // the WebView and want to extends the current sharedCookiesEnabled option with an
  217. // additional property.
  218. // Generates JS: document.cookie = "key=; Expires=Thu, 01 Jan 1970 00:00:01 GMT;"
  219. // for each cookie which is already available in the WebView context.
  220. /*
  221. [script appendString:@"(function () {\n"];
  222. [script appendString:@" var cookies = document.cookie.split('; ');\n"];
  223. [script appendString:@" for (var i = 0; i < cookies.length; i++) {\n"];
  224. [script appendString:@" if (cookies[i].indexOf('=') !== -1) {\n"];
  225. [script appendString:@" document.cookie = cookies[i].split('=')[0] + '=; Expires=Thu, 01 Jan 1970 00:00:01 GMT';\n"];
  226. [script appendString:@" }\n"];
  227. [script appendString:@" }\n"];
  228. [script appendString:@"})();\n\n"];
  229. */
  230. // Set cookies in a direct called function. This ensures that no
  231. // javascript error will break the web content javascript.
  232. // Generates JS: document.cookie = "key=value; Path=/; Expires=Thu, 01 Jan 20xx 00:00:01 GMT;"
  233. // for each cookie which is available in the application context.
  234. [script appendString:@"(function () {\n"];
  235. for (NSHTTPCookie *cookie in [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
  236. [script appendFormat:@"document.cookie = %@ + '=' + %@",
  237. RCTJSONStringify(cookie.name, NULL),
  238. RCTJSONStringify(cookie.value, NULL)];
  239. if (cookie.path) {
  240. [script appendFormat:@" + '; Path=' + %@", RCTJSONStringify(cookie.path, NULL)];
  241. }
  242. if (cookie.expiresDate) {
  243. [script appendFormat:@" + '; Expires=' + new Date(%f).toUTCString()",
  244. cookie.expiresDate.timeIntervalSince1970 * 1000
  245. ];
  246. }
  247. [script appendString:@";\n"];
  248. }
  249. [script appendString:@"})();\n"];
  250. WKUserScript* cookieInScript = [[WKUserScript alloc] initWithSource:script
  251. injectionTime:WKUserScriptInjectionTimeAtDocumentStart
  252. forMainFrameOnly:YES];
  253. [wkWebViewConfig.userContentController addUserScript:cookieInScript];
  254. }
  255. }
  256. _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
  257. [self setBackgroundColor: _savedBackgroundColor];
  258. _webView.scrollView.delegate = self;
  259. _webView.UIDelegate = self;
  260. _webView.navigationDelegate = self;
  261. _webView.scrollView.scrollEnabled = _scrollEnabled;
  262. _webView.scrollView.pagingEnabled = _pagingEnabled;
  263. _webView.scrollView.bounces = _bounces;
  264. _webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
  265. _webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
  266. _webView.scrollView.directionalLockEnabled = _directionalLockEnabled;
  267. _webView.allowsLinkPreview = _allowsLinkPreview;
  268. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  269. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  270. if (_userAgent) {
  271. _webView.customUserAgent = _userAgent;
  272. }
  273. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  274. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  275. _webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
  276. }
  277. #endif
  278. [self addSubview:_webView];
  279. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  280. [self setKeyboardDisplayRequiresUserAction: _savedKeyboardDisplayRequiresUserAction];
  281. [self visitSource];
  282. }
  283. }
  284. // Update webview property when the component prop changes.
  285. - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
  286. _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
  287. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  288. }
  289. - (void)removeFromSuperview
  290. {
  291. if (_webView) {
  292. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  293. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  294. [_webView removeFromSuperview];
  295. _webView.scrollView.delegate = nil;
  296. _webView = nil;
  297. }
  298. [super removeFromSuperview];
  299. }
  300. -(void)showFullScreenVideoStatusBars
  301. {
  302. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  303. _isFullScreenVideoOpen = YES;
  304. RCTUnsafeExecuteOnMainQueueSync(^{
  305. [RCTSharedApplication() setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  306. });
  307. #pragma clang diagnostic pop
  308. }
  309. -(void)hideFullScreenVideoStatusBars
  310. {
  311. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  312. _isFullScreenVideoOpen = NO;
  313. RCTUnsafeExecuteOnMainQueueSync(^{
  314. [RCTSharedApplication() setStatusBarHidden:self->_savedStatusBarHidden animated:YES];
  315. [RCTSharedApplication() setStatusBarStyle:self->_savedStatusBarStyle animated:YES];
  316. });
  317. #pragma clang diagnostic pop
  318. }
  319. -(void)keyboardWillHide
  320. {
  321. keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
  322. [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
  323. }
  324. -(void)keyboardWillShow
  325. {
  326. if (keyboardTimer != nil) {
  327. [keyboardTimer invalidate];
  328. }
  329. }
  330. -(void)keyboardDisplacementFix
  331. {
  332. // Additional viewport checks to prevent unintentional scrolls
  333. UIScrollView *scrollView = self.webView.scrollView;
  334. double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  335. if (maxContentOffset < 0) {
  336. maxContentOffset = 0;
  337. }
  338. if (scrollView.contentOffset.y > maxContentOffset) {
  339. // https://stackoverflow.com/a/9637807/824966
  340. [UIView animateWithDuration:.25 animations:^{
  341. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  342. }];
  343. }
  344. }
  345. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  346. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  347. if(_onLoadingProgress){
  348. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  349. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  350. _onLoadingProgress(event);
  351. }
  352. }else{
  353. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  354. }
  355. }
  356. - (void)setBackgroundColor:(UIColor *)backgroundColor
  357. {
  358. _savedBackgroundColor = backgroundColor;
  359. if (_webView == nil) {
  360. return;
  361. }
  362. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  363. self.opaque = _webView.opaque = (alpha == 1.0);
  364. _webView.scrollView.backgroundColor = backgroundColor;
  365. _webView.backgroundColor = backgroundColor;
  366. }
  367. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  368. - (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
  369. {
  370. _savedContentInsetAdjustmentBehavior = behavior;
  371. if (_webView == nil) {
  372. return;
  373. }
  374. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  375. CGPoint contentOffset = _webView.scrollView.contentOffset;
  376. _webView.scrollView.contentInsetAdjustmentBehavior = behavior;
  377. _webView.scrollView.contentOffset = contentOffset;
  378. }
  379. }
  380. #endif
  381. /**
  382. * This method is called whenever JavaScript running within the web view calls:
  383. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  384. */
  385. - (void)userContentController:(WKUserContentController *)userContentController
  386. didReceiveScriptMessage:(WKScriptMessage *)message
  387. {
  388. if ([message.name isEqualToString:HistoryShimName]) {
  389. if (_onLoadingFinish) {
  390. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  391. [event addEntriesFromDictionary: @{@"navigationType": message.body}];
  392. _onLoadingFinish(event);
  393. }
  394. } else if ([message.name isEqualToString:MessageHandlerName]) {
  395. if (_onMessage) {
  396. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  397. [event addEntriesFromDictionary: @{@"data": message.body}];
  398. _onMessage(event);
  399. }
  400. }
  401. }
  402. - (void)setSource:(NSDictionary *)source
  403. {
  404. if (![_source isEqualToDictionary:source]) {
  405. _source = [source copy];
  406. if (_webView != nil) {
  407. [self visitSource];
  408. }
  409. }
  410. }
  411. - (void)setAllowingReadAccessToURL:(NSString *)allowingReadAccessToURL
  412. {
  413. if (![_allowingReadAccessToURL isEqualToString:allowingReadAccessToURL]) {
  414. _allowingReadAccessToURL = [allowingReadAccessToURL copy];
  415. if (_webView != nil) {
  416. [self visitSource];
  417. }
  418. }
  419. }
  420. - (void)setContentInset:(UIEdgeInsets)contentInset
  421. {
  422. _contentInset = contentInset;
  423. [RCTView autoAdjustInsetsForView:self
  424. withScrollView:_webView.scrollView
  425. updateOffset:NO];
  426. }
  427. - (void)refreshContentInset
  428. {
  429. [RCTView autoAdjustInsetsForView:self
  430. withScrollView:_webView.scrollView
  431. updateOffset:YES];
  432. }
  433. - (void)visitSource
  434. {
  435. // Check for a static html source first
  436. NSString *html = [RCTConvert NSString:_source[@"html"]];
  437. if (html) {
  438. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  439. if (!baseURL) {
  440. baseURL = [NSURL URLWithString:@"about:blank"];
  441. }
  442. [_webView loadHTMLString:html baseURL:baseURL];
  443. return;
  444. }
  445. NSURLRequest *request = [self requestForSource:_source];
  446. // Because of the way React works, as pages redirect, we actually end up
  447. // passing the redirect urls back here, so we ignore them if trying to load
  448. // the same url. We'll expose a call to 'reload' to allow a user to load
  449. // the existing page.
  450. if ([request.URL isEqual:_webView.URL]) {
  451. return;
  452. }
  453. if (!request.URL) {
  454. // Clear the webview
  455. [_webView loadHTMLString:@"" baseURL:nil];
  456. return;
  457. }
  458. if (request.URL.host) {
  459. [_webView loadRequest:request];
  460. }
  461. else {
  462. NSURL* readAccessUrl = _allowingReadAccessToURL ? [RCTConvert NSURL:_allowingReadAccessToURL] : request.URL;
  463. [_webView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];
  464. }
  465. }
  466. -(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
  467. {
  468. if (_webView == nil) {
  469. _savedKeyboardDisplayRequiresUserAction = keyboardDisplayRequiresUserAction;
  470. return;
  471. }
  472. if (_savedKeyboardDisplayRequiresUserAction == true) {
  473. return;
  474. }
  475. UIView* subview;
  476. for (UIView* view in _webView.scrollView.subviews) {
  477. if([[view.class description] hasPrefix:@"WK"])
  478. subview = view;
  479. }
  480. if(subview == nil) return;
  481. Class class = subview.class;
  482. NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
  483. NSOperatingSystemVersion iOS_12_2_0 = (NSOperatingSystemVersion){12, 2, 0};
  484. NSOperatingSystemVersion iOS_13_0_0 = (NSOperatingSystemVersion){13, 0, 0};
  485. Method method;
  486. IMP override;
  487. if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_13_0_0]) {
  488. // iOS 13.0.0 - Future
  489. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:");
  490. method = class_getInstanceMethod(class, selector);
  491. IMP original = method_getImplementation(method);
  492. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  493. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  494. });
  495. }
  496. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_12_2_0]) {
  497. // iOS 12.2.0 - iOS 13.0.0
  498. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  499. method = class_getInstanceMethod(class, selector);
  500. IMP original = method_getImplementation(method);
  501. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  502. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  503. });
  504. }
  505. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
  506. // iOS 11.3.0 - 12.2.0
  507. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  508. method = class_getInstanceMethod(class, selector);
  509. IMP original = method_getImplementation(method);
  510. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  511. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  512. });
  513. } else {
  514. // iOS 9.0 - 11.3.0
  515. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
  516. method = class_getInstanceMethod(class, selector);
  517. IMP original = method_getImplementation(method);
  518. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {
  519. ((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);
  520. });
  521. }
  522. method_setImplementation(method, override);
  523. }
  524. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  525. {
  526. if (_webView == nil) {
  527. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  528. return;
  529. }
  530. if (_savedHideKeyboardAccessoryView == false) {
  531. return;
  532. }
  533. UIView* subview;
  534. for (UIView* view in _webView.scrollView.subviews) {
  535. if([[view.class description] hasPrefix:@"WK"])
  536. subview = view;
  537. }
  538. if(subview == nil) return;
  539. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  540. Class newClass = NSClassFromString(name);
  541. if(newClass == nil)
  542. {
  543. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  544. if(!newClass) return;
  545. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  546. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  547. objc_registerClassPair(newClass);
  548. }
  549. object_setClass(subview, newClass);
  550. }
  551. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  552. {
  553. scrollView.decelerationRate = _decelerationRate;
  554. }
  555. - (void)setScrollEnabled:(BOOL)scrollEnabled
  556. {
  557. _scrollEnabled = scrollEnabled;
  558. _webView.scrollView.scrollEnabled = scrollEnabled;
  559. }
  560. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  561. {
  562. // Don't allow scrolling the scrollView.
  563. if (!_scrollEnabled) {
  564. scrollView.bounds = _webView.bounds;
  565. }
  566. else if (_onScroll != nil) {
  567. NSDictionary *event = @{
  568. @"contentOffset": @{
  569. @"x": @(scrollView.contentOffset.x),
  570. @"y": @(scrollView.contentOffset.y)
  571. },
  572. @"contentInset": @{
  573. @"top": @(scrollView.contentInset.top),
  574. @"left": @(scrollView.contentInset.left),
  575. @"bottom": @(scrollView.contentInset.bottom),
  576. @"right": @(scrollView.contentInset.right)
  577. },
  578. @"contentSize": @{
  579. @"width": @(scrollView.contentSize.width),
  580. @"height": @(scrollView.contentSize.height)
  581. },
  582. @"layoutMeasurement": @{
  583. @"width": @(scrollView.frame.size.width),
  584. @"height": @(scrollView.frame.size.height)
  585. },
  586. @"zoomScale": @(scrollView.zoomScale ?: 1),
  587. };
  588. _onScroll(event);
  589. }
  590. }
  591. - (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
  592. {
  593. _directionalLockEnabled = directionalLockEnabled;
  594. _webView.scrollView.directionalLockEnabled = directionalLockEnabled;
  595. }
  596. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  597. {
  598. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  599. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  600. }
  601. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  602. {
  603. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  604. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  605. }
  606. - (void)postMessage:(NSString *)message
  607. {
  608. NSDictionary *eventInitDict = @{@"data": message};
  609. NSString *source = [NSString
  610. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  611. RCTJSONStringify(eventInitDict, NULL)
  612. ];
  613. [self injectJavaScript: source];
  614. }
  615. - (void)layoutSubviews
  616. {
  617. [super layoutSubviews];
  618. // Ensure webview takes the position and dimensions of RNCWebView
  619. _webView.frame = self.bounds;
  620. _webView.scrollView.contentInset = _contentInset;
  621. }
  622. - (NSMutableDictionary<NSString *, id> *)baseEvent
  623. {
  624. NSDictionary *event = @{
  625. @"url": _webView.URL.absoluteString ?: @"",
  626. @"title": _webView.title ?: @"",
  627. @"loading" : @(_webView.loading),
  628. @"canGoBack": @(_webView.canGoBack),
  629. @"canGoForward" : @(_webView.canGoForward)
  630. };
  631. return [[NSMutableDictionary alloc] initWithDictionary: event];
  632. }
  633. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  634. clientAuthenticationCredential = credential;
  635. }
  636. + (void)setCustomCertificatesForHost:(nullable NSDictionary*)certificates {
  637. customCertificatesForHost = certificates;
  638. }
  639. - (void) webView:(WKWebView *)webView
  640. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  641. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  642. {
  643. NSString* host = nil;
  644. if (webView.URL != nil) {
  645. host = webView.URL.host;
  646. }
  647. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  648. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  649. return;
  650. }
  651. if ([[challenge protectionSpace] serverTrust] != nil && customCertificatesForHost != nil && host != nil) {
  652. SecCertificateRef localCertificate = (__bridge SecCertificateRef)([customCertificatesForHost objectForKey:host]);
  653. if (localCertificate != nil) {
  654. NSData *localCertificateData = (NSData*) CFBridgingRelease(SecCertificateCopyData(localCertificate));
  655. SecTrustRef trust = [[challenge protectionSpace] serverTrust];
  656. long count = SecTrustGetCertificateCount(trust);
  657. for (long i = 0; i < count; i++) {
  658. SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(trust, i);
  659. if (serverCertificate == nil) { continue; }
  660. NSData *serverCertificateData = (NSData *) CFBridgingRelease(SecCertificateCopyData(serverCertificate));
  661. if ([serverCertificateData isEqualToData:localCertificateData]) {
  662. NSURLCredential *useCredential = [NSURLCredential credentialForTrust:trust];
  663. if (challenge.sender != nil) {
  664. [challenge.sender useCredential:useCredential forAuthenticationChallenge:challenge];
  665. }
  666. completionHandler(NSURLSessionAuthChallengeUseCredential, useCredential);
  667. return;
  668. }
  669. }
  670. }
  671. }
  672. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  673. }
  674. #pragma mark - WKNavigationDelegate methods
  675. /**
  676. * alert
  677. */
  678. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  679. {
  680. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  681. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  682. completionHandler();
  683. }]];
  684. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  685. }
  686. /**
  687. * confirm
  688. */
  689. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  690. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  691. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  692. completionHandler(YES);
  693. }]];
  694. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  695. completionHandler(NO);
  696. }]];
  697. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  698. }
  699. /**
  700. * prompt
  701. */
  702. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  703. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  704. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  705. textField.text = defaultText;
  706. }];
  707. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  708. completionHandler([[alert.textFields lastObject] text]);
  709. }];
  710. [alert addAction:okAction];
  711. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  712. completionHandler(nil);
  713. }];
  714. [alert addAction:cancelAction];
  715. alert.preferredAction = okAction;
  716. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  717. }
  718. /**
  719. * topViewController
  720. */
  721. -(UIViewController *)topViewController{
  722. UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  723. return controller;
  724. }
  725. /**
  726. * topViewControllerWithRootViewController
  727. */
  728. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  729. if (viewController==nil) return nil;
  730. if (viewController.presentedViewController!=nil) {
  731. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  732. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  733. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  734. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  735. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  736. } else {
  737. return viewController;
  738. }
  739. }
  740. /**
  741. * getCurrentWindow
  742. */
  743. -(UIWindow *)getCurrentWindow{
  744. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  745. if (window.windowLevel!=UIWindowLevelNormal) {
  746. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  747. if (window.windowLevel==UIWindowLevelNormal) {
  748. window = wid;
  749. break;
  750. }
  751. }
  752. }
  753. return window;
  754. }
  755. /**
  756. * Decides whether to allow or cancel a navigation.
  757. * @see https://fburl.com/42r9fxob
  758. */
  759. - (void) webView:(WKWebView *)webView
  760. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  761. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  762. {
  763. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  764. static dispatch_once_t onceToken;
  765. dispatch_once(&onceToken, ^{
  766. navigationTypes = @{
  767. @(WKNavigationTypeLinkActivated): @"click",
  768. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  769. @(WKNavigationTypeBackForward): @"backforward",
  770. @(WKNavigationTypeReload): @"reload",
  771. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  772. @(WKNavigationTypeOther): @"other",
  773. };
  774. });
  775. WKNavigationType navigationType = navigationAction.navigationType;
  776. NSURLRequest *request = navigationAction.request;
  777. if (_onShouldStartLoadWithRequest) {
  778. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  779. [event addEntriesFromDictionary: @{
  780. @"url": (request.URL).absoluteString,
  781. @"mainDocumentURL": (request.mainDocumentURL).absoluteString,
  782. @"navigationType": navigationTypes[@(navigationType)]
  783. }];
  784. if (![self.delegate webView:self
  785. shouldStartLoadForRequest:event
  786. withCallback:_onShouldStartLoadWithRequest]) {
  787. decisionHandler(WKNavigationActionPolicyCancel);
  788. return;
  789. }
  790. }
  791. if (_onLoadingStart) {
  792. // We have this check to filter out iframe requests and whatnot
  793. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  794. if (isTopFrame) {
  795. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  796. [event addEntriesFromDictionary: @{
  797. @"url": (request.URL).absoluteString,
  798. @"navigationType": navigationTypes[@(navigationType)]
  799. }];
  800. _onLoadingStart(event);
  801. }
  802. }
  803. // Allow all navigation by default
  804. decisionHandler(WKNavigationActionPolicyAllow);
  805. }
  806. /**
  807. * Called when the web view’s content process is terminated.
  808. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi?language=objc
  809. */
  810. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
  811. {
  812. RCTLogWarn(@"Webview Process Terminated");
  813. if (_onContentProcessDidTerminate) {
  814. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  815. _onContentProcessDidTerminate(event);
  816. }
  817. }
  818. /**
  819. * Decides whether to allow or cancel a navigation after its response is known.
  820. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview?language=objc
  821. */
  822. - (void) webView:(WKWebView *)webView
  823. decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
  824. decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
  825. {
  826. if (_onHttpError && navigationResponse.forMainFrame) {
  827. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  828. NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
  829. NSInteger statusCode = response.statusCode;
  830. if (statusCode >= 400) {
  831. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  832. [event addEntriesFromDictionary: @{
  833. @"url": response.URL.absoluteString,
  834. @"statusCode": @(statusCode)
  835. }];
  836. _onHttpError(event);
  837. }
  838. }
  839. }
  840. decisionHandler(WKNavigationResponsePolicyAllow);
  841. }
  842. /**
  843. * Called when an error occurs while the web view is loading content.
  844. * @see https://fburl.com/km6vqenw
  845. */
  846. - (void) webView:(WKWebView *)webView
  847. didFailProvisionalNavigation:(WKNavigation *)navigation
  848. withError:(NSError *)error
  849. {
  850. if (_onLoadingError) {
  851. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  852. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  853. // a new URL in the WebView before the previous one came back. We can just
  854. // ignore these since they aren't real errors.
  855. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  856. return;
  857. }
  858. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102 || [error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 101) {
  859. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  860. // when the URL is from an http redirect. This is a common pattern when
  861. // implementing OAuth with a WebView.
  862. return;
  863. }
  864. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  865. [event addEntriesFromDictionary:@{
  866. @"didFailProvisionalNavigation": @YES,
  867. @"domain": error.domain,
  868. @"code": @(error.code),
  869. @"description": error.localizedDescription,
  870. }];
  871. _onLoadingError(event);
  872. }
  873. }
  874. - (void)evaluateJS:(NSString *)js
  875. thenCall: (void (^)(NSString*)) callback
  876. {
  877. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  878. if (callback != nil) {
  879. callback([NSString stringWithFormat:@"%@", result]);
  880. }
  881. if (error != nil) {
  882. RCTLogWarn(@"%@", [NSString stringWithFormat:@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string. %@", error]);
  883. }
  884. }];
  885. }
  886. /**
  887. * Called when the navigation is complete.
  888. * @see https://fburl.com/rtys6jlb
  889. */
  890. - (void)webView:(WKWebView *)webView
  891. didFinishNavigation:(WKNavigation *)navigation
  892. {
  893. if (_injectedJavaScript) {
  894. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  895. NSMutableDictionary *event = [self baseEvent];
  896. event[@"jsEvaluationValue"] = jsEvaluationValue;
  897. if (self.onLoadingFinish) {
  898. self.onLoadingFinish(event);
  899. }
  900. }];
  901. } else if (_onLoadingFinish) {
  902. _onLoadingFinish([self baseEvent]);
  903. }
  904. }
  905. - (void)injectJavaScript:(NSString *)script
  906. {
  907. [self evaluateJS: script thenCall: nil];
  908. }
  909. - (void)goForward
  910. {
  911. [_webView goForward];
  912. }
  913. - (void)goBack
  914. {
  915. [_webView goBack];
  916. }
  917. - (void)reload
  918. {
  919. /**
  920. * When the initial load fails due to network connectivity issues,
  921. * [_webView reload] doesn't reload the webpage. Therefore, we must
  922. * manually call [_webView loadRequest:request].
  923. */
  924. NSURLRequest *request = [self requestForSource:self.source];
  925. if (request.URL && !_webView.URL.absoluteString.length) {
  926. [_webView loadRequest:request];
  927. } else {
  928. [_webView reload];
  929. }
  930. }
  931. - (void)stopLoading
  932. {
  933. [_webView stopLoading];
  934. }
  935. - (void)setBounces:(BOOL)bounces
  936. {
  937. _bounces = bounces;
  938. _webView.scrollView.bounces = bounces;
  939. }
  940. - (NSURLRequest *)requestForSource:(id)json {
  941. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  942. // If sharedCookiesEnabled we automatically add all application cookies to the
  943. // http request. This is automatically done on iOS 11+ in the WebView constructor.
  944. // Se we need to manually add these shared cookies here only for iOS versions < 11.
  945. if (_sharedCookiesEnabled) {
  946. if (@available(iOS 11.0, *)) {
  947. // see WKWebView initialization for added cookies
  948. } else {
  949. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
  950. NSDictionary<NSString *, NSString *> *cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
  951. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  952. [mutableRequest setAllHTTPHeaderFields:cookieHeader];
  953. return mutableRequest;
  954. }
  955. }
  956. return request;
  957. }
  958. @end