react-native-webview.git

RNCWKWebView.m 12KB

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