暂无描述

RNCWebView.m 39KB

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