설명 없음

RNCWebView.m 38KB

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