No Description

RNCWKWebView.m 16KB

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