react-native-webview.git

RNCWKWebView.m 16KB

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