No Description

RNCWebView.m 51KB

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