説明なし

RNCWebView.m 48KB

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