Нема описа

RNCWKWebView.m 16KB

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