Няма описание

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