react-native-webview.git

RNCWebView.m 42KB

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