react-native-webview.git

RNCWKWebView.m 15KB

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