暫無描述

RNCWebView.m 38KB

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