Nav apraksta

RNCWebView.m 51KB

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