Nessuna descrizione

RNCWKWebView.m 14KB

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