react-native-webview.git

RNCWebView.m 46KB

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