Bez popisu

RNCWebView.m 35KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944
  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. _webView.scrollView.delegate = self;
  200. _webView.UIDelegate = self;
  201. _webView.navigationDelegate = self;
  202. _webView.scrollView.scrollEnabled = _scrollEnabled;
  203. _webView.scrollView.pagingEnabled = _pagingEnabled;
  204. _webView.scrollView.bounces = _bounces;
  205. _webView.scrollView.showsHorizontalScrollIndicator = _showsHorizontalScrollIndicator;
  206. _webView.scrollView.showsVerticalScrollIndicator = _showsVerticalScrollIndicator;
  207. _webView.scrollView.directionalLockEnabled = _directionalLockEnabled;
  208. _webView.allowsLinkPreview = _allowsLinkPreview;
  209. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  210. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  211. if (_userAgent) {
  212. _webView.customUserAgent = _userAgent;
  213. }
  214. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  215. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  216. _webView.scrollView.contentInsetAdjustmentBehavior = _savedContentInsetAdjustmentBehavior;
  217. }
  218. #endif
  219. [self addSubview:_webView];
  220. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  221. [self setKeyboardDisplayRequiresUserAction: _savedKeyboardDisplayRequiresUserAction];
  222. [self visitSource];
  223. }
  224. }
  225. // Update webview property when the component prop changes.
  226. - (void)setAllowsBackForwardNavigationGestures:(BOOL)allowsBackForwardNavigationGestures {
  227. _allowsBackForwardNavigationGestures = allowsBackForwardNavigationGestures;
  228. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  229. }
  230. - (void)removeFromSuperview
  231. {
  232. if (_webView) {
  233. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHandlerName];
  234. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  235. [_webView removeFromSuperview];
  236. _webView.scrollView.delegate = nil;
  237. _webView = nil;
  238. }
  239. [super removeFromSuperview];
  240. }
  241. -(void)toggleFullScreenVideoStatusBars
  242. {
  243. #pragma clang diagnostic ignored "-Wdeprecated-declarations"
  244. if (!_isFullScreenVideoOpen) {
  245. _isFullScreenVideoOpen = YES;
  246. RCTUnsafeExecuteOnMainQueueSync(^{
  247. [RCTSharedApplication() setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
  248. });
  249. } else {
  250. _isFullScreenVideoOpen = NO;
  251. RCTUnsafeExecuteOnMainQueueSync(^{
  252. [RCTSharedApplication() setStatusBarHidden:_savedStatusBarHidden animated:YES];
  253. [RCTSharedApplication() setStatusBarStyle:_savedStatusBarStyle animated:YES];
  254. });
  255. }
  256. #pragma clang diagnostic pop
  257. }
  258. -(void)keyboardWillHide
  259. {
  260. keyboardTimer = [NSTimer scheduledTimerWithTimeInterval:0 target:self selector:@selector(keyboardDisplacementFix) userInfo:nil repeats:false];
  261. [[NSRunLoop mainRunLoop] addTimer:keyboardTimer forMode:NSRunLoopCommonModes];
  262. }
  263. -(void)keyboardWillShow
  264. {
  265. if (keyboardTimer != nil) {
  266. [keyboardTimer invalidate];
  267. }
  268. }
  269. -(void)keyboardDisplacementFix
  270. {
  271. // Additional viewport checks to prevent unintentional scrolls
  272. UIScrollView *scrollView = self.webView.scrollView;
  273. double maxContentOffset = scrollView.contentSize.height - scrollView.frame.size.height;
  274. if (maxContentOffset < 0) {
  275. maxContentOffset = 0;
  276. }
  277. if (scrollView.contentOffset.y > maxContentOffset) {
  278. // https://stackoverflow.com/a/9637807/824966
  279. [UIView animateWithDuration:.25 animations:^{
  280. scrollView.contentOffset = CGPointMake(0, maxContentOffset);
  281. }];
  282. }
  283. }
  284. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  285. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  286. if(_onLoadingProgress){
  287. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  288. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  289. _onLoadingProgress(event);
  290. }
  291. }else{
  292. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  293. }
  294. }
  295. - (void)setBackgroundColor:(UIColor *)backgroundColor
  296. {
  297. _savedBackgroundColor = backgroundColor;
  298. if (_webView == nil) {
  299. return;
  300. }
  301. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  302. self.opaque = _webView.opaque = (alpha == 1.0);
  303. _webView.scrollView.backgroundColor = backgroundColor;
  304. _webView.backgroundColor = backgroundColor;
  305. }
  306. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  307. - (void)setContentInsetAdjustmentBehavior:(UIScrollViewContentInsetAdjustmentBehavior)behavior
  308. {
  309. _savedContentInsetAdjustmentBehavior = behavior;
  310. if (_webView == nil) {
  311. return;
  312. }
  313. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  314. CGPoint contentOffset = _webView.scrollView.contentOffset;
  315. _webView.scrollView.contentInsetAdjustmentBehavior = behavior;
  316. _webView.scrollView.contentOffset = contentOffset;
  317. }
  318. }
  319. #endif
  320. /**
  321. * This method is called whenever JavaScript running within the web view calls:
  322. * - window.webkit.messageHandlers[MessageHandlerName].postMessage
  323. */
  324. - (void)userContentController:(WKUserContentController *)userContentController
  325. didReceiveScriptMessage:(WKScriptMessage *)message
  326. {
  327. if (_onMessage != nil) {
  328. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  329. [event addEntriesFromDictionary: @{@"data": message.body}];
  330. _onMessage(event);
  331. }
  332. }
  333. - (void)setSource:(NSDictionary *)source
  334. {
  335. if (![_source isEqualToDictionary:source]) {
  336. _source = [source copy];
  337. if (_webView != nil) {
  338. [self visitSource];
  339. }
  340. }
  341. }
  342. - (void)setAllowingReadAccessToURL:(NSString *)allowingReadAccessToURL
  343. {
  344. if (![_allowingReadAccessToURL isEqualToString:allowingReadAccessToURL]) {
  345. _allowingReadAccessToURL = [allowingReadAccessToURL copy];
  346. if (_webView != nil) {
  347. [self visitSource];
  348. }
  349. }
  350. }
  351. - (void)setContentInset:(UIEdgeInsets)contentInset
  352. {
  353. _contentInset = contentInset;
  354. [RCTView autoAdjustInsetsForView:self
  355. withScrollView:_webView.scrollView
  356. updateOffset:NO];
  357. }
  358. - (void)refreshContentInset
  359. {
  360. [RCTView autoAdjustInsetsForView:self
  361. withScrollView:_webView.scrollView
  362. updateOffset:YES];
  363. }
  364. - (void)visitSource
  365. {
  366. // Check for a static html source first
  367. NSString *html = [RCTConvert NSString:_source[@"html"]];
  368. if (html) {
  369. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  370. if (!baseURL) {
  371. baseURL = [NSURL URLWithString:@"about:blank"];
  372. }
  373. [_webView loadHTMLString:html baseURL:baseURL];
  374. return;
  375. }
  376. NSURLRequest *request = [self requestForSource:_source];
  377. // Because of the way React works, as pages redirect, we actually end up
  378. // passing the redirect urls back here, so we ignore them if trying to load
  379. // the same url. We'll expose a call to 'reload' to allow a user to load
  380. // the existing page.
  381. if ([request.URL isEqual:_webView.URL]) {
  382. return;
  383. }
  384. if (!request.URL) {
  385. // Clear the webview
  386. [_webView loadHTMLString:@"" baseURL:nil];
  387. return;
  388. }
  389. if (request.URL.host) {
  390. [_webView loadRequest:request];
  391. }
  392. else {
  393. NSURL* readAccessUrl = _allowingReadAccessToURL ? [NSURL URLWithString:_allowingReadAccessToURL] : request.URL;
  394. [_webView loadFileURL:request.URL allowingReadAccessToURL:readAccessUrl];
  395. }
  396. }
  397. -(void)setKeyboardDisplayRequiresUserAction:(BOOL)keyboardDisplayRequiresUserAction
  398. {
  399. if (_webView == nil) {
  400. _savedKeyboardDisplayRequiresUserAction = keyboardDisplayRequiresUserAction;
  401. return;
  402. }
  403. if (_savedKeyboardDisplayRequiresUserAction == true) {
  404. return;
  405. }
  406. UIView* subview;
  407. for (UIView* view in _webView.scrollView.subviews) {
  408. if([[view.class description] hasPrefix:@"WK"])
  409. subview = view;
  410. }
  411. if(subview == nil) return;
  412. Class class = subview.class;
  413. NSOperatingSystemVersion iOS_11_3_0 = (NSOperatingSystemVersion){11, 3, 0};
  414. NSOperatingSystemVersion iOS_12_2_0 = (NSOperatingSystemVersion){12, 2, 0};
  415. NSOperatingSystemVersion iOS_13_0_0 = (NSOperatingSystemVersion){13, 0, 0};
  416. Method method;
  417. IMP override;
  418. if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_13_0_0]) {
  419. // iOS 13.0.0 - Future
  420. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:activityStateChanges:userObject:");
  421. method = class_getInstanceMethod(class, selector);
  422. IMP original = method_getImplementation(method);
  423. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  424. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  425. });
  426. }
  427. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_12_2_0]) {
  428. // iOS 12.2.0 - iOS 13.0.0
  429. SEL selector = sel_getUid("_elementDidFocus:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  430. method = class_getInstanceMethod(class, selector);
  431. IMP original = method_getImplementation(method);
  432. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  433. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  434. });
  435. }
  436. else if ([[NSProcessInfo processInfo] isOperatingSystemAtLeastVersion: iOS_11_3_0]) {
  437. // iOS 11.3.0 - 12.2.0
  438. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode:changingActivityState:userObject:");
  439. method = class_getInstanceMethod(class, selector);
  440. IMP original = method_getImplementation(method);
  441. override = imp_implementationWithBlock(^void(id me, void* arg0, BOOL arg1, BOOL arg2, BOOL arg3, id arg4) {
  442. ((void (*)(id, SEL, void*, BOOL, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3, arg4);
  443. });
  444. } else {
  445. // iOS 9.0 - 11.3.0
  446. SEL selector = sel_getUid("_startAssistingNode:userIsInteracting:blurPreviousNode: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, id arg3) {
  450. ((void (*)(id, SEL, void*, BOOL, BOOL, id))original)(me, selector, arg0, TRUE, arg2, arg3);
  451. });
  452. }
  453. method_setImplementation(method, override);
  454. }
  455. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  456. {
  457. if (_webView == nil) {
  458. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  459. return;
  460. }
  461. if (_savedHideKeyboardAccessoryView == false) {
  462. return;
  463. }
  464. UIView* subview;
  465. for (UIView* view in _webView.scrollView.subviews) {
  466. if([[view.class description] hasPrefix:@"WK"])
  467. subview = view;
  468. }
  469. if(subview == nil) return;
  470. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  471. Class newClass = NSClassFromString(name);
  472. if(newClass == nil)
  473. {
  474. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  475. if(!newClass) return;
  476. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  477. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  478. objc_registerClassPair(newClass);
  479. }
  480. object_setClass(subview, newClass);
  481. }
  482. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  483. {
  484. scrollView.decelerationRate = _decelerationRate;
  485. }
  486. - (void)setScrollEnabled:(BOOL)scrollEnabled
  487. {
  488. _scrollEnabled = scrollEnabled;
  489. _webView.scrollView.scrollEnabled = scrollEnabled;
  490. }
  491. - (void)scrollViewDidScroll:(UIScrollView *)scrollView
  492. {
  493. // Don't allow scrolling the scrollView.
  494. if (!_scrollEnabled) {
  495. scrollView.bounds = _webView.bounds;
  496. }
  497. else if (_onScroll != nil) {
  498. NSDictionary *event = @{
  499. @"contentOffset": @{
  500. @"x": @(scrollView.contentOffset.x),
  501. @"y": @(scrollView.contentOffset.y)
  502. },
  503. @"contentInset": @{
  504. @"top": @(scrollView.contentInset.top),
  505. @"left": @(scrollView.contentInset.left),
  506. @"bottom": @(scrollView.contentInset.bottom),
  507. @"right": @(scrollView.contentInset.right)
  508. },
  509. @"contentSize": @{
  510. @"width": @(scrollView.contentSize.width),
  511. @"height": @(scrollView.contentSize.height)
  512. },
  513. @"layoutMeasurement": @{
  514. @"width": @(scrollView.frame.size.width),
  515. @"height": @(scrollView.frame.size.height)
  516. },
  517. @"zoomScale": @(scrollView.zoomScale ?: 1),
  518. };
  519. _onScroll(event);
  520. }
  521. }
  522. - (void)setDirectionalLockEnabled:(BOOL)directionalLockEnabled
  523. {
  524. _directionalLockEnabled = directionalLockEnabled;
  525. _webView.scrollView.directionalLockEnabled = directionalLockEnabled;
  526. }
  527. - (void)setShowsHorizontalScrollIndicator:(BOOL)showsHorizontalScrollIndicator
  528. {
  529. _showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  530. _webView.scrollView.showsHorizontalScrollIndicator = showsHorizontalScrollIndicator;
  531. }
  532. - (void)setShowsVerticalScrollIndicator:(BOOL)showsVerticalScrollIndicator
  533. {
  534. _showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  535. _webView.scrollView.showsVerticalScrollIndicator = showsVerticalScrollIndicator;
  536. }
  537. - (void)postMessage:(NSString *)message
  538. {
  539. NSDictionary *eventInitDict = @{@"data": message};
  540. NSString *source = [NSString
  541. stringWithFormat:@"window.dispatchEvent(new MessageEvent('message', %@));",
  542. RCTJSONStringify(eventInitDict, NULL)
  543. ];
  544. [self injectJavaScript: source];
  545. }
  546. - (void)layoutSubviews
  547. {
  548. [super layoutSubviews];
  549. // Ensure webview takes the position and dimensions of RNCWebView
  550. _webView.frame = self.bounds;
  551. _webView.scrollView.contentInset = _contentInset;
  552. }
  553. - (NSMutableDictionary<NSString *, id> *)baseEvent
  554. {
  555. NSDictionary *event = @{
  556. @"url": _webView.URL.absoluteString ?: @"",
  557. @"title": _webView.title ?: @"",
  558. @"loading" : @(_webView.loading),
  559. @"canGoBack": @(_webView.canGoBack),
  560. @"canGoForward" : @(_webView.canGoForward)
  561. };
  562. return [[NSMutableDictionary alloc] initWithDictionary: event];
  563. }
  564. + (void)setClientAuthenticationCredential:(nullable NSURLCredential*)credential {
  565. clientAuthenticationCredential = credential;
  566. }
  567. - (void) webView:(WKWebView *)webView
  568. didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
  569. completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable))completionHandler
  570. {
  571. if (!clientAuthenticationCredential) {
  572. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  573. return;
  574. }
  575. if ([[challenge protectionSpace] authenticationMethod] == NSURLAuthenticationMethodClientCertificate) {
  576. completionHandler(NSURLSessionAuthChallengeUseCredential, clientAuthenticationCredential);
  577. } else {
  578. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
  579. }
  580. }
  581. #pragma mark - WKNavigationDelegate methods
  582. /**
  583. * alert
  584. */
  585. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  586. {
  587. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  588. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  589. completionHandler();
  590. }]];
  591. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  592. }
  593. /**
  594. * confirm
  595. */
  596. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  597. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  598. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  599. completionHandler(YES);
  600. }]];
  601. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  602. completionHandler(NO);
  603. }]];
  604. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  605. }
  606. /**
  607. * prompt
  608. */
  609. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  610. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  611. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  612. textField.text = defaultText;
  613. }];
  614. UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  615. completionHandler([[alert.textFields lastObject] text]);
  616. }];
  617. [alert addAction:okAction];
  618. UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  619. completionHandler(nil);
  620. }];
  621. [alert addAction:cancelAction];
  622. alert.preferredAction = okAction;
  623. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  624. }
  625. /**
  626. * topViewController
  627. */
  628. -(UIViewController *)topViewController{
  629.    UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  630.    return controller;
  631. }
  632. /**
  633. * topViewControllerWithRootViewController
  634. */
  635. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  636. if (viewController==nil) return nil;
  637. if (viewController.presentedViewController!=nil) {
  638. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  639. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  640. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  641. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  642. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  643. } else {
  644. return viewController;
  645. }
  646. }
  647. /**
  648. * getCurrentWindow
  649. */
  650. -(UIWindow *)getCurrentWindow{
  651. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  652. if (window.windowLevel!=UIWindowLevelNormal) {
  653. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  654. if (window.windowLevel==UIWindowLevelNormal) {
  655. window = wid;
  656. break;
  657. }
  658. }
  659. }
  660. return window;
  661. }
  662. /**
  663. * Decides whether to allow or cancel a navigation.
  664. * @see https://fburl.com/42r9fxob
  665. */
  666. - (void) webView:(WKWebView *)webView
  667. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  668. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  669. {
  670. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  671. static dispatch_once_t onceToken;
  672. dispatch_once(&onceToken, ^{
  673. navigationTypes = @{
  674. @(WKNavigationTypeLinkActivated): @"click",
  675. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  676. @(WKNavigationTypeBackForward): @"backforward",
  677. @(WKNavigationTypeReload): @"reload",
  678. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  679. @(WKNavigationTypeOther): @"other",
  680. };
  681. });
  682. WKNavigationType navigationType = navigationAction.navigationType;
  683. NSURLRequest *request = navigationAction.request;
  684. if (_onShouldStartLoadWithRequest) {
  685. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  686. [event addEntriesFromDictionary: @{
  687. @"url": (request.URL).absoluteString,
  688. @"mainDocumentURL": (request.mainDocumentURL).absoluteString,
  689. @"navigationType": navigationTypes[@(navigationType)]
  690. }];
  691. if (![self.delegate webView:self
  692. shouldStartLoadForRequest:event
  693. withCallback:_onShouldStartLoadWithRequest]) {
  694. decisionHandler(WKNavigationResponsePolicyCancel);
  695. return;
  696. }
  697. }
  698. if (_onLoadingStart) {
  699. // We have this check to filter out iframe requests and whatnot
  700. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  701. if (isTopFrame) {
  702. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  703. [event addEntriesFromDictionary: @{
  704. @"url": (request.URL).absoluteString,
  705. @"navigationType": navigationTypes[@(navigationType)]
  706. }];
  707. _onLoadingStart(event);
  708. }
  709. }
  710. // Allow all navigation by default
  711. decisionHandler(WKNavigationResponsePolicyAllow);
  712. }
  713. /**
  714. * Called when an error occurs while the web view is loading content.
  715. * @see https://fburl.com/km6vqenw
  716. */
  717. - (void) webView:(WKWebView *)webView
  718. didFailProvisionalNavigation:(WKNavigation *)navigation
  719. withError:(NSError *)error
  720. {
  721. if (_onLoadingError) {
  722. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  723. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  724. // a new URL in the WebView before the previous one came back. We can just
  725. // ignore these since they aren't real errors.
  726. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  727. return;
  728. }
  729. if ([error.domain isEqualToString:@"WebKitErrorDomain"] && error.code == 102) {
  730. // Error code 102 "Frame load interrupted" is raised by the WKWebView
  731. // when the URL is from an http redirect. This is a common pattern when
  732. // implementing OAuth with a WebView.
  733. return;
  734. }
  735. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  736. [event addEntriesFromDictionary:@{
  737. @"didFailProvisionalNavigation": @YES,
  738. @"domain": error.domain,
  739. @"code": @(error.code),
  740. @"description": error.localizedDescription,
  741. }];
  742. _onLoadingError(event);
  743. }
  744. [self setBackgroundColor: _savedBackgroundColor];
  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. [self setBackgroundColor: _savedBackgroundColor];
  777. }
  778. - (void)injectJavaScript:(NSString *)script
  779. {
  780. [self evaluateJS: script thenCall: nil];
  781. }
  782. - (void)goForward
  783. {
  784. [_webView goForward];
  785. }
  786. - (void)goBack
  787. {
  788. [_webView goBack];
  789. }
  790. - (void)reload
  791. {
  792. /**
  793. * When the initial load fails due to network connectivity issues,
  794. * [_webView reload] doesn't reload the webpage. Therefore, we must
  795. * manually call [_webView loadRequest:request].
  796. */
  797. NSURLRequest *request = [self requestForSource:self.source];
  798. if (request.URL && !_webView.URL.absoluteString.length) {
  799. [_webView loadRequest:request];
  800. } else {
  801. [_webView reload];
  802. }
  803. }
  804. - (void)stopLoading
  805. {
  806. [_webView stopLoading];
  807. }
  808. - (void)setBounces:(BOOL)bounces
  809. {
  810. _bounces = bounces;
  811. _webView.scrollView.bounces = bounces;
  812. }
  813. - (NSURLRequest *)requestForSource:(id)json {
  814. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  815. // If sharedCookiesEnabled we automatically add all application cookies to the
  816. // http request. This is automatically done on iOS 11+ in the WebView constructor.
  817. // Se we need to manually add these shared cookies here only for iOS versions < 11.
  818. if (_sharedCookiesEnabled) {
  819. if (@available(iOS 11.0, *)) {
  820. // see WKWebView initialization for added cookies
  821. } else {
  822. NSArray *cookies = [[NSHTTPCookieStorage sharedHTTPCookieStorage] cookiesForURL:request.URL];
  823. NSDictionary<NSString *, NSString *> *cookieHeader = [NSHTTPCookie requestHeaderFieldsWithCookies:cookies];
  824. NSMutableURLRequest *mutableRequest = [request mutableCopy];
  825. [mutableRequest setAllHTTPHeaderFields:cookieHeader];
  826. return mutableRequest;
  827. }
  828. }
  829. return request;
  830. }
  831. @end