react-native-webview.git

RNCWebView.m 42KB

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