react-native-webview.git

RNCWebView.m 47KB

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