react-native-webview.git

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