react-native-webview.git

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