react-native-webview.git

RNCWebView.m 45KB

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