react-native-webview.git

RNCWebView.m 45KB

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