react-native-webview.git

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