react-native-webview.git

RNCWebView.m 45KB

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