react-native-webview.git

RNCWebView.m 46KB

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