react-native-webview.git

RNCWKWebView.m 27KB

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