Ei kuvausta

RNCWebView.m 53KB

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