暂无描述

RNCWKWebView.m 16KB

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