Ingen beskrivning

RNCWebView.m 47KB

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