react-native-webview.git

RNCWKWebView.m 12KB

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