Brak opisu

RNCWebView.m 52KB

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