No Description

RNCWebView.m 51KB

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