Sin descripción

RNCWebView.m 51KB

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