説明なし

RNCWKWebView.m 13KB

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