No Description

RNCWKWebView.m 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  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 <UIKit/UIKit.h>
  11. #import "objc/runtime.h"
  12. static NSString *const MessageHanderName = @"ReactNative";
  13. // runtime trick to remove WKWebView keyboard default toolbar
  14. // see: http://stackoverflow.com/questions/19033292/ios-7-uiwebview-keyboard-issue/19042279#19042279
  15. @interface _SwizzleHelperWK : NSObject @end
  16. @implementation _SwizzleHelperWK
  17. -(id)inputAccessoryView
  18. {
  19. return nil;
  20. }
  21. @end
  22. @interface RNCWKWebView () <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler, UIScrollViewDelegate, RCTAutoInsetsProtocol>
  23. @property (nonatomic, copy) RCTDirectEventBlock onLoadingStart;
  24. @property (nonatomic, copy) RCTDirectEventBlock onLoadingFinish;
  25. @property (nonatomic, copy) RCTDirectEventBlock onLoadingError;
  26. @property (nonatomic, copy) RCTDirectEventBlock onLoadingProgress;
  27. @property (nonatomic, copy) RCTDirectEventBlock onShouldStartLoadWithRequest;
  28. @property (nonatomic, copy) RCTDirectEventBlock onMessage;
  29. @property (nonatomic, copy) WKWebView *webView;
  30. @end
  31. @implementation RNCWKWebView
  32. {
  33. UIColor * _savedBackgroundColor;
  34. BOOL _savedHideKeyboardAccessoryView;
  35. }
  36. - (void)dealloc{}
  37. /**
  38. * See https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/WebKitAvail.html.
  39. */
  40. + (BOOL)dynamicallyLoadWebKitIfAvailable
  41. {
  42. static BOOL _webkitAvailable=NO;
  43. static dispatch_once_t onceToken;
  44. dispatch_once(&onceToken, ^{
  45. NSBundle *webKitBundle = [NSBundle bundleWithPath:@"/System/Library/Frameworks/WebKit.framework"];
  46. if (webKitBundle) {
  47. _webkitAvailable = [webKitBundle load];
  48. }
  49. });
  50. return _webkitAvailable;
  51. }
  52. - (instancetype)initWithFrame:(CGRect)frame
  53. {
  54. if ((self = [super initWithFrame:frame])) {
  55. super.backgroundColor = [UIColor clearColor];
  56. _bounces = YES;
  57. _scrollEnabled = YES;
  58. _automaticallyAdjustContentInsets = YES;
  59. _contentInset = UIEdgeInsetsZero;
  60. }
  61. return self;
  62. }
  63. - (void)didMoveToWindow
  64. {
  65. if (self.window != nil && _webView == nil) {
  66. if (![[self class] dynamicallyLoadWebKitIfAvailable]) {
  67. return;
  68. };
  69. WKWebViewConfiguration *wkWebViewConfig = [WKWebViewConfiguration new];
  70. wkWebViewConfig.userContentController = [WKUserContentController new];
  71. [wkWebViewConfig.userContentController addScriptMessageHandler: self name: MessageHanderName];
  72. wkWebViewConfig.allowsInlineMediaPlayback = _allowsInlineMediaPlayback;
  73. #if WEBKIT_IOS_10_APIS_AVAILABLE
  74. wkWebViewConfig.mediaTypesRequiringUserActionForPlayback = _mediaPlaybackRequiresUserAction
  75. ? WKAudiovisualMediaTypeAll
  76. : WKAudiovisualMediaTypeNone;
  77. wkWebViewConfig.dataDetectorTypes = _dataDetectorTypes;
  78. #else
  79. wkWebViewConfig.mediaPlaybackRequiresUserAction = _mediaPlaybackRequiresUserAction;
  80. #endif
  81. _webView = [[WKWebView alloc] initWithFrame:self.bounds configuration: wkWebViewConfig];
  82. _webView.scrollView.delegate = self;
  83. _webView.UIDelegate = self;
  84. _webView.navigationDelegate = self;
  85. _webView.scrollView.scrollEnabled = _scrollEnabled;
  86. _webView.scrollView.pagingEnabled = _pagingEnabled;
  87. _webView.scrollView.bounces = _bounces;
  88. _webView.allowsLinkPreview = _allowsLinkPreview;
  89. [_webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew context:nil];
  90. _webView.allowsBackForwardNavigationGestures = _allowsBackForwardNavigationGestures;
  91. if (_userAgent) {
  92. _webView.customUserAgent = _userAgent;
  93. }
  94. #if defined(__IPHONE_OS_VERSION_MAX_ALLOWED) && __IPHONE_OS_VERSION_MAX_ALLOWED >= 110000 /* __IPHONE_11_0 */
  95. if ([_webView.scrollView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
  96. _webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
  97. }
  98. #endif
  99. [self addSubview:_webView];
  100. [self setHideKeyboardAccessoryView: _savedHideKeyboardAccessoryView];
  101. [self visitSource];
  102. }
  103. }
  104. - (void)removeFromSuperview
  105. {
  106. if (_webView) {
  107. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHanderName];
  108. [_webView removeObserver:self forKeyPath:@"estimatedProgress"];
  109. [_webView removeFromSuperview];
  110. _webView = nil;
  111. }
  112. [super removeFromSuperview];
  113. }
  114. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  115. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  116. if(_onLoadingProgress){
  117. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  118. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  119. _onLoadingProgress(event);
  120. }
  121. }else{
  122. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  123. }
  124. }
  125. - (void)setBackgroundColor:(UIColor *)backgroundColor
  126. {
  127. _savedBackgroundColor = backgroundColor;
  128. if (_webView == nil) {
  129. return;
  130. }
  131. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  132. self.opaque = _webView.opaque = (alpha == 1.0);
  133. _webView.scrollView.backgroundColor = backgroundColor;
  134. _webView.backgroundColor = backgroundColor;
  135. }
  136. /**
  137. * This method is called whenever JavaScript running within the web view calls:
  138. * - window.webkit.messageHandlers.[MessageHanderName].postMessage
  139. */
  140. - (void)userContentController:(WKUserContentController *)userContentController
  141. didReceiveScriptMessage:(WKScriptMessage *)message
  142. {
  143. if (_onMessage != nil) {
  144. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  145. [event addEntriesFromDictionary: @{@"data": message.body}];
  146. _onMessage(event);
  147. }
  148. }
  149. - (void)setSource:(NSDictionary *)source
  150. {
  151. if (![_source isEqualToDictionary:source]) {
  152. _source = [source copy];
  153. if (_webView != nil) {
  154. [self visitSource];
  155. }
  156. }
  157. }
  158. - (void)setContentInset:(UIEdgeInsets)contentInset
  159. {
  160. _contentInset = contentInset;
  161. [RCTView autoAdjustInsetsForView:self
  162. withScrollView:_webView.scrollView
  163. updateOffset:NO];
  164. }
  165. - (void)refreshContentInset
  166. {
  167. [RCTView autoAdjustInsetsForView:self
  168. withScrollView:_webView.scrollView
  169. updateOffset:YES];
  170. }
  171. - (void)visitSource
  172. {
  173. // Check for a static html source first
  174. NSString *html = [RCTConvert NSString:_source[@"html"]];
  175. if (html) {
  176. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  177. if (!baseURL) {
  178. baseURL = [NSURL URLWithString:@"about:blank"];
  179. }
  180. [_webView loadHTMLString:html baseURL:baseURL];
  181. return;
  182. }
  183. NSURLRequest *request = [RCTConvert NSURLRequest:_source];
  184. // Because of the way React works, as pages redirect, we actually end up
  185. // passing the redirect urls back here, so we ignore them if trying to load
  186. // the same url. We'll expose a call to 'reload' to allow a user to load
  187. // the existing page.
  188. if ([request.URL isEqual:_webView.URL]) {
  189. return;
  190. }
  191. if (!request.URL) {
  192. // Clear the webview
  193. [_webView loadHTMLString:@"" baseURL:nil];
  194. return;
  195. }
  196. [_webView loadRequest:request];
  197. }
  198. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  199. {
  200. if (_webView == nil) {
  201. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  202. return;
  203. }
  204. if (_savedHideKeyboardAccessoryView == false) {
  205. return;
  206. }
  207. UIView* subview;
  208. for (UIView* view in _webView.scrollView.subviews) {
  209. if([[view.class description] hasPrefix:@"WK"])
  210. subview = view;
  211. }
  212. if(subview == nil) return;
  213. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  214. Class newClass = NSClassFromString(name);
  215. if(newClass == nil)
  216. {
  217. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  218. if(!newClass) return;
  219. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  220. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  221. objc_registerClassPair(newClass);
  222. }
  223. object_setClass(subview, newClass);
  224. }
  225. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  226. {
  227. scrollView.decelerationRate = _decelerationRate;
  228. }
  229. - (void)setScrollEnabled:(BOOL)scrollEnabled
  230. {
  231. _scrollEnabled = scrollEnabled;
  232. _webView.scrollView.scrollEnabled = scrollEnabled;
  233. }
  234. - (void)postMessage:(NSString *)message
  235. {
  236. NSDictionary *eventInitDict = @{@"data": message};
  237. NSString *source = [NSString
  238. stringWithFormat:@"document.dispatchEvent(new MessageEvent('message', %@));",
  239. RCTJSONStringify(eventInitDict, NULL)
  240. ];
  241. [self evaluateJS: source thenCall: nil];
  242. }
  243. - (void)layoutSubviews
  244. {
  245. [super layoutSubviews];
  246. // Ensure webview takes the position and dimensions of RNCWKWebView
  247. _webView.frame = self.bounds;
  248. }
  249. - (NSMutableDictionary<NSString *, id> *)baseEvent
  250. {
  251. NSDictionary *event = @{
  252. @"url": _webView.URL.absoluteString ?: @"",
  253. @"title": _webView.title,
  254. @"loading" : @(_webView.loading),
  255. @"canGoBack": @(_webView.canGoBack),
  256. @"canGoForward" : @(_webView.canGoForward)
  257. };
  258. return [[NSMutableDictionary alloc] initWithDictionary: event];
  259. }
  260. #pragma mark - WKNavigationDelegate methods
  261. /**
  262. * alert
  263. */
  264. - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
  265. {
  266. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  267. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  268. completionHandler();
  269. }]];
  270. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  271. }
  272. /**
  273. * confirm
  274. */
  275. - (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
  276. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:message preferredStyle:UIAlertControllerStyleAlert];
  277. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  278. completionHandler(YES);
  279. }]];
  280. [alert addAction:[UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action) {
  281. completionHandler(NO);
  282. }]];
  283. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  284. }
  285. /**
  286. * prompt
  287. */
  288. - (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString *))completionHandler{
  289. UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"" message:prompt preferredStyle:UIAlertControllerStyleAlert];
  290. [alert addTextFieldWithConfigurationHandler:^(UITextField *textField) {
  291. textField.textColor = [UIColor lightGrayColor];
  292. textField.placeholder = defaultText;
  293. }];
  294. [alert addAction:[UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
  295. completionHandler([[alert.textFields lastObject] text]);
  296. }]];
  297. [[self topViewController] presentViewController:alert animated:YES completion:NULL];
  298. }
  299. /**
  300. * topViewController
  301. */
  302. -(UIViewController *)topViewController{
  303.    UIViewController *controller = [self topViewControllerWithRootViewController:[self getCurrentWindow].rootViewController];
  304.    return controller;
  305. }
  306. /**
  307. * topViewControllerWithRootViewController
  308. */
  309. -(UIViewController *)topViewControllerWithRootViewController:(UIViewController *)viewController{
  310. if (viewController==nil) return nil;
  311. if (viewController.presentedViewController!=nil) {
  312. return [self topViewControllerWithRootViewController:viewController.presentedViewController];
  313. } else if ([viewController isKindOfClass:[UITabBarController class]]){
  314. return [self topViewControllerWithRootViewController:[(UITabBarController *)viewController selectedViewController]];
  315. } else if ([viewController isKindOfClass:[UINavigationController class]]){
  316. return [self topViewControllerWithRootViewController:[(UINavigationController *)viewController visibleViewController]];
  317. } else {
  318. return viewController;
  319. }
  320. }
  321. /**
  322. * getCurrentWindow
  323. */
  324. -(UIWindow *)getCurrentWindow{
  325. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  326. if (window.windowLevel!=UIWindowLevelNormal) {
  327. for (UIWindow *wid in [UIApplication sharedApplication].windows) {
  328. if (window.windowLevel==UIWindowLevelNormal) {
  329. window = wid;
  330. break;
  331. }
  332. }
  333. }
  334. return window;
  335. }
  336. /**
  337. * Decides whether to allow or cancel a navigation.
  338. * @see https://fburl.com/42r9fxob
  339. */
  340. - (void) webView:(WKWebView *)webView
  341. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  342. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  343. {
  344. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  345. static dispatch_once_t onceToken;
  346. dispatch_once(&onceToken, ^{
  347. navigationTypes = @{
  348. @(WKNavigationTypeLinkActivated): @"click",
  349. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  350. @(WKNavigationTypeBackForward): @"backforward",
  351. @(WKNavigationTypeReload): @"reload",
  352. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  353. @(WKNavigationTypeOther): @"other",
  354. };
  355. });
  356. WKNavigationType navigationType = navigationAction.navigationType;
  357. NSURLRequest *request = navigationAction.request;
  358. if (_onShouldStartLoadWithRequest) {
  359. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  360. [event addEntriesFromDictionary: @{
  361. @"url": (request.URL).absoluteString,
  362. @"navigationType": navigationTypes[@(navigationType)]
  363. }];
  364. if (![self.delegate webView:self
  365. shouldStartLoadForRequest:event
  366. withCallback:_onShouldStartLoadWithRequest]) {
  367. decisionHandler(WKNavigationResponsePolicyCancel);
  368. return;
  369. }
  370. }
  371. if (_onLoadingStart) {
  372. // We have this check to filter out iframe requests and whatnot
  373. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  374. if (isTopFrame) {
  375. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  376. [event addEntriesFromDictionary: @{
  377. @"url": (request.URL).absoluteString,
  378. @"navigationType": navigationTypes[@(navigationType)]
  379. }];
  380. _onLoadingStart(event);
  381. }
  382. }
  383. // Allow all navigation by default
  384. decisionHandler(WKNavigationResponsePolicyAllow);
  385. }
  386. /**
  387. * Called when an error occurs while the web view is loading content.
  388. * @see https://fburl.com/km6vqenw
  389. */
  390. - (void) webView:(WKWebView *)webView
  391. didFailProvisionalNavigation:(WKNavigation *)navigation
  392. withError:(NSError *)error
  393. {
  394. if (_onLoadingError) {
  395. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  396. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  397. // a new URL in the WebView before the previous one came back. We can just
  398. // ignore these since they aren't real errors.
  399. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  400. return;
  401. }
  402. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  403. [event addEntriesFromDictionary:@{
  404. @"didFailProvisionalNavigation": @YES,
  405. @"domain": error.domain,
  406. @"code": @(error.code),
  407. @"description": error.localizedDescription,
  408. }];
  409. _onLoadingError(event);
  410. }
  411. [self setBackgroundColor: _savedBackgroundColor];
  412. }
  413. - (void)evaluateJS:(NSString *)js
  414. thenCall: (void (^)(NSString*)) callback
  415. {
  416. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  417. if (error == nil) {
  418. if (callback != nil) {
  419. callback([NSString stringWithFormat:@"%@", result]);
  420. }
  421. } else {
  422. RCTLogError(@"Error evaluating injectedJavaScript: This is possibly due to an unsupported return type. Try adding true to the end of your injectedJavaScript string.");
  423. }
  424. }];
  425. }
  426. /**
  427. * Called when the navigation is complete.
  428. * @see https://fburl.com/rtys6jlb
  429. */
  430. - (void) webView:(WKWebView *)webView
  431. didFinishNavigation:(WKNavigation *)navigation
  432. {
  433. if (_messagingEnabled) {
  434. #if RCT_DEV
  435. // Implementation inspired by Lodash.isNative.
  436. NSString *isPostMessageNative = @"String(String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage'))";
  437. [self evaluateJS: isPostMessageNative thenCall: ^(NSString *result) {
  438. if (! [result isEqualToString:@"true"]) {
  439. RCTLogError(@"Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
  440. }
  441. }];
  442. #endif
  443. NSString *source = [NSString stringWithFormat:
  444. @"(function() {"
  445. "window.originalPostMessage = window.postMessage;"
  446. "window.postMessage = function(data) {"
  447. "window.webkit.messageHandlers.%@.postMessage(String(data));"
  448. "};"
  449. "})();",
  450. MessageHanderName
  451. ];
  452. [self evaluateJS: source thenCall: nil];
  453. }
  454. if (_injectedJavaScript) {
  455. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  456. NSMutableDictionary *event = [self baseEvent];
  457. event[@"jsEvaluationValue"] = jsEvaluationValue;
  458. if (self.onLoadingFinish) {
  459. self.onLoadingFinish(event);
  460. }
  461. }];
  462. } else if (_onLoadingFinish) {
  463. _onLoadingFinish([self baseEvent]);
  464. }
  465. [self setBackgroundColor: _savedBackgroundColor];
  466. }
  467. - (void)injectJavaScript:(NSString *)script
  468. {
  469. [self evaluateJS: script thenCall: nil];
  470. }
  471. - (void)goForward
  472. {
  473. [_webView goForward];
  474. }
  475. - (void)goBack
  476. {
  477. [_webView goBack];
  478. }
  479. - (void)reload
  480. {
  481. /**
  482. * When the initial load fails due to network connectivity issues,
  483. * [_webView reload] doesn't reload the webpage. Therefore, we must
  484. * manually call [_webView loadRequest:request].
  485. */
  486. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  487. if (request.URL && !_webView.URL.absoluteString.length) {
  488. [_webView loadRequest:request];
  489. }
  490. else {
  491. [_webView reload];
  492. }
  493. }
  494. - (void)stopLoading
  495. {
  496. [_webView stopLoading];
  497. }
  498. - (void)setBounces:(BOOL)bounces
  499. {
  500. _bounces = bounces;
  501. _webView.scrollView.bounces = bounces;
  502. }
  503. @end