No Description

RNCWebView.m 51KB

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