No Description

RNCWebView.m 53KB

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