Keine Beschreibung

RNCWebView.m 48KB

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