No Description

RNCWebView.m 42KB

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