No Description

RNCWebView.m 37KB

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