설명 없음

RNCWebView.m 38KB

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