react-native-webview.git

RNCWebView.m 43KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158
  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. #endif // !TARGET_OS_OSX
  392. }
  393. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  394. - (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
  395. {
  396. _savedContentInsetAdjustmentBehavior = behavior;
  397. if (_webView == nil) {
  398. return;
  399. }
  400. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  401. CGPoint contentOffset = _webView.scrollView.contentOffset;
  402. _webView.scrollView.contentInsetAdjustmentBehavior = behavior;
  403. _webView.scrollView.contentOffset = contentOffset;
  404. }
  405. }
  406. #endif
  407. /**
  408. * This method is called whenever JavaScript running within the web view calls:
  409. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  410. */
  411. - (void)userContentController:(WKUserContentController *)userContentController
  412. didReceiveScriptMessage:(WKScriptMessage *)message
  413. {
  414. if ([message.name isEqualToString:HistoryShimName]) {
  415. if (_onLoadingFinish) {
  416. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  417. [event addEntriesFromDictionary: @{@"navigationType": message.body}];
  418. _onLoadingFinish(event);
  419. }
  420. } else if ([message.name isEqualToString:MessageHandlerName]) {
  421. if (_onMessage) {
  422. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  423. [event addEntriesFromDictionary: @{@"data": message.body}];
  424. _onMessage(event);
  425. }
  426. }
  427. }
  428. - (void)setSource:(NSDictionary *)source
  429. {
  430. if (![_source isEqualToDictionary:source]) {
  431. _source = [source copy];
  432. if (_webView != nil) {
  433. [self visitSource];
  434. }
  435. }
  436. }
  437. - (void)setAllowingReadAccessToURL:(NSString *)allowingReadAccessToURL
  438. {
  439. if (![_allowingReadAccessToURL isEqualToString:allowingReadAccessToURL]) {
  440. _allowingReadAccessToURL = [allowingReadAccessToURL copy];
  441. if (_webView != nil) {
  442. [self visitSource];
  443. }
  444. }
  445. }
  446. - (void)setContentInset:(UIEdgeInsets)contentInset
  447. {
  448. _contentInset = contentInset;
  449. [RCTView autoAdjustInsetsForView:self
  450. #if !TARGET_OS_OSX
  451. withScrollView:_webView.scrollView
  452. #else
  453. withScrollView:nil
  454. #endif // !TARGET_OS_OSX
  455. updateOffset:NO];
  456. }
  457. - (void)refreshContentInset
  458. {
  459. [RCTView autoAdjustInsetsForView:self
  460. #if !TARGET_OS_OSX
  461. withScrollView:_webView.scrollView
  462. #else
  463. withScrollView:nil
  464. #endif // !TARGET_OS_OSX
  465. updateOffset:YES];
  466. }
  467. - (void)visitSource
  468. {
  469. // Check for a static html source first
  470. NSString *html = [RCTConvert NSString:_source[@"html"]];
  471. if (html) {
  472. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  473. if (!baseURL) {
  474. baseURL = [NSURL URLWithString:@"about:blank"];
  475. }
  476. [_webView loadHTMLString:html baseURL:baseURL];
  477. return;
  478. }
  479. NSURLRequest *request = [self requestForSource:_source];
  480. // Because of the way React works, as pages redirect, we actually end up
  481. // passing the redirect urls back here, so we ignore them if trying to load
  482. // the same url. We'll expose a call to 'reload' to allow a user to load
  483. // the existing page.
  484. if ([request.URL isEqual:_webView.URL]) {
  485. return;
  486. }
  487. if (!request.URL) {
  488. // Clear the webview
  489. [_webView loadHTMLString:@"" baseURL:nil];
  490. return;
  491. }
  492. if (request.URL.host) {
  493. [_webView loadRequest:request];
  494. }
  495. else {
  496. NSURL* readAccessUrl = _allowingReadAccessToURL ? [RCTConvert NSURL:_allowingReadAccessToURL] : request.URL;
  497. [_webView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];
  498. }
  499. }
  500. #if !TARGET_OS_OSX
  501. -(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
  502. {
  503. if (_webView == nil) {
  504. _savedKeyboardDisplayRequiresUserAction = keyboardDisplayRequiresUserAction;
  505. return;
  506. }
  507. if (_savedKeyboardDisplayRequiresUserAction == true) {
  508. return;
  509. }
  510. UIView* subview;
  511. for (UIView* view in _webView.scrollView.subviews) {
  512. if([[view.class description] hasPrefix:@"WK"])
  513. subview = view;
  514. }
  515. if(subview == nil) return;
  516. Class class = subview.class;
  517. NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
  518. NSOperatingSystemVersion iOS_12_2_0 = (NSOperatingSystemVersion){12, 2, 0};
  519. NSOperatingSystemVersion iOS_13_0_0 = (NSOperatingSystemVersion){13, 0, 0};
  520. Method method;
  521. IMP override;
  522. if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_13_0_0]) {
  523. // iOS 13.0.0 - Future
  524. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:");
  525. method = class_getInstanceMethod(class, selector);
  526. IMP original = method_getImplementation(method);
  527. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  528. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  529. });
  530. }
  531. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_12_2_0]) {
  532. // iOS 12.2.0 - iOS 13.0.0
  533. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  534. method = class_getInstanceMethod(class, selector);
  535. IMP original = method_getImplementation(method);
  536. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  537. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  538. });
  539. }
  540. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
  541. // iOS 11.3.0 - 12.2.0
  542. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  543. method = class_getInstanceMethod(class, selector);
  544. IMP original = method_getImplementation(method);
  545. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  546. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  547. });
  548. } else {
  549. // iOS 9.0 - 11.3.0
  550. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:userObject:");
  551. method = class_getInstanceMethod(class, selector);
  552. IMP original = method_getImplementation(method);
  553. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, id arg3) {
  554. ((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);
  555. });
  556. }
  557. method_setImplementation(method, override);
  558. }
  559. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  560. {
  561. if (_webView == nil) {
  562. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  563. return;
  564. }
  565. if (_savedHideKeyboardAccessoryView == false) {
  566. return;
  567. }
  568. UIView* subview;
  569. for (UIView* view in _webView.scrollView.subviews) {
  570. if([[view.class description] hasPrefix:@"WK"])
  571. subview = view;
  572. }
  573. if(subview == nil) return;
  574. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  575. Class newClass = NSClassFromString(name);
  576. if(newClass == nil)
  577. {
  578. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  579. if(!newClass) return;
  580. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  581. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  582. objc_registerClassPair(newClass);
  583. }
  584. object_setClass(subview, newClass);
  585. }
  586. #endif // !TARGET_OS_OSX
  587. - (void)scrollViewWillBeginDragging:(RCTUIScrollView *)scrollView
  588. {
  589. #if !TARGET_OS_OSX
  590. scrollView.decelerationRate = _decelerationRate;
  591. #endif // !TARGET_OS_OSX
  592. }
  593. - (void)setScrollEnabled:(BOOL)scrollEnabled
  594. {
  595. _scrollEnabled = scrollEnabled;
  596. #if !TARGET_OS_OSX
  597. _webView.scrollView.scrollEnabled = scrollEnabled;
  598. #endif // !TARGET_OS_OSX
  599. }
  600. - (void)scrollViewDidScroll:(RCTUIScrollView *)scrollView
  601. {
  602. // Don't allow scrolling the scrollView.
  603. if (!_scrollEnabled) {
  604. scrollView.bounds = _webView.bounds;
  605. }
  606. else if (_onScroll != nil) {
  607. NSDictionary *event = @{
  608. @"contentOffset": @{
  609. @"x": @(scrollView.contentOffset.x),
  610. @"y": @(scrollView.contentOffset.y)
  611. },
  612. @"contentInset": @{
  613. @"top": @(scrollView.contentInset.top),
  614. @"left": @(scrollView.contentInset.left),
  615. @"bottom": @(scrollView.contentInset.bottom),
  616. @"right": @(scrollView.contentInset.right)
  617. },
  618. @"contentSize": @{
  619. @"width": @(scrollView.contentSize.width),
  620. @"height": @(scrollView.contentSize.height)
  621. },
  622. @"layoutMeasurement": @{
  623. @"width": @(scrollView.frame.size.width),
  624. @"height": @(scrollView.frame.size.height)
  625. },
  626. @"zoomScale": @(scrollView.zoomScale ?: 1),
  627. };
  628. _onScroll(event);
  629. }
  630. }
  631. - (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
  632. {
  633. _directionalLockEnabled = directionalLockEnabled;
  634. #if !TARGET_OS_OSX
  635. _webView.scrollView.directionalLockEnabled = directionalLockEnabled;
  636. #endif // !TARGET_OS_OSX
  637. }
  638. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  639. {
  640. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  641. #if !TARGET_OS_OSX
  642. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  643. #endif // !TARGET_OS_OSX
  644. }
  645. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  646. {
  647. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  648. #if !TARGET_OS_OSX
  649. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  650. #endif // !TARGET_OS_OSX
  651. }
  652. - (void)postMessage:(NSString *)message
  653. {
  654. NSDictionary *eventInitDict = @{@"data": message};
  655. NSString *source = [NSString
  656. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  657. RCTJSONStringify(eventInitDict, NULL)
  658. ];
  659. [self injectJavaScript: source];
  660. }
  661. - (void)layoutSubviews
  662. {
  663. [super layoutSubviews];
  664. // Ensure webview takes the position and dimensions of RNCWebView
  665. _webView.frame = self.bounds;
  666. #if !TARGET_OS_OSX
  667. _webView.scrollView.contentInset = _contentInset;
  668. #endif // !TARGET_OS_OSX
  669. }
  670. - (NSMutableDictionary<NSString *, id> *)baseEvent
  671. {
  672. NSDictionary *event = @{
  673. @"url": _webView.URL.absoluteString ?: @"",
  674. @"title": _webView.title ?: @"",
  675. @"loading" : @(_webView.loading),
  676. @"canGoBack": @(_webView.canGoBack),
  677. @"canGoForward" : @(_webView.canGoForward)
  678. };
  679. return [[NSMutableDictionary alloc] initWithDictionary: event];
  680. }
  681. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  682. clientAuthenticationCredential = credential;
  683. }
  684. + (void)setCustomCertificatesForHost:(nullable NSDictionary*)certificates {
  685. customCertificatesForHost = certificates;
  686. }
  687. - (void) webView:(WKWebView *)webView
  688. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  689. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  690. {
  691. NSString* host = nil;
  692. if (webView.URL != nil) {
  693. host = webView.URL.host;
  694. }
  695. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  696. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  697. return;
  698. }
  699. if ([[challenge protectionSpace] serverTrust] != nil && customCertificatesForHost != nil && host != nil) {
  700. SecCertificateRef localCertificate = (__bridge SecCertificateRef)([customCertificatesForHost objectForKey:host]);
  701. if (localCertificate != nil) {
  702. NSData *localCertificateData = (NSData*) CFBridgingRelease(SecCertificateCopyData(localCertificate));
  703. SecTrustRef trust = [[challenge protectionSpace] serverTrust];
  704. long count = SecTrustGetCertificateCount(trust);
  705. for (long i = 0; i < count; i++) {
  706. SecCertificateRef serverCertificate = SecTrustGetCertificateAtIndex(trust, i);
  707. if (serverCertificate == nil) { continue; }
  708. NSData *serverCertificateData = (NSData *) CFBridgingRelease(SecCertificateCopyData(serverCertificate));
  709. if ([serverCertificateData isEqualToData:localCertificateData]) {
  710. NSURLCredential *useCredential = [NSURLCredential credentialForTrust:trust];
  711. if (challenge.sender != nil) {
  712. [challenge.sender useCredential:useCredential forAuthenticationChallenge:challenge];
  713. }
  714. completionHandler(NSURLSessionAuthChallengeUseCredential, useCredential);
  715. return;
  716. }
  717. }
  718. }
  719. }
  720. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  721. }
  722. #pragma mark - WKNavigationDelegate methods
  723. /**
  724. * alert
  725. */
  726. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  727. {
  728. #if !TARGET_OS_OSX
  729. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  730. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  731. completionHandler();
  732. }]];
  733. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  734. #else
  735. // TODO
  736. #endif // !TARGET_OS_OSX
  737. }
  738. /**
  739. * confirm
  740. */
  741. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  742. #if !TARGET_OS_OSX
  743. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  744. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  745. completionHandler(YES);
  746. }]];
  747. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  748. completionHandler(NO);
  749. }]];
  750. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  751. #else
  752. // TODO
  753. #endif // !TARGET_OS_OSX
  754. }
  755. /**
  756. * prompt
  757. */
  758. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  759. #if !TARGET_OS_OSX
  760. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  761. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  762. textField.text = defaultText;
  763. }];
  764. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  765. completionHandler([[alert.textFields lastObject] text]);
  766. }];
  767. [alert addAction:okAction];
  768. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  769. completionHandler(nil);
  770. }];
  771. [alert addAction:cancelAction];
  772. alert.preferredAction = okAction;
  773. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  774. #else
  775. // TODO
  776. #endif // !TARGET_OS_OSX
  777. }
  778. #if !TARGET_OS_OSX
  779. /**
  780. * topViewController
  781. */
  782. -(UIViewController *)topViewController{
  783. UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  784. return controller;
  785. }
  786. /**
  787. * topViewControllerWithRootViewController
  788. */
  789. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  790. if (viewController==nil) return nil;
  791. if (viewController.presentedViewController!=nil) {
  792. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  793. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  794. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  795. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  796. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  797. } else {
  798. return viewController;
  799. }
  800. }
  801. /**
  802. * getCurrentWindow
  803. */
  804. -(UIWindow *)getCurrentWindow{
  805. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  806. if (window.windowLevel!=UIWindowLevelNormal) {
  807. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  808. if (window.windowLevel==UIWindowLevelNormal) {
  809. window = wid;
  810. break;
  811. }
  812. }
  813. }
  814. return window;
  815. }
  816. #endif // !TARGET_OS_OSX
  817. /**
  818. * Decides whether to allow or cancel a navigation.
  819. * @see https://fburl.com/42r9fxob
  820. */
  821. - (void) webView:(WKWebView *)webView
  822. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  823. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  824. {
  825. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  826. static dispatch_once_t onceToken;
  827. dispatch_once(&onceToken, ^{
  828. navigationTypes = @{
  829. @(WKNavigationTypeLinkActivated): @"click",
  830. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  831. @(WKNavigationTypeBackForward): @"backforward",
  832. @(WKNavigationTypeReload): @"reload",
  833. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  834. @(WKNavigationTypeOther): @"other",
  835. };
  836. });
  837. WKNavigationType navigationType = navigationAction.navigationType;
  838. NSURLRequest *request = navigationAction.request;
  839. if (_onShouldStartLoadWithRequest) {
  840. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  841. [event addEntriesFromDictionary: @{
  842. @"url": (request.URL).absoluteString,
  843. @"mainDocumentURL": (request.mainDocumentURL).absoluteString,
  844. @"navigationType": navigationTypes[@(navigationType)]
  845. }];
  846. if (![self.delegate webView:self
  847. shouldStartLoadForRequest:event
  848. withCallback:_onShouldStartLoadWithRequest]) {
  849. decisionHandler(WKNavigationActionPolicyCancel);
  850. return;
  851. }
  852. }
  853. if (_onLoadingStart) {
  854. // We have this check to filter out iframe requests and whatnot
  855. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  856. if (isTopFrame) {
  857. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  858. [event addEntriesFromDictionary: @{
  859. @"url": (request.URL).absoluteString,
  860. @"navigationType": navigationTypes[@(navigationType)]
  861. }];
  862. _onLoadingStart(event);
  863. }
  864. }
  865. // Allow all navigation by default
  866. decisionHandler(WKNavigationActionPolicyAllow);
  867. }
  868. /**
  869. * Called when the web view’s content process is terminated.
  870. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455639-webviewwebcontentprocessdidtermi?language=objc
  871. */
  872. - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView
  873. {
  874. RCTLogWarn(@"Webview Process Terminated");
  875. if (_onContentProcessDidTerminate) {
  876. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  877. _onContentProcessDidTerminate(event);
  878. }
  879. }
  880. /**
  881. * Decides whether to allow or cancel a navigation after its response is known.
  882. * @see https://developer.apple.com/documentation/webkit/wknavigationdelegate/1455643-webview?language=objc
  883. */
  884. - (void) webView:(WKWebView *)webView
  885. decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse
  886. decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
  887. {
  888. if (_onHttpError && navigationResponse.forMainFrame) {
  889. if ([navigationResponse.response isKindOfClass:[NSHTTPURLResponse class]]) {
  890. NSHTTPURLResponse *response = (NSHTTPURLResponse *)navigationResponse.response;
  891. NSInteger statusCode = response.statusCode;
  892. if (statusCode >= 400) {
  893. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  894. [event addEntriesFromDictionary: @{
  895. @"url": response.URL.absoluteString,
  896. @"statusCode": @(statusCode)
  897. }];
  898. _onHttpError(event);
  899. }
  900. }
  901. }
  902. decisionHandler(WKNavigationResponsePolicyAllow);
  903. }
  904. /**
  905. * Called when an error occurs while the web view is loading content.
  906. * @see https://fburl.com/km6vqenw
  907. */
  908. - (void) webView:(WKWebView *)webView
  909. didFailProvisionalNavigation:(WKNavigation *)navigation
  910. withError:(NSError *)error
  911. {
  912. if (_onLoadingError) {
  913. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  914. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  915. // a new URL in the WebView before the previous one came back. We can just
  916. // ignore these since they aren't real errors.
  917. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  918. return;
  919. }
  920. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102 || [error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 101) {
  921. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  922. // when the URL is from an http redirect. This is a common pattern when
  923. // implementing OAuth with a WebView.
  924. return;
  925. }
  926. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  927. [event addEntriesFromDictionary:@{
  928. @"didFailProvisionalNavigation": @YES,
  929. @"domain": error.domain,
  930. @"code": @(error.code),
  931. @"description": error.localizedDescription,
  932. }];
  933. _onLoadingError(event);
  934. }
  935. }
  936. - (void)evaluateJS:(NSString *)js
  937. thenCall: (void (^)(NSString*)) callback
  938. {
  939. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  940. if (callback != nil) {
  941. callback([NSString stringWithFormat:@"%@", result]);
  942. }
  943. if (error != nil) {
  944. 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]);
  945. }
  946. }];
  947. }
  948. /**
  949. * Called when the navigation is complete.
  950. * @see https://fburl.com/rtys6jlb
  951. */
  952. - (void)webView:(WKWebView *)webView
  953. didFinishNavigation:(WKNavigation *)navigation
  954. {
  955. if (_injectedJavaScript) {
  956. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  957. NSMutableDictionary *event = [self baseEvent];
  958. event[@"jsEvaluationValue"] = jsEvaluationValue;
  959. if (self.onLoadingFinish) {
  960. self.onLoadingFinish(event);
  961. }
  962. }];
  963. } else if (_onLoadingFinish) {
  964. _onLoadingFinish([self baseEvent]);
  965. }
  966. }
  967. - (void)injectJavaScript:(NSString *)script
  968. {
  969. [self evaluateJS: script thenCall: nil];
  970. }
  971. - (void)goForward
  972. {
  973. [_webView goForward];
  974. }
  975. - (void)goBack
  976. {
  977. [_webView goBack];
  978. }
  979. - (void)reload
  980. {
  981. /**
  982. * When the initial load fails due to network connectivity issues,
  983. * [_webView reload] doesn't reload the webpage. Therefore, we must
  984. * manually call [_webView loadRequest:request].
  985. */
  986. NSURLRequest *request = [self requestForSource:self.source];
  987. if (request.URL && !_webView.URL.absoluteString.length) {
  988. [_webView loadRequest:request];
  989. } else {
  990. [_webView reload];
  991. }
  992. }
  993. - (void)stopLoading
  994. {
  995. [_webView stopLoading];
  996. }
  997. - (void)setBounces:(BOOL)bounces
  998. {
  999. _bounces = bounces;
  1000. #if !TARGET_OS_OSX
  1001. _webView.scrollView.bounces = bounces;
  1002. #endif // !TARGET_OS_OSX
  1003. }
  1004. - (NSURLRequest *)requestForSource:(id)json {
  1005. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  1006. // If sharedCookiesEnabled we automatically add all application cookies to the
  1007. // http request. This is automatically done on iOS 11+ in the WebView constructor.
  1008. // Se we need to manually add these shared cookies here only for iOS versions < 11.
  1009. if (_sharedCookiesEnabled) {
  1010. if (@available(iOS 11.0, *)) {
  1011. // see WKWebView initialization for added cookies
  1012. } else {
  1013. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
  1014. NSDictionary<NSString *, NSString *> *cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
  1015. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  1016. [mutableRequest setAllHTTPHeaderFields:cookieHeader];
  1017. return mutableRequest;
  1018. }
  1019. }
  1020. return request;
  1021. }
  1022. @end
  1023. @implementation RNCWeakScriptMessageDelegate
  1024. - (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate {
  1025. self = [super init];
  1026. if (self) {
  1027. _scriptDelegate = scriptDelegate;
  1028. }
  1029. return self;
  1030. }
  1031. - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
  1032. [self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
  1033. }
  1034. @end