react-native-webview.git

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