No Description

RNCWebView.m 52KB

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