react-native-webview.git

RNCWKWebView.m 33KB

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