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