Ingen beskrivning

RNCWKWebView.m 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  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 && _webView == 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. _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. } else {
  103. [_webView.configuration.userContentController removeScriptMessageHandlerForName:MessageHanderName];
  104. }
  105. }
  106. - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{
  107. if ([keyPath isEqual:@"estimatedProgress"] && object == self.webView) {
  108. if(_onLoadingProgress){
  109. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  110. [event addEntriesFromDictionary:@{@"progress":[NSNumber numberWithDouble:self.webView.estimatedProgress]}];
  111. _onLoadingProgress(event);
  112. }
  113. }else{
  114. [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
  115. }
  116. }
  117. - (void)setBackgroundColor:(UIColor *)backgroundColor
  118. {
  119. _savedBackgroundColor = backgroundColor;
  120. if (_webView == nil) {
  121. return;
  122. }
  123. CGFloat alpha = CGColorGetAlpha(backgroundColor.CGColor);
  124. self.opaque = _webView.opaque = (alpha == 1.0);
  125. _webView.scrollView.backgroundColor = backgroundColor;
  126. _webView.backgroundColor = backgroundColor;
  127. }
  128. /**
  129. * This method is called whenever JavaScript running within the web view calls:
  130. * - window.webkit.messageHandlers.[MessageHanderName].postMessage
  131. */
  132. - (void)userContentController:(WKUserContentController *)userContentController
  133. didReceiveScriptMessage:(WKScriptMessage *)message
  134. {
  135. if (_onMessage != nil) {
  136. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  137. [event addEntriesFromDictionary: @{@"data": message.body}];
  138. _onMessage(event);
  139. }
  140. }
  141. - (void)setSource:(NSDictionary *)source
  142. {
  143. if (![_source isEqualToDictionary:source]) {
  144. _source = [source copy];
  145. if (_webView != nil) {
  146. [self visitSource];
  147. }
  148. }
  149. }
  150. - (void)setContentInset:(UIEdgeInsets)contentInset
  151. {
  152. _contentInset = contentInset;
  153. [RCTView autoAdjustInsetsForView:self
  154. withScrollView:_webView.scrollView
  155. updateOffset:NO];
  156. }
  157. - (void)refreshContentInset
  158. {
  159. [RCTView autoAdjustInsetsForView:self
  160. withScrollView:_webView.scrollView
  161. updateOffset:YES];
  162. }
  163. - (void)visitSource
  164. {
  165. // Check for a static html source first
  166. NSString *html = [RCTConvert NSString:_source[@"html"]];
  167. if (html) {
  168. NSURL *baseURL = [RCTConvert NSURL:_source[@"baseUrl"]];
  169. if (!baseURL) {
  170. baseURL = [NSURL URLWithString:@"about:blank"];
  171. }
  172. [_webView loadHTMLString:html baseURL:baseURL];
  173. return;
  174. }
  175. NSURLRequest *request = [RCTConvert NSURLRequest:_source];
  176. // Because of the way React works, as pages redirect, we actually end up
  177. // passing the redirect urls back here, so we ignore them if trying to load
  178. // the same url. We'll expose a call to 'reload' to allow a user to load
  179. // the existing page.
  180. if ([request.URL isEqual:_webView.URL]) {
  181. return;
  182. }
  183. if (!request.URL) {
  184. // Clear the webview
  185. [_webView loadHTMLString:@"" baseURL:nil];
  186. return;
  187. }
  188. [_webView loadRequest:request];
  189. }
  190. -(void)setHideKeyboardAccessoryView:(BOOL)hideKeyboardAccessoryView
  191. {
  192. if (_webView == nil) {
  193. _savedHideKeyboardAccessoryView = hideKeyboardAccessoryView;
  194. return;
  195. }
  196. if (_savedHideKeyboardAccessoryView == false) {
  197. return;
  198. }
  199. UIView* subview;
  200. for (UIView* view in _webView.scrollView.subviews) {
  201. if([[view.class description] hasPrefix:@"WK"])
  202. subview = view;
  203. }
  204. if(subview == nil) return;
  205. NSString* name = [NSString stringWithFormat:@"%@_SwizzleHelperWK", subview.class.superclass];
  206. Class newClass = NSClassFromString(name);
  207. if(newClass == nil)
  208. {
  209. newClass = objc_allocateClassPair(subview.class, [name cStringUsingEncoding:NSASCIIStringEncoding], 0);
  210. if(!newClass) return;
  211. Method method = class_getInstanceMethod([_SwizzleHelperWK class], @selector(inputAccessoryView));
  212. class_addMethod(newClass, @selector(inputAccessoryView), method_getImplementation(method), method_getTypeEncoding(method));
  213. objc_registerClassPair(newClass);
  214. }
  215. object_setClass(subview, newClass);
  216. }
  217. - (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
  218. {
  219. scrollView.decelerationRate = _decelerationRate;
  220. }
  221. - (void)setScrollEnabled:(BOOL)scrollEnabled
  222. {
  223. _scrollEnabled = scrollEnabled;
  224. _webView.scrollView.scrollEnabled = scrollEnabled;
  225. }
  226. - (void)postMessage:(NSString *)message
  227. {
  228. NSDictionary *eventInitDict = @{@"data": message};
  229. NSString *source = [NSString
  230. stringWithFormat:@"document.dispatchEvent(new MessageEvent('message', %@));",
  231. RCTJSONStringify(eventInitDict, NULL)
  232. ];
  233. [self evaluateJS: source thenCall: nil];
  234. }
  235. - (void)layoutSubviews
  236. {
  237. [super layoutSubviews];
  238. // Ensure webview takes the position and dimensions of RNCWKWebView
  239. _webView.frame = self.bounds;
  240. }
  241. - (NSMutableDictionary<NSString *, id> *)baseEvent
  242. {
  243. NSDictionary *event = @{
  244. @"url": _webView.URL.absoluteString ?: @"",
  245. @"title": _webView.title,
  246. @"loading" : @(_webView.loading),
  247. @"canGoBack": @(_webView.canGoBack),
  248. @"canGoForward" : @(_webView.canGoForward)
  249. };
  250. return [[NSMutableDictionary alloc] initWithDictionary: event];
  251. }
  252. #pragma mark - WKNavigationDelegate methods
  253. /**
  254. * Decides whether to allow or cancel a navigation.
  255. * @see https://fburl.com/42r9fxob
  256. */
  257. - (void) webView:(WKWebView *)webView
  258. decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction
  259. decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
  260. {
  261. static NSDictionary<NSNumber *, NSString *> *navigationTypes;
  262. static dispatch_once_t onceToken;
  263. dispatch_once(&onceToken, ^{
  264. navigationTypes = @{
  265. @(WKNavigationTypeLinkActivated): @"click",
  266. @(WKNavigationTypeFormSubmitted): @"formsubmit",
  267. @(WKNavigationTypeBackForward): @"backforward",
  268. @(WKNavigationTypeReload): @"reload",
  269. @(WKNavigationTypeFormResubmitted): @"formresubmit",
  270. @(WKNavigationTypeOther): @"other",
  271. };
  272. });
  273. WKNavigationType navigationType = navigationAction.navigationType;
  274. NSURLRequest *request = navigationAction.request;
  275. if (_onShouldStartLoadWithRequest) {
  276. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  277. [event addEntriesFromDictionary: @{
  278. @"url": (request.URL).absoluteString,
  279. @"navigationType": navigationTypes[@(navigationType)]
  280. }];
  281. if (![self.delegate webView:self
  282. shouldStartLoadForRequest:event
  283. withCallback:_onShouldStartLoadWithRequest]) {
  284. decisionHandler(WKNavigationResponsePolicyCancel);
  285. return;
  286. }
  287. }
  288. if (_onLoadingStart) {
  289. // We have this check to filter out iframe requests and whatnot
  290. BOOL isTopFrame = [request.URL isEqual:request.mainDocumentURL];
  291. if (isTopFrame) {
  292. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  293. [event addEntriesFromDictionary: @{
  294. @"url": (request.URL).absoluteString,
  295. @"navigationType": navigationTypes[@(navigationType)]
  296. }];
  297. _onLoadingStart(event);
  298. }
  299. }
  300. // Allow all navigation by default
  301. decisionHandler(WKNavigationResponsePolicyAllow);
  302. }
  303. /**
  304. * Called when an error occurs while the web view is loading content.
  305. * @see https://fburl.com/km6vqenw
  306. */
  307. - (void) webView:(WKWebView *)webView
  308. didFailProvisionalNavigation:(WKNavigation *)navigation
  309. withError:(NSError *)error
  310. {
  311. if (_onLoadingError) {
  312. if ([error.domain isEqualToString:NSURLErrorDomain] && error.code == NSURLErrorCancelled) {
  313. // NSURLErrorCancelled is reported when a page has a redirect OR if you load
  314. // a new URL in the WebView before the previous one came back. We can just
  315. // ignore these since they aren't real errors.
  316. // http://stackoverflow.com/questions/1024748/how-do-i-fix-nsurlerrordomain-error-999-in-iphone-3-0-os
  317. return;
  318. }
  319. NSMutableDictionary<NSString *, id> *event = [self baseEvent];
  320. [event addEntriesFromDictionary:@{
  321. @"didFailProvisionalNavigation": @YES,
  322. @"domain": error.domain,
  323. @"code": @(error.code),
  324. @"description": error.localizedDescription,
  325. }];
  326. _onLoadingError(event);
  327. }
  328. [self setBackgroundColor: _savedBackgroundColor];
  329. }
  330. - (void)evaluateJS:(NSString *)js
  331. thenCall: (void (^)(NSString*)) callback
  332. {
  333. [self.webView evaluateJavaScript: js completionHandler: ^(id result, NSError *error) {
  334. if (error == nil && callback != nil) {
  335. callback([NSString stringWithFormat:@"%@", result]);
  336. }
  337. }];
  338. }
  339. /**
  340. * Called when the navigation is complete.
  341. * @see https://fburl.com/rtys6jlb
  342. */
  343. - (void) webView:(WKWebView *)webView
  344. didFinishNavigation:(WKNavigation *)navigation
  345. {
  346. if (_messagingEnabled) {
  347. #if RCT_DEV
  348. // Implementation inspired by Lodash.isNative.
  349. NSString *isPostMessageNative = @"String(String(window.postMessage) === String(Object.hasOwnProperty).replace('hasOwnProperty', 'postMessage'))";
  350. [self evaluateJS: isPostMessageNative thenCall: ^(NSString *result) {
  351. if (! [result isEqualToString:@"true"]) {
  352. RCTLogError(@"Setting onMessage on a WebView overrides existing values of window.postMessage, but a previous value was defined");
  353. }
  354. }];
  355. #endif
  356. NSString *source = [NSString stringWithFormat:
  357. @"(function() {"
  358. "window.originalPostMessage = window.postMessage;"
  359. "window.postMessage = function(data) {"
  360. "window.webkit.messageHandlers.%@.postMessage(String(data));"
  361. "};"
  362. "})();",
  363. MessageHanderName
  364. ];
  365. [self evaluateJS: source thenCall: nil];
  366. }
  367. if (_injectedJavaScript) {
  368. [self evaluateJS: _injectedJavaScript thenCall: ^(NSString *jsEvaluationValue) {
  369. NSMutableDictionary *event = [self baseEvent];
  370. event[@"jsEvaluationValue"] = jsEvaluationValue;
  371. if (self.onLoadingFinish) {
  372. self.onLoadingFinish(event);
  373. }
  374. }];
  375. } else if (_onLoadingFinish) {
  376. _onLoadingFinish([self baseEvent]);
  377. }
  378. [self setBackgroundColor: _savedBackgroundColor];
  379. }
  380. - (void)injectJavaScript:(NSString *)script
  381. {
  382. [self evaluateJS: script thenCall: nil];
  383. }
  384. - (void)goForward
  385. {
  386. [_webView goForward];
  387. }
  388. - (void)goBack
  389. {
  390. [_webView goBack];
  391. }
  392. - (void)reload
  393. {
  394. /**
  395. * When the initial load fails due to network connectivity issues,
  396. * [_webView reload] doesn't reload the webpage. Therefore, we must
  397. * manually call [_webView loadRequest:request].
  398. */
  399. NSURLRequest *request = [RCTConvert NSURLRequest:self.source];
  400. if (request.URL && !_webView.URL.absoluteString.length) {
  401. [_webView loadRequest:request];
  402. }
  403. else {
  404. [_webView reload];
  405. }
  406. }
  407. - (void)stopLoading
  408. {
  409. [_webView stopLoading];
  410. }
  411. - (void)setBounces:(BOOL)bounces
  412. {
  413. _bounces = bounces;
  414. _webView.scrollView.bounces = bounces;
  415. }
  416. @end