react-native-webview.git

RNCWebView.m 36KB

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