react-native-webview.git

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