Нет описания

RNCWebView.m 50KB

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