No Description

RNCWebView.m 35KB

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