react-native-webview.git

RNCWKWebView.m 15KB

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