No Description

RNCWKWebView.m 16KB

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