react-native-webview.git

RNCWKWebView.m 32KB

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