No Description

RNCWebView.m 41KB

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