Ei kuvausta

RNCWebView.m 45KB

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